Close Open Privacy Scan
App Privacy Score
High risk · 556 finding(s)
Dependency score: 37 (High risk)
bar_chart Score Breakdown
list Scan Summary
swap_horiz Confirmed data exfiltration in application code
External domains:
${a}?ns=${h.namespace}`,l=parseRepoInfo(o,i${e.authDomain}${e.config.authDomain}${e.host}${h}?ns=`+a.namespace,o=us(s,i${h}`${n}`${o}`${process.env.FIREBASE_STORAGE_EMULATOR_HOST}`;${r.authDomain}${this.region}-${t}.cloudfunctions.net${t}${s?`:${s}`:${t}`<YOURapis.google.comconsole.firebase.google.comfcmregistrations.googleapis.comfirebase.google.comfirebaseinstallations.googleapis.comfirebaseremoteconfig.googleapis.comfirebaseremoteconfigrealtime.googleapis.complay.google.comsecuretoken.google.comwww.google.comwww.gstatic.com
repo/pkgs/core/scripts/release/buildChangelog.ts:8 → repo/pkgs/core/scripts/release/buildChangelog.ts:55repo/pkgs/core/scripts/release/buildChangelog.ts:8 → repo/pkgs/core/scripts/release/buildChangelog.ts:55repo/pkgs/tz/playground.mjs:3 → repo/pkgs/tz/playground.mjs:1repo/pkgs/tz/playground.mjs:3 → repo/pkgs/tz/playground.mjs:1hub Dependency data flows (9)
pkgs/npm/[email protected]/firebase-messaging-compat.js:1 → pkgs/npm/[email protected]/firebase-messaging-compat.js:1pkgs/npm/[email protected]/firebase-messaging-compat.js:1 → pkgs/npm/[email protected]/firebase-messaging-compat.js:1pkgs/npm/[email protected]/firebase-messaging-sw.js:1 → pkgs/npm/[email protected]/firebase-messaging-sw.js:1pkgs/npm/[email protected]/firebase-messaging.js:1 → pkgs/npm/[email protected]/firebase-messaging.js:1pkgs/npm/[email protected]/firebase-remote-config-compat.js:1 → pkgs/npm/[email protected]/firebase-remote-config-compat.js:1pkgs/npm/[email protected]/firebase-remote-config-compat.js:1 → pkgs/npm/[email protected]/firebase-remote-config-compat.js:1pkgs/npm/[email protected]/firebase-remote-config.js:1 → pkgs/npm/[email protected]/firebase-remote-config.js:1pkgs/npm/[email protected]/lib/sendToCoveralls.js:9 → pkgs/npm/[email protected]/lib/sendToCoveralls.js:19</> First-Party Code
first-party (npm)
npm first-party gh
.request("GET /repos/{owner}/{repo}/commits/{ref}", {
owner: "date-fns",
repo: "date-fns",
ref: c.hash,
})
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
console.log(
`###### ${
process.env.TZ ||
Intl.DateTimeFormat("en-US", {
timeZoneName: "longGeneric",
})
.format(new Date())
.split(" ")
.slice(1)
.join(" ")
} ######`,
);
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
expand_more 27 low-confidence finding(s)
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return readFile(resolve(process.cwd(), "." + pathname));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
pkg = process.env.DATE_FNS_CDN_TEST_PKG || "@date-fns/cdn",
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readdir } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readdir } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readdir } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const gh = new Octokit({ auth: process.env.OCTOKIT_TOKEN });
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const dateFnsDir = process.env.DATE_FNS_DIR;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const packageJsonStr = await readFile(
path.resolve(dateFnsDir, "package.json"),
"utf-8",
);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const docsJsonStr = await readFile("tmp/docs.json", "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const packageStr = await readFile(packagePath, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const markdown = await readFile(
path.resolve(configDir, file.path),
"utf8",
);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const docsJSON = await readFile(jsonPath, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { copyFile, mkdir } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.TZ ||
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const code = await readFile(srcPath, "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { copyFile, mkdir } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
first-party (npm): pkgs/core
npm first-party gh
.request("GET /repos/{owner}/{repo}/commits/{ref}", {
owner: "date-fns",
repo: "date-fns",
ref: c.hash,
})
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
expand_more 13 low-confidence finding(s)
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return readFile(resolve(process.cwd(), "." + pathname));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
pkg = process.env.DATE_FNS_CDN_TEST_PKG || "@date-fns/cdn",
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readdir } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readdir } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readdir } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const gh = new Octokit({ auth: process.env.OCTOKIT_TOKEN });
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.tz;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
first-party (npm): pkgs/tz
npm first-partyconsole.log(
`###### ${
process.env.TZ ||
Intl.DateTimeFormat("en-US", {
timeZoneName: "longGeneric",
})
.format(new Date())
.split(" ")
.slice(1)
.join(" ")
} ######`,
);
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
expand_more 4 low-confidence finding(s)
import { copyFile, mkdir } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.TZ ||
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const code = await readFile(srcPath, "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
first-party (npm): pkgs/docs
npm first-partyexpand_more 9 low-confidence finding(s)
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const dateFnsDir = process.env.DATE_FNS_DIR;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const packageJsonStr = await readFile(
path.resolve(dateFnsDir, "package.json"),
"utf-8",
);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const docsJsonStr = await readFile("tmp/docs.json", "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const packageStr = await readFile(packagePath, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const markdown = await readFile(
path.resolve(configDir, file.path),
"utf8",
);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const docsJSON = await readFile(jsonPath, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
first-party (npm): pkgs/utc
npm first-partyexpand_more 1 low-confidence finding(s)
import { copyFile, mkdir } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
</> Dependencies
firebase
npm dependencyimport{_getProvider,_isFirebaseServerApp as e,_registerComponent as t,registerVersion as r,getApp as n,SDK_VERSION as i}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";const s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const i=e[t],s=t+1<e.length,o=s?e[t+1]:0,a=t+2<e.length,c=a?e[t+2]:0,u=i>>2,d=(3&i)<<4|o>>4;let l=(15&o)<<2|c>>6,h=63&c;a||(h=64,s||(l=64)),n.push(r[u],r[d],r[l],r[h])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=63&i|128):55296==(64512&i)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++n)),t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const i=e[r++];if(i<128)t[n++]=String.fromCharCode(i);else if(i>191&&i<224){const s=e[r++];t[n++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{const s=e[r++],o=e[r++];t[n++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const i=r[e.charAt(t++)],s=t<e.length?r[e.charAt(t)]:0;++t;const o=t<e.length?r[e.charAt(t)]:64;++t;const a=t<e.length?r[e.charAt(t)]:64;if(++t,null==i||null==s||null==o||null==a)throw new DecodeBase64StringError;const c=i<<2|s>>4;if(n.push(c),64!==o){const e=s<<4&240|o>>2;if(n.push(e),64!==a){const e=o<<6&192|a;n.push(e)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64Decode=function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&base64Decode(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getExperimentalSetting=e=>getDefaults()?.[`_${e}`];class Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,r)=>{t?this.reject(t):this.resolve(r),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,r))}}}function getUA(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,i=this.errors[e],s=i?function replaceTemplate(e,t){return e.replace(o,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(i,r):"Error",a=`${this.serviceName}: ${s} (${n}).`;return new FirebaseError(n,a,r)}}const o=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const r=Object.keys(e),n=Object.keys(t);for(const i of r){if(!n.includes(i))return!1;const r=e[i],s=t[i];if(isObject(r)&&isObject(s)){if(!deepEqual(r,s))return!1}else if(r!==s)return!1}for(const e of n)if(!r.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function querystring(e){const t=[];for(const[r,n]of Object.entries(e))Array.isArray(n)?n.forEach((e=>{t.push(encodeURIComponent(r)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(r)+"="+encodeURIComponent(n));return t.length?"&"+t.join("&"):""}function querystringDecode(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[r,n]=e.split("=");t[decodeURIComponent(r)]=decodeURIComponent(n)}})),t}function extractQuerystring(e){const t=e.indexOf("?");if(!t)return"";const r=e.indexOf("#",t);return e.substring(t,r>0?r:void 0)}class ObserverProxy{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,r){let n;if(void 0===e&&void 0===t&&void 0===r)throw new Error("Missing Observer.");n=function implementsAnyMethods(e,t){if("object"!=typeof e||null===e)return!1;for(const r of t)if(r in e&&"function"==typeof e[r])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:r},void 0===n.next&&(n.next=noop),void 0===n.error&&(n.error=noop),void 0===n.complete&&(n.complete=noop);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?n.error(this.finalError):n.complete()}catch(e){}})),this.observers.push(n),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then((()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function noop(){}function getModularInstance(e){return e&&e._delegate?e._delegate:e}function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}var a;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(a||(a={}));const c={debug:a.DEBUG,verbose:a.VERBOSE,info:a.INFO,warn:a.WARN,error:a.ERROR,silent:a.SILENT},u=a.INFO,d={[a.DEBUG]:"log",[a.VERBOSE]:"log",[a.INFO]:"info",[a.WARN]:"warn",[a.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const n=(new Date).toISOString(),i=d[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${n}] ${e.name}:`,...r)};class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const l={PHONE:"phone",TOTP:"totp"},h={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},p={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password",FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PHONE:"phone",TWITTER:"twitter.com"},f={LINK:"link",REAUTHENTICATE:"reauthenticate",SIGN_IN:"signIn"},m={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function _prodErrorMap(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const g=function _debugErrorMap(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registered for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is incorrect, malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-password":"A non-empty password must be provided","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.","missing-recaptcha-token":"The reCAPTCHA token is missing when sending request to the backend.","invalid-recaptcha-token":"The reCAPTCHA token is invalid when sending request to the backend.","invalid-recaptcha-action":"The reCAPTCHA action is invalid when sending request to the backend.","recaptcha-not-enabled":"reCAPTCHA Enterprise integration is not enabled for this project.","missing-client-type":"The reCAPTCHA client type is missing when sending request to the backend.","missing-recaptcha-version":"The reCAPTCHA version is missing when sending request to the backend.","invalid-req-type":"Invalid request parameters.","invalid-recaptcha-version":"The reCAPTCHA version is invalid when sending request to the backend.","unsupported-password-policy-schema-version":"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.","password-does-not-meet-requirements":"The password does not meet the requirements.","invalid-hosting-link-domain":"The provided Hosting link domain is not configured in Firebase Hosting or is not owned by the current project. This cannot be a default Hosting domain (`web.app` or `firebaseapp.com`)."}},_=_prodErrorMap,I=new ErrorFactory("auth","Firebase",{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}),v={ADMIN_ONLY_OPERATION:"auth/admin-restricted-operation",ARGUMENT_ERROR:"auth/argument-error",APP_NOT_AUTHORIZED:"auth/app-not-authorized",APP_NOT_INSTALLED:"auth/app-not-installed",CAPTCHA_CHECK_FAILED:"auth/captcha-check-failed",CODE_EXPIRED:"auth/code-expired",CORDOVA_NOT_READY:"auth/cordova-not-ready",CORS_UNSUPPORTED:"auth/cors-unsupported",CREDENTIAL_ALREADY_IN_USE:"auth/credential-already-in-use",CREDENTIAL_MISMATCH:"auth/custom-token-mismatch",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"auth/requires-recent-login",DEPENDENT_SDK_INIT_BEFORE_AUTH:"auth/dependent-sdk-initialized-before-auth",DYNAMIC_LINK_NOT_ACTIVATED:"auth/dynamic-link-not-activated",EMAIL_CHANGE_NEEDS_VERIFICATION:"auth/email-change-needs-verification",EMAIL_EXISTS:"auth/email-already-in-use",EMULATOR_CONFIG_FAILED:"auth/emulator-config-failed",EXPIRED_OOB_CODE:"auth/expired-action-code",EXPIRED_POPUP_REQUEST:"auth/cancelled-popup-request",INTERNAL_ERROR:"auth/internal-error",INVALID_API_KEY:"auth/invalid-api-key",INVALID_APP_CREDENTIAL:"auth/invalid-app-credential",INVALID_APP_ID:"auth/invalid-app-id",INVALID_AUTH:"auth/invalid-user-token",INVALID_AUTH_EVENT:"auth/invalid-auth-event",INVALID_CERT_HASH:"auth/invalid-cert-hash",INVALID_CODE:"auth/invalid-verification-code",INVALID_CONTINUE_URI:"auth/invalid-continue-uri",INVALID_CORDOVA_CONFIGURATION:"auth/invalid-cordova-configuration",INVALID_CUSTOM_TOKEN:"auth/invalid-custom-token",INVALID_DYNAMIC_LINK_DOMAIN:"auth/invalid-dynamic-link-domain",INVALID_EMAIL:"auth/invalid-email",INVALID_EMULATOR_SCHEME:"auth/invalid-emulator-scheme",INVALID_IDP_RESPONSE:"auth/invalid-credential",INVALID_LOGIN_CREDENTIALS:"auth/invalid-credential",INVALID_MESSAGE_PAYLOAD:"auth/invalid-message-payload",INVALID_MFA_SESSION:"auth/invalid-multi-factor-session",INVALID_OAUTH_CLIENT_ID:"auth/invalid-oauth-client-id",INVALID_OAUTH_PROVIDER:"auth/invalid-oauth-provider",INVALID_OOB_CODE:"auth/invalid-action-code",INVALID_ORIGIN:"auth/unauthorized-domain",INVALID_PASSWORD:"auth/wrong-password",INVALID_PERSISTENCE:"auth/invalid-persistence-type",INVALID_PHONE_NUMBER:"auth/invalid-phone-number",INVALID_PROVIDER_ID:"auth/invalid-provider-id",INVALID_RECIPIENT_EMAIL:"auth/invalid-recipient-email",INVALID_SENDER:"auth/invalid-sender",INVALID_SESSION_INFO:"auth/invalid-verification-id",INVALID_TENANT_ID:"auth/invalid-tenant-id",MFA_INFO_NOT_FOUND:"auth/multi-factor-info-not-found",MFA_REQUIRED:"auth/multi-factor-auth-required",MISSING_ANDROID_PACKAGE_NAME:"auth/missing-android-pkg-name",MISSING_APP_CREDENTIAL:"auth/missing-app-credential",MISSING_AUTH_DOMAIN:"auth/auth-domain-config-required",MISSING_CODE:"auth/missing-verification-code",MISSING_CONTINUE_URI:"auth/missing-continue-uri",MISSING_IFRAME_START:"auth/missing-iframe-start",MISSING_IOS_BUNDLE_ID:"auth/missing-ios-bundle-id",MISSING_OR_INVALID_NONCE:"auth/missing-or-invalid-nonce",MISSING_MFA_INFO:"auth/missing-multi-factor-info",MISSING_MFA_SESSION:"auth/missing-multi-factor-session",MISSING_PHONE_NUMBER:"auth/missing-phone-number",MISSING_PASSWORD:"auth/missing-password",MISSING_SESSION_INFO:"auth/missing-verification-id",MODULE_DESTROYED:"auth/app-deleted",NEED_CONFIRMATION:"auth/account-exists-with-different-credential",NETWORK_REQUEST_FAILED:"auth/network-request-failed",NULL_USER:"auth/null-user",NO_AUTH_EVENT:"auth/no-auth-event",NO_SUCH_PROVIDER:"auth/no-such-provider",OPERATION_NOT_ALLOWED:"auth/operation-not-allowed",OPERATION_NOT_SUPPORTED:"auth/operation-not-supported-in-this-environment",POPUP_BLOCKED:"auth/popup-blocked",POPUP_CLOSED_BY_USER:"auth/popup-closed-by-user",PROVIDER_ALREADY_LINKED:"auth/provider-already-linked",QUOTA_EXCEEDED:"auth/quota-exceeded",REDIRECT_CANCELLED_BY_USER:"auth/redirect-cancelled-by-user",REDIRECT_OPERATION_PENDING:"auth/redirect-operation-pending",REJECTED_CREDENTIAL:"auth/rejected-credential",SECOND_FACTOR_ALREADY_ENROLLED:"auth/second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"auth/maximum-second-factor-count-exceeded",TENANT_ID_MISMATCH:"auth/tenant-id-mismatch",TIMEOUT:"auth/timeout",TOKEN_EXPIRED:"auth/user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"auth/too-many-requests",UNAUTHORIZED_DOMAIN:"auth/unauthorized-continue-uri",UNSUPPORTED_FIRST_FACTOR:"auth/unsupported-first-factor",UNSUPPORTED_PERSISTENCE:"auth/unsupported-persistence-type",UNSUPPORTED_TENANT_OPERATION:"auth/unsupported-tenant-operation",UNVERIFIED_EMAIL:"auth/unverified-email",USER_CANCELLED:"auth/user-cancelled",USER_DELETED:"auth/user-not-found",USER_DISABLED:"auth/user-disabled",USER_MISMATCH:"auth/user-mismatch",USER_SIGNED_OUT:"auth/user-signed-out",WEAK_PASSWORD:"auth/weak-password",WEB_STORAGE_UNSUPPORTED:"auth/web-storage-unsupported",ALREADY_INITIALIZED:"auth/already-initialized",RECAPTCHA_NOT_ENABLED:"auth/recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"auth/missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"auth/invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"auth/invalid-recaptcha-action",MISSING_CLIENT_TYPE:"auth/missing-client-type",MISSING_RECAPTCHA_VERSION:"auth/missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"auth/invalid-recaptcha-version",INVALID_REQ_TYPE:"auth/invalid-req-type",INVALID_HOSTING_LINK_DOMAIN:"auth/invalid-hosting-link-domain"},E=new class Logger{constructor(e){this.name=e,this._logLevel=u,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in a))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?c[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,a.DEBUG,...e),this._logHandler(this,a.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,a.VERBOSE,...e),this._logHandler(this,a.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,a.INFO,...e),this._logHandler(this,a.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,a.WARN,...e),this._logHandler(this,a.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,a.ERROR,...e),this._logHandler(this,a.ERROR,...e)}}("@firebase/auth");function _logError(e,...t){E.logLevel<=a.ERROR&&E.error(`Auth (${i}): ${e}`,...t)}function _fail(e,...t){throw createErrorInternal(e,...t)}function _createError(e,...t){return createErrorInternal(e,...t)}function _errorWithCustomMessage(e,t,r){const n={..._(),[t]:r};return new ErrorFactory("auth","Firebase",n).create(t,{appName:e.name})}function _serverAppCurrentUserOperationNotSupportedError(e){return _errorWithCustomMessage(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function _assertInstanceOf(e,t,r){if(!(t instanceof r))throw r.name!==t.constructor.name&&_fail(e,"argument-error"),_errorWithCustomMessage(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`)}function createErrorInternal(e,...t){if("string"!=typeof e){const r=t[0],n=[...t.slice(1)];return n[0]&&(n[0].appName=e.name),e._errorFactory.create(r,...n)}return I.create(e,...t)}function _assert(e,t,...r){if(!e)throw createErrorInternal(t,...r)}function debugFail(e){const t="INTERNAL ASSERTION FAILED: "+e;throw _logError(t),new Error(t)}function debugAssert(e,t){e||debugFail(t)}function _getCurrentUrl(){return"undefined"!=typeof self&&self.location?.href||""}function _isHttpOrHttps(){return"http:"===_getCurrentScheme()||"https:"===_getCurrentScheme()}function _getCurrentScheme(){return"undefined"!=typeof self&&self.location?.protocol||null}function _isOnline(){return!("undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(_isHttpOrHttps()||function isBrowserExtension(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}()||"connection"in navigator))||navigator.onLine}class Delay{constructor(e,t){this.shortDelay=e,this.longDelay=t,debugAssert(t>e,"Short delay should be less than long delay!"),this.isMobile=function isMobileCordova(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())}()||function isReactNative(){return"object"==typeof navigator&&"ReactNative"===navigator.product}()}get(){return _isOnline()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function _emulatorUrl(e,t){debugAssert(e.emulator,"Emulator should always be set here");const{url:r}=e.emulator;return t?`${r}${t.startsWith("/")?t.slice(1):t}`:r}class FetchProvider{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!=typeof self&&"fetch"in self?self.fetch:"undefined"!=typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!=typeof fetch?fetch:void debugFail("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"undefined"!=typeof self&&"Headers"in self?self.Headers:"undefined"!=typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!=typeof Headers?Headers:void debugFail("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"undefined"!=typeof self&&"Response"in self?self.Response:"undefined"!=typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!=typeof Response?Response:void debugFail("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const T={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},A=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],y=new Delay(3e4,6e4);function _addTidIfNecessary(e,t){return e.tenantId&&!t.tenantId?{...t,tenantId:e.tenantId}:t}async function _performApiRequest(e,t,r,n,i={}){return _performFetchWithErrorHandling(e,i,(async()=>{let i={},s={};n&&("GET"===t?s=n:i={body:JSON.stringify(n)});const o=querystring({...s,key:e.config.apiKey}).slice(1),a=await e._getAdditionalHeaders();a["Content-Type"]="application/json",e.languageCode&&(a["X-Firebase-Locale"]=e.languageCode);const c={method:t,headers:a,...i};return function isCloudflareWorker(){return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent}()||(c.referrerPolicy="strict-origin-when-cross-origin"),e.emulatorConfig&&isCloudWorkstation(e.emulatorConfig.host)&&(c.credentials="include"),FetchProvider.fetch()(await _getFinalTarget(e,e.config.apiHost,r,o),c)}))}async function _performFetchWithErrorHandling(e,t,r){e._canInitEmulator=!1;const n={...T,...t};try{const t=new NetworkTimeout(e),i=await Promise.race([r(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if("needConfirmation"in s)throw _makeTaggedError(e,"account-exists-with-different-credential",s);if(i.ok&&!("errorMessage"in s))return s;{const t=i.ok?s.errorMessage:s.error.message,[r,o]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===r)throw _makeTaggedError(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===r)throw _makeTaggedError(e,"email-already-in-use",s);if("USER_DISABLED"===r)throw _makeTaggedError(e,"user-disabled",s);const a=n[r]||r.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw _errorWithCustomMessage(e,a,o);_fail(e,a)}}catch(t){if(t instanceof FirebaseError)throw t;_fail(e,"network-request-failed",{message:String(t)})}}async function _performSignInRequest(e,t,r,n,i={}){const s=await _performApiRequest(e,t,r,n,i);return"mfaPendingCredential"in s&&_fail(e,"multi-factor-auth-required",{_serverResponse:s}),s}async function _getFinalTarget(e,t,r,n){const i=`${t}${r}?${n}`,s=e,o=s.config.emulator?_emulatorUrl(e.config,i):`${e.config.apiScheme}://${i}`;if(A.includes(r)&&(await s._persistenceManagerAvailable,"COOKIE"===s._getPersistenceType())){return s._getPersistence()._getFinalTarget(o).toString()}return o}function _parseEnforcementState(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class NetworkTimeout{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(_createError(this.auth,"network-request-failed"))),y.get())}))}}function _makeTaggedError(e,t,r){const n={appName:e.name};r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber);const i=_createError(e,t,n);return i.customData._tokenResponse=r,i}function isV2(e){return void 0!==e&&void 0!==e.getResponse}function isEnterprise(e){return void 0!==e&&void 0!==e.enterprise}class RecaptchaConfig{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return _parseEnforcementState(t.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function getRecaptchaConfig(e,t){return _performApiRequest(e,"GET","/v2/recaptchaConfig",_addTidIfNecessary(e,t))}async function getAccountInfo(e,t){return _performApiRequest(e,"POST","/v1/accounts:lookup",t)}function utcTimestampToDateString(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function getIdToken(e,t=!1){return getModularInstance(e).getIdToken(t)}async function getIdTokenResult(e,t=!1){const r=getModularInstance(e),n=await r.getIdToken(t),i=_parseToken(n);_assert(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error");const s="object"==typeof i.firebase?i.firebase:void 0,o=s?.sign_in_provider;return{claims:i,token:n,authTime:utcTimestampToDateString(secondsStringToMilliseconds(i.auth_time)),issuedAtTime:utcTimestampToDateString(secondsStringToMilliseconds(i.iat)),expirationTime:utcTimestampToDateString(secondsStringToMilliseconds(i.exp)),signInProvider:o||null,signInSecondFactor:s?.sign_in_second_factor||null}}function secondsStringToMilliseconds(e){return 1e3*Number(e)}function _parseToken(e){const[t,r,n]=e.split(".");if(void 0===t||void 0===r||void 0===n)return _logError("JWT malformed, contained fewer than 3 sections"),null;try{const e=base64Decode(r);return e?JSON.parse(e):(_logError("Failed to decode base64 JWT payload"),null)}catch(e){return _logError("Caught error parsing JWT payload as JSON",e?.toString()),null}}function _tokenExpiresIn(e){const t=_parseToken(e);return _assert(t,"internal-error"),_assert(void 0!==t.exp,"internal-error"),_assert(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function _logoutIfInvalidated(e,t,r=!1){if(r)return t;try{return await t}catch(t){throw t instanceof FirebaseError&&function isUserInvalidated({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class ProactiveRefresh{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,e)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout((async()=>{await this.iteration()}),t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===e?.code&&this.schedule(!0))}this.schedule()}}class UserMetadata{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=utcTimestampToDateString(this.lastLoginAt),this.creationTime=utcTimestampToDateString(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function _reloadWithoutSaving(e){const t=e.auth,r=await e.getIdToken(),n=await _logoutIfInvalidated(e,getAccountInfo(t,{idToken:r}));_assert(n?.users.length,t,"internal-error");const i=n.users[0];e._notifyReloadListener(i);const s=i.providerUserInfo?.length?extractProviderData(i.providerUserInfo):[],o=function mergeProviderData(e,t){return[...e.filter((e=>!t.some((t=>t.providerId===e.providerId)))),...t]}(e.providerData,s),a=e.isAnonymous,c=!(e.email&&i.passwordHash||o?.length),u=!!a&&c,d={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:o,metadata:new UserMetadata(i.createdAt,i.lastLoginAt),isAnonymous:u};Object.assign(e,d)}async function reload(e){const t=getModularInstance(e);await _reloadWithoutSaving(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}function extractProviderData(e){return e.map((({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null})))}class StsTokenManager{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){_assert(e.idToken,"internal-error"),_assert(void 0!==e.idToken,"internal-error"),_assert(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):_tokenExpiresIn(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){_assert(0!==e.length,"internal-error");const t=_tokenExpiresIn(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(_assert(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null):this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:r,refreshToken:n,expiresIn:i}=await async function requestStsToken(e,t){const r=await _performFetchWithErrorHandling(e,{},(async()=>{const r=querystring({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:n,apiKey:i}=e.config,s=await _getFinalTarget(e,n,"/v1/token",`key=${i}`),o=await e._getAdditionalHeaders();o["Content-Type"]="application/x-www-form-urlencoded";const a={method:"POST",headers:o,body:r};return e.emulatorConfig&&isCloudWorkstation(e.emulatorConfig.host)&&(a.credentials="include"),FetchProvider.fetch()(s,a)}));return{accessToken:r.access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token}}(e,t);this.updateTokensAndExpiration(r,n,Number(i))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*r}static fromJSON(e,t){const{refreshToken:r,accessToken:n,expirationTime:i}=t,s=new StsTokenManager;return r&&(_assert("string"==typeof r,"internal-error",{appName:e}),s.refreshToken=r),n&&(_assert("string"==typeof n,"internal-error",{appName:e}),s.accessToken=n),i&&(_assert("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new StsTokenManager,this.toJSON())}_performRefresh(){return debugFail("not implemented")}}function assertStringOrUndefined(e,t){_assert("string"==typeof e||void 0===e,"internal-error",{appName:t})}class UserImpl{constructor({uid:e,auth:t,stsTokenManager:r,...n}){this.providerId="firebase",this.proactiveRefresh=new ProactiveRefresh(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=n.displayName||null,this.email=n.email||null,this.emailVerified=n.emailVerified||!1,this.phoneNumber=n.phoneNumber||null,this.photoURL=n.photoURL||null,this.isAnonymous=n.isAnonymous||!1,this.tenantId=n.tenantId||null,this.providerData=n.providerData?[...n.providerData]:[],this.metadata=new UserMetadata(n.createdAt||void 0,n.lastLoginAt||void 0)}async getIdToken(e){const t=await _logoutIfInvalidated(this,this.stsTokenManager.getToken(this.auth,e));return _assert(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return getIdTokenResult(this,e)}reload(){return reload(this)}_assign(e){this!==e&&(_assert(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map((e=>({...e}))),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new UserImpl({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){_assert(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await _reloadWithoutSaving(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(e(this.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));const t=await this.getIdToken();return await _logoutIfInvalidated(this,async function deleteAccount(e,t){return _performApiRequest(e,"POST","/v1/accounts:delete",t)}(this.auth,{idToken:t})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map((e=>({...e}))),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){const r=t.displayName??void 0,n=t.email??void 0,i=t.phoneNumber??void 0,s=t.photoURL??void 0,o=t.tenantId??void 0,a=t._redirectEventId??void 0,c=t.createdAt??void 0,u=t.lastLoginAt??void 0,{uid:d,emailVerified:l,isAnonymous:h,providerData:p,stsTokenManager:f}=t;_assert(d&&f,e,"internal-error");const m=StsTokenManager.fromJSON(this.name,f);_assert("string"==typeof d,e,"internal-error"),assertStringOrUndefined(r,e.name),assertStringOrUndefined(n,e.name),_assert("boolean"==typeof l,e,"internal-error"),_assert("boolean"==typeof h,e,"internal-error"),assertStringOrUndefined(i,e.name),assertStringOrUndefined(s,e.name),assertStringOrUndefined(o,e.name),assertStringOrUndefined(a,e.name),assertStringOrUndefined(c,e.name),assertStringOrUndefined(u,e.name);const g=new UserImpl({uid:d,auth:e,email:n,emailVerified:l,displayName:r,isAnonymous:h,photoURL:s,phoneNumber:i,tenantId:o,stsTokenManager:m,createdAt:c,lastLoginAt:u});return p&&Array.isArray(p)&&(g.providerData=p.map((e=>({...e})))),a&&(g._redirectEventId=a),g}static async _fromIdTokenResponse(e,t,r=!1){const n=new StsTokenManager;n.updateFromServerResponse(t);const i=new UserImpl({uid:t.localId,auth:e,stsTokenManager:n,isAnonymous:r});return await _reloadWithoutSaving(i),i}static async _fromGetAccountInfoResponse(e,t,r){const n=t.users[0];_assert(void 0!==n.localId,"internal-error");const i=void 0!==n.providerUserInfo?extractProviderData(n.providerUserInfo):[],s=!(n.email&&n.passwordHash||i?.length),o=new StsTokenManager;o.updateFromIdToken(r);const a=new UserImpl({uid:n.localId,auth:e,stsTokenManager:o,isAnonymous:s}),c={uid:n.localId,displayName:n.displayName||null,photoURL:n.photoUrl||null,email:n.email||null,emailVerified:n.emailVerified||!1,phoneNumber:n.phoneNumber||null,tenantId:n.tenantId||null,providerData:i,metadata:new UserMetadata(n.createdAt,n.lastLoginAt),isAnonymous:!(n.email&&n.passwordHash||i?.length)};return Object.assign(a,c),a}}const w=new Map;function _getInstance(e){debugAssert(e instanceof Function,"Expected a class definition");let t=w.get(e);return t?(debugAssert(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,w.set(e,t),t)}class InMemoryPersistence{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}InMemoryPersistence.type="NONE";const S=InMemoryPersistence;function _persistenceKeyName(e,t,r){return`firebase:${e}:${t}:${r}`}class PersistenceUserManager{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;const{config:n,name:i}=this.auth;this.fullUserKey=_persistenceKeyName(this.userKey,n.apiKey,i),this.fullPersistenceKey=_persistenceKeyName("persistence",n.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);if(!e)return null;if("string"==typeof e){const t=await getAccountInfo(this.auth,{idToken:e}).catch((()=>{}));return t?UserImpl._fromGetAccountInfoResponse(this.auth,t,e):null}return UserImpl._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,r="authUser"){if(!t.length)return new PersistenceUserManager(_getInstance(S),e,r);const n=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let i=n[0]||_getInstance(S);const s=_persistenceKeyName(r,e.config.apiKey,e.name);let o=null;for(const r of t)try{const t=await r._get(s);if(t){let n;if("string"==typeof t){const r=await getAccountInfo(e,{idToken:t}).catch((()=>{}));if(!r)break;n=await UserImpl._fromGetAccountInfoResponse(e,r,t)}else n=UserImpl._fromJSON(e,t);r!==i&&(o=n),i=r;break}}catch{}const a=n.filter((e=>e._shouldAllowMigration));return i._shouldAllowMigration&&a.length?(i=a[0],o&&await i._set(s,o.toJSON()),await Promise.all(t.map((async e=>{if(e!==i)try{await e._remove(s)}catch{}}))),new PersistenceUserManager(i,e,r)):new PersistenceUserManager(i,e,r)}}function _getBrowserName(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(_isIEMobile(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(_isFirefox(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(_isBlackBerry(t))return"Blackberry";if(_isWebOS(t))return"Webos";if(_isSafari(t))return"Safari";if((t.includes("chrome/")||_isChromeIOS(t))&&!t.includes("edge/"))return"Chrome";if(_isAndroid(t))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=e.match(t);if(2===r?.length)return r[1]}return"Other"}function _isFirefox(e=getUA()){return/firefox\//i.test(e)}function _isSafari(e=getUA()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function _isChromeIOS(e=getUA()){return/crios\//i.test(e)}function _isIEMobile(e=getUA()){return/iemobile/i.test(e)}function _isAndroid(e=getUA()){return/android/i.test(e)}function _isBlackBerry(e=getUA()){return/blackberry/i.test(e)}function _isWebOS(e=getUA()){return/webos/i.test(e)}function _isIOS(e=getUA()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function _isIE10(){return function isIE(){const e=getUA();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}()&&10===document.documentMode}function _isMobileBrowser(e=getUA()){return _isIOS(e)||_isAndroid(e)||_isWebOS(e)||_isBlackBerry(e)||/windows phone/i.test(e)||_isIEMobile(e)}function _getClientVersion(e,t=[]){let r;switch(e){case"Browser":r=_getBrowserName(getUA());break;case"Worker":r=`${_getBrowserName(getUA())}-${e}`;break;default:r=e}const n=t.length?t.join(","):"FirebaseCore-web";return`${r}/JsCore/${i}/${n}`}class AuthMiddlewareQueue{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const wrappedCallback=t=>new Promise(((r,n)=>{try{r(e(t))}catch(e){n(e)}}));wrappedCallback.onAbort=t,this.queue.push(wrappedCallback);const r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(e){t.reverse();for(const e of t)try{e()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:e?.message})}}}class PasswordPolicyImpl{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??6,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),void 0!==t.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),void 0!==t.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),void 0!==t.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),void 0!==t.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){const t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){const r=this.customStrengthOptions.minPasswordLength,n=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),n&&(t.meetsMaxPasswordLength=e.length<=n)}validatePasswordCharacterOptions(e,t){let r;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let n=0;n<e.length;n++)r=e.charAt(n),this.updatePasswordCharacterOptionsStatuses(t,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,n,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=n)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class AuthImpl{constructor(e,t,r,n){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Subscription(this),this.idTokenSubscription=new Subscription(this),this.beforeStateQueue=new AuthMiddlewareQueue(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=I,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion,this._persistenceManagerAvailable=new Promise((e=>this._resolvePersistenceManagerAvailable=e))}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=_getInstance(t)),this._initializationPromise=this.queue((async()=>{if(!this._deleted&&(this.persistenceManager=await PersistenceUserManager.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0):void 0}async initializeCurrentUserFromIdToken(e){try{const t=await getAccountInfo(this,{idToken:e}),r=await UserImpl._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(t){if(e(this.app)){const e=this.app.settings.authIdToken;return e?new Promise((t=>{setTimeout((()=>this.initializeCurrentUserFromIdToken(e).then(t,t)))})):this.directlySetCurrentUser(null)}const r=await this.assertedPersistence.getCurrentUser();let n=r,i=!1;if(t&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const e=this.redirectUser?._redirectEventId,r=n?._redirectEventId,s=await this.tryRedirectSignIn(t);e&&e!==r||!s?.user||(n=s.user,i=!0)}if(!n)return this.directlySetCurrentUser(null);if(!n._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(n)}catch(e){n=r,this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(e)))}return n?this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}return _assert(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId?this.directlySetCurrentUser(n):this.reloadAndSetCurrentUserOrClear(n)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await _reloadWithoutSaving(e)}catch(e){if("auth/network-request-failed"!==e?.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function _getUserLanguage(){if("undefined"==typeof navigator)return null;const e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(t){if(e(this.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));const r=t?getModularInstance(t):null;return r&&_assert(r.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(r&&r._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&_assert(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue((async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()}))}async signOut(){return e(this.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(t){return e(this.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)):this.queue((async()=>{await this.assertedPersistence.setPersistence(_getInstance(t))}))}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await async function _getPasswordPolicy(e,t={}){return _performApiRequest(e,"GET","/v2/passwordPolicy",_addTidIfNecessary(e,t))}(this),t=new PasswordPolicyImpl(e);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new ErrorFactory("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser)e();else{const r=this.onAuthStateChanged((()=>{r(),e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await async function revokeToken(e,t){return _performApiRequest(e,"POST","/v2/accounts:revokeToken",_addTidIfNecessary(e,t))}(this,t)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){const r=await this.getOrInitRedirectPersistenceManager(t);return null===e?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&_getInstance(e)||this._popupRedirectResolver;_assert(t,this,"argument-error"),this.redirectPersistenceManager=await PersistenceUserManager.create(this,[_getInstance(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue((async()=>{})),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(e)))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,r,n){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t);let s=!1;const o=this._isInitialized?Promise.resolve():this._initializationPromise;if(_assert(o,this,"internal-error"),o.then((()=>{s||i(this.currentUser)})),"function"==typeof t){const i=e.addObserver(t,r,n);return()=>{s=!0,i()}}{const r=e.addObserver(t);return()=>{s=!0,r()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return _assert(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=_getClientVersion(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);const t=await(this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader());t&&(e["X-Firebase-Client"]=t);const r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(e(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const t=await(this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken());return t?.error&&function _logWarn(e,...t){E.logLevel<=a.WARN&&E.warn(`Auth (${i}): ${e}`,...t)}(`Error while retrieving App Check token: ${t.error}`),t?.token}}function _castAuth(e){return getModularInstance(e)}class Subscription{constructor(e){this.auth=e,this.observer=null,this.addObserver=function createSubscribe(e,t){const r=new ObserverProxy(e,t);return r.subscribe.bind(r)}((e=>this.observer=e))}get next(){return _assert(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let P={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function _loadJS(e){return P.loadJS(e)}function _generateCallbackName(e){return`__${e}${Math.floor(1e6*Math.random())}`}const R=1e12;class MockReCaptcha{constructor(e){this.auth=e,this.counter=R,this._widgets=new Map}render(e,t){const r=this.counter;return this._widgets.set(r,new MockWidget(e,this.auth.name,t||{})),this.counter++,r}reset(e){const t=e||R;this._widgets.get(t)?.delete(),this._widgets.delete(t)}getResponse(e){const t=e||R;return this._widgets.get(t)?.getResponse()||""}async execute(e){const t=e||R;return this._widgets.get(t)?.execute(),""}}class MockGreCAPTCHATopLevel{constructor(){this.enterprise=new MockGreCAPTCHA}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class MockGreCAPTCHA{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class MockWidget{constructor(e,t,r){this.params=r,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};const n="string"==typeof e?document.getElementById(e):e;_assert(n,"argument-error",{appName:t}),this.container=n,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout((()=>{this.responseToken=function generateRandomAlphaNumericString(e){const t=[],r="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<e;n++)t.push(r.charAt(Math.floor(Math.random()*r.length)));return t.join("")}(50);const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout((()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()}),6e4)}),500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}const k="NO_RECAPTCHA",C="onFirebaseAuthREInstanceReady";class RecaptchaEnterpriseVerifier{constructor(e){this.type="recaptcha-enterprise",this.auth=_castAuth(e)}async verify(e="verify",t=!1){function retrieveRecaptchaToken(t,r,n){const i=window.grecaptcha;isEnterprise(i)?i.enterprise.ready((()=>{i.enterprise.execute(t,{action:e}).then((e=>{r(e)})).catch((()=>{r(k)}))})):n(Error("No reCAPTCHA enterprise script loaded."))}if(this.auth.settings.appVerificationDisabledForTesting){return(new MockGreCAPTCHATopLevel).execute("siteKey",{action:"verify"})}return new Promise(((e,r)=>{(async function retrieveSiteKey(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise((async(t,r)=>{getRecaptchaConfig(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((n=>{if(void 0!==n.recaptchaKey){const r=new RecaptchaConfig(n);return null==e.tenantId?e._agentRecaptchaConfig=r:e._tenantRecaptchaConfigs[e.tenantId]=r,t(r.siteKey)}r(new Error("recaptcha Enterprise site key undefined"))})).catch((e=>{r(e)}))}))})(this.auth).then((async n=>{if(!t&&isEnterprise(window.grecaptcha)&&RecaptchaEnterpriseVerifier.scriptInjectionDeferred)await RecaptchaEnterpriseVerifier.scriptInjectionDeferred.promise,retrieveRecaptchaToken(n,e,r);else{if("undefined"==typeof window)return void r(new Error("RecaptchaVerifier is only supported in browser"));let t=function _recaptchaEnterpriseScriptUrl(){return P.recaptchaEnterpriseScript}();0!==t.length&&(t+=n+`&onload=${C}`),RecaptchaEnterpriseVerifier.scriptInjectionDeferred=new Deferred,window[C]=()=>{RecaptchaEnterpriseVerifier.scriptInjectionDeferred?.resolve()},_loadJS(t).then((()=>RecaptchaEnterpriseVerifier.scriptInjectionDeferred?.promise)).then((()=>{retrieveRecaptchaToken(n,e,r)})).catch((e=>{r(e)}))}})).catch((e=>{r(e)}))}))}}async function injectRecaptchaFields(e,t,r,n=!1,i=!1){const s=new RecaptchaEnterpriseVerifier(e);let o;if(i)o=k;else try{o=await s.verify(r)}catch(e){o=await s.verify(r,!0)}const a={...t};if("mfaSmsEnrollment"===r||"mfaSmsSignIn"===r){if("phoneEnrollmentInfo"in a){const e=a.phoneEnrollmentInfo.phoneNumber,t=a.phoneEnrollmentInfo.recaptchaToken;Object.assign(a,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:t,captchaResponse:o,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in a){const e=a.phoneSignInInfo.recaptchaToken;Object.assign(a,{phoneSignInInfo:{recaptchaToken:e,captchaResponse:o,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return a}return n?Object.assign(a,{captchaResp:o}):Object.assign(a,{captchaResponse:o}),Object.assign(a,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(a,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),a}async function handleRecaptchaFlow(e,t,r,n,i){if("EMAIL_PASSWORD_PROVIDER"===i){if(e._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await injectRecaptchaFields(e,t,r,"getOobCode"===r);return n(e,i)}return n(e,t).catch((async i=>{if("auth/missing-recaptcha-token"===i.code){console.log(`${r} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const i=await injectRecaptchaFields(e,t,r,"getOobCode"===r);return n(e,i)}return Promise.reject(i)}))}if("PHONE_PROVIDER"===i){if(e._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){const i=await injectRecaptchaFields(e,t,r);return n(e,i).catch((async i=>{if("AUDIT"===e._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")&&("auth/missing-recaptcha-token"===i.code||"auth/invalid-app-credential"===i.code)){console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${r} flow.`);const i=await injectRecaptchaFields(e,t,r,!1,!0);return n(e,i)}return Promise.reject(i)}))}{const i=await injectRecaptchaFields(e,t,r,!1,!0);return n(e,i)}}return Promise.reject(i+" provider is not supported.")}async function _initializeRecaptchaConfig(e){const t=_castAuth(e),r=await getRecaptchaConfig(t,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}),n=new RecaptchaConfig(r);if(null==t.tenantId?t._agentRecaptchaConfig=n:t._tenantRecaptchaConfigs[t.tenantId]=n,n.isAnyProviderEnabled()){new RecaptchaEnterpriseVerifier(t).verify()}}function initializeAuth(e,t){const r=_getProvider(e,"auth");if(r.isInitialized()){const e=r.getImmediate();if(deepEqual(r.getOptions(),t??{}))return e;_fail(e,"already-initialized")}return r.initialize({options:t})}function connectAuthEmulator(e,t,r){const n=_castAuth(e);_assert(/^https?:\/\//.test(t),n,"invalid-emulator-scheme");const i=!!r?.disableWarnings,s=extractProtocol(t),{host:o,port:a}=function extractHostAndPort(e){const t=extractProtocol(e),r=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!r)return{host:"",port:null};const n=r[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(n);if(i){const e=i[1];return{host:e,port:parsePort(n.substr(e.length+1))}}{const[e,t]=n.split(":");return{host:e,port:parsePort(t)}}}(t),c=null===a?"":`:${a}`,u={url:`${s}//${o}${c}/`},d=Object.freeze({host:o,port:a,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})});if(!n._canInitEmulator)return _assert(n.config.emulator&&n.emulatorConfig,n,"emulator-config-failed"),void _assert(deepEqual(u,n.config.emulator)&&deepEqual(d,n.emulatorConfig),n,"emulator-config-failed");n.config.emulator=u,n.emulatorConfig=d,n.settings.appVerificationDisabledForTesting=!0,isCloudWorkstation(o)?async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(`${s}//${o}${c}`):i||function emitEmulatorWarning(){function attachBanner(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials.");"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",attachBanner):attachBanner())}()}function extractProtocol(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function parsePort(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}RecaptchaEnterpriseVerifier.scriptInjectionDeferred=null;class AuthCredential{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return debugFail("not implemented")}_getIdTokenResponse(e){return debugFail("not implemented")}_linkToIdToken(e,t){return debugFail("not implemented")}_getReauthenticationResolver(e){return debugFail("not implemented")}}async function resetPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:resetPassword",_addTidIfNecessary(e,t))}async function linkEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:signUp",t)}async function signInWithPassword(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPassword",_addTidIfNecessary(e,t))}async function sendOobCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendOobCode",_addTidIfNecessary(e,t))}async function sendPasswordResetEmail$1(e,t){return sendOobCode(e,t)}async function sendSignInLinkToEmail$1(e,t){return sendOobCode(e,t)}class EmailAuthCredential extends AuthCredential{constructor(e,t,r,n=null){super("password",r),this._email=e,this._password=t,this._tenantId=n}static _fromEmailAndPassword(e,t){return new EmailAuthCredential(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new EmailAuthCredential(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e;if(t?.email&&t?.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return handleRecaptchaFlow(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",signInWithPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return async function signInWithEmailLink$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}(e,{email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return handleRecaptchaFlow(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",linkEmailPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return async function signInWithEmailLinkForLinking(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function signInWithIdp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithIdp",_addTidIfNecessary(e,t))}class OAuthCredential extends AuthCredential{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new OAuthCredential(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):_fail("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:r,signInMethod:n,...i}=t;if(!r||!n)return null;const s=new OAuthCredential(r,n);return s.idToken=i.idToken||void 0,s.accessToken=i.accessToken||void 0,s.secret=i.secret,s.nonce=i.nonce,s.pendingToken=i.pendingToken||null,s}_getIdTokenResponse(e){return signInWithIdp(e,this.buildRequest())}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,signInWithIdp(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,signInWithIdp(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=querystring(t)}return e}}async function sendPhoneVerificationCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendVerificationCode",_addTidIfNecessary(e,t))}const b={USER_NOT_FOUND:"user-not-found"};class PhoneAuthCredential extends AuthCredential{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new PhoneAuthCredential({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new PhoneAuthCredential({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function signInWithPhoneNumber$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function linkWithPhoneNumber$1(e,t){const r=await _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t));if(r.temporaryProof)throw _makeTaggedError(e,"account-exists-with-different-credential",r);return r}(e,{idToken:t,...this._makeVerificationRequest()})}_getReauthenticationResolver(e){return async function verifyPhoneNumberForExisting(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,{...t,operation:"REAUTH"}),b)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:r,verificationCode:n}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:r,code:n}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}=e;return r||t||n||i?new PhoneAuthCredential({verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}):null}}class ActionCodeURL{constructor(e){const t=querystringDecode(extractQuerystring(e)),r=t.apiKey??null,n=t.oobCode??null,i=function parseMode(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(t.mode??null);_assert(r&&n&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=n,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){const t=function parseDeepLink(e){const t=querystringDecode(extractQuerystring(e)).link,r=t?querystringDecode(extractQuerystring(t)).deep_link_id:null,n=querystringDecode(extractQuerystring(e)).deep_link_id;return(n?querystringDecode(extractQuerystring(n)).link:null)||n||r||t||e}(e);try{return new ActionCodeURL(t)}catch{return null}}}function parseActionCodeURL(e){return ActionCodeURL.parseLink(e)}class EmailAuthProvider{constructor(){this.providerId=EmailAuthProvider.PROVIDER_ID}static credential(e,t){return EmailAuthCredential._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const r=ActionCodeURL.parseLink(t);return _assert(r,"argument-error"),EmailAuthCredential._fromEmailAndCode(e,r.code,r.tenantId)}}EmailAuthProvider.PROVIDER_ID="password",EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD="password",EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class FederatedAuthProvider{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class BaseOAuthProvider extends FederatedAuthProvider{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class OAuthProvider extends BaseOAuthProvider{static credentialFromJSON(e){const t="string"==typeof e?JSON.parse(e):e;return _assert("providerId"in t&&"signInMethod"in t,"argument-error"),OAuthCredential._fromParams(t)}credential(e){return this._credential({...e,nonce:e.rawNonce})}_credential(e){return _assert(e.idToken||e.accessToken,"argument-error"),OAuthCredential._fromParams({...e,providerId:this.providerId,signInMethod:this.providerId})}static credentialFromResult(e){return OAuthProvider.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return OAuthProvider.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r,oauthTokenSecret:n,pendingToken:i,nonce:s,providerId:o}=e;if(!(r||n||t||i))return null;if(!o)return null;try{return new OAuthProvider(o)._credential({idToken:t,accessToken:r,nonce:s,pendingToken:i})}catch(e){return null}}}class FacebookAuthProvider extends BaseOAuthProvider{constructor(){super("facebook.com")}static credential(e){return OAuthCredential._fromParams({providerId:FacebookAuthProvider.PROVIDER_ID,signInMethod:FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return FacebookAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return FacebookAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return FacebookAuthProvider.credential(e.oauthAccessToken)}catch{return null}}}FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD="facebook.com",FacebookAuthProvider.PROVIDER_ID="facebook.com";class GoogleAuthProvider extends BaseOAuthProvider{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return OAuthCredential._fromParams({providerId:GoogleAuthProvider.PROVIDER_ID,signInMethod:GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return GoogleAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GoogleAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return GoogleAuthProvider.credential(t,r)}catch{return null}}}GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD="google.com",GoogleAuthProvider.PROVIDER_ID="google.com";class GithubAuthProvider extends BaseOAuthProvider{constructor(){super("github.com")}static credential(e){return OAuthCredential._fromParams({providerId:GithubAuthProvider.PROVIDER_ID,signInMethod:GithubAuthProvider.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return GithubAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GithubAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return GithubAuthProvider.credential(e.oauthAccessToken)}catch{return null}}}GithubAuthProvider.GITHUB_SIGN_IN_METHOD="github.com",GithubAuthProvider.PROVIDER_ID="github.com";class SAMLAuthCredential extends AuthCredential{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return signInWithIdp(e,this.buildRequest())}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,signInWithIdp(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,signInWithIdp(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:r,signInMethod:n,pendingToken:i}=t;return r&&n&&i&&r===n?new SAMLAuthCredential(r,i):null}static _create(e,t){return new SAMLAuthCredential(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class SAMLAuthProvider extends FederatedAuthProvider{constructor(e){_assert(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){const t=SAMLAuthCredential.fromJSON(e);return _assert(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{pendingToken:t,providerId:r}=e;if(!t||!r)return null;try{return SAMLAuthCredential._create(r,t)}catch(e){return null}}}class TwitterAuthProvider extends BaseOAuthProvider{constructor(){super("twitter.com")}static credential(e,t){return OAuthCredential._fromParams({providerId:TwitterAuthProvider.PROVIDER_ID,signInMethod:TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return TwitterAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return TwitterAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return TwitterAuthProvider.credential(t,r)}catch{return null}}}async function signUp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signUp",_addTidIfNecessary(e,t))}TwitterAuthProvider.TWITTER_SIGN_IN_METHOD="twitter.com",TwitterAuthProvider.PROVIDER_ID="twitter.com";class UserCredentialImpl{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,n=!1){const i=await UserImpl._fromIdTokenResponse(e,r,n),s=providerIdForResponse(r);return new UserCredentialImpl({user:i,providerId:s,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);const n=providerIdForResponse(r);return new UserCredentialImpl({user:e,providerId:n,_tokenResponse:r,operationType:t})}}function providerIdForResponse(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}async function signInAnonymously(t){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const r=_castAuth(t);if(await r._initializationPromise,r.currentUser?.isAnonymous)return new UserCredentialImpl({user:r.currentUser,providerId:null,operationType:"signIn"});const n=await signUp(r,{returnSecureToken:!0}),i=await UserCredentialImpl._fromIdTokenResponse(r,"signIn",n,!0);return await r._updateCurrentUser(i.user),i}class MultiFactorError extends FirebaseError{constructor(e,t,r,n){super(t.code,t.message),this.operationType=r,this.user=n,Object.setPrototypeOf(this,MultiFactorError.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,n){return new MultiFactorError(e,t,r,n)}}function _processCredentialSavingMfaContextIfNecessary(e,t,r,n){return("reauthenticate"===t?r._getReauthenticationResolver(e):r._getIdTokenResponse(e)).catch((r=>{if("auth/multi-factor-auth-required"===r.code)throw MultiFactorError._fromErrorAndOperation(e,r,t,n);throw r}))}function providerDataAsNames(e){return new Set(e.map((({providerId:e})=>e)).filter((e=>!!e)))}async function unlink(e,t){const r=getModularInstance(e);await _assertLinkedStatus(!0,r,t);const{providerUserInfo:n}=await async function deleteLinkedAccounts(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}(r.auth,{idToken:await r.getIdToken(),deleteProvider:[t]}),i=providerDataAsNames(n||[]);return r.providerData=r.providerData.filter((e=>i.has(e.providerId))),i.has("phone")||(r.phoneNumber=null),await r.auth._persistUserIfCurrent(r),r}async function _link$1(e,t,r=!1){const n=await _logoutIfInvalidated(e,t._linkToIdToken(e.auth,await e.getIdToken()),r);return UserCredentialImpl._forOperation(e,"link",n)}async function _assertLinkedStatus(e,t,r){await _reloadWithoutSaving(t);const n=!1===e?"provider-already-linked":"no-such-provider";_assert(providerDataAsNames(t.providerData).has(r)===e,t.auth,n)}async function _reauthenticate(t,r,n=!1){const{auth:i}=t;if(e(i.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i));const s="reauthenticate";try{const e=await _logoutIfInvalidated(t,_processCredentialSavingMfaContextIfNecessary(i,s,r,t),n);_assert(e.idToken,i,"internal-error");const o=_parseToken(e.idToken);_assert(o,i,"internal-error");const{sub:a}=o;return _assert(t.uid===a,i,"user-mismatch"),UserCredentialImpl._forOperation(t,s,e)}catch(e){throw"auth/user-not-found"===e?.code&&_fail(i,"user-mismatch"),e}}async function _signInWithCredential(t,r,n=!1){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i="signIn",s=await _processCredentialSavingMfaContextIfNecessary(t,i,r),o=await UserCredentialImpl._fromIdTokenResponse(t,i,s);return n||await t._updateCurrentUser(o.user),o}async function signInWithCredential(e,t){return _signInWithCredential(_castAuth(e),t)}async function linkWithCredential(e,t){const r=getModularInstance(e);return await _assertLinkedStatus(!1,r,t.providerId),_link$1(r,t)}async function reauthenticateWithCredential(e,t){return _reauthenticate(getModularInstance(e),t)}async function signInWithCustomToken(t,r){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const n=_castAuth(t),i=await async function signInWithCustomToken$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithCustomToken",_addTidIfNecessary(e,t))}(n,{token:r,returnSecureToken:!0}),s=await UserCredentialImpl._fromIdTokenResponse(n,"signIn",i);return await n._updateCurrentUser(s.user),s}class MultiFactorInfoImpl{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?PhoneMultiFactorInfoImpl._fromServerResponse(e,t):"totpInfo"in t?TotpMultiFactorInfoImpl._fromServerResponse(e,t):_fail(e,"internal-error")}}class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new PhoneMultiFactorInfoImpl(t)}}class TotpMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new TotpMultiFactorInfoImpl(t)}}function _setActionCodeSettingsOnRequest(e,t,r){_assert(r.url?.length>0,e,"invalid-continue-uri"),_assert(void 0===r.dynamicLinkDomain||r.dynamicLinkDomain.length>0,e,"invalid-dynamic-link-domain"),_assert(void 0===r.linkDomain||r.linkDomain.length>0,e,"invalid-hosting-link-domain"),t.continueUrl=r.url,t.dynamicLinkDomain=r.dynamicLinkDomain,t.linkDomain=r.linkDomain,t.canHandleCodeInApp=r.handleCodeInApp,r.iOS&&(_assert(r.iOS.bundleId.length>0,e,"missing-ios-bundle-id"),t.iOSBundleId=r.iOS.bundleId),r.android&&(_assert(r.android.packageName.length>0,e,"missing-android-pkg-name"),t.androidInstallApp=r.android.installApp,t.androidMinimumVersionCode=r.android.minimumVersion,t.androidPackageName=r.android.packageName)}async function recachePasswordPolicy(e){const t=_castAuth(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function sendPasswordResetEmail(e,t,r){const n=_castAuth(e),i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};r&&_setActionCodeSettingsOnRequest(n,i,r),await handleRecaptchaFlow(n,i,"getOobCode",sendPasswordResetEmail$1,"EMAIL_PASSWORD_PROVIDER")}async function confirmPasswordReset(e,t,r){await resetPassword(getModularInstance(e),{oobCode:t,newPassword:r}).catch((async t=>{throw"auth/password-does-not-meet-requirements"===t.code&&recachePasswordPolicy(e),t}))}async function applyActionCode(e,t){await async function applyActionCode$1(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",_addTidIfNecessary(e,t))}(getModularInstance(e),{oobCode:t})}async function checkActionCode(e,t){const r=getModularInstance(e),n=await resetPassword(r,{oobCode:t}),i=n.requestType;switch(_assert(i,r,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":_assert(n.newEmail,r,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":_assert(n.mfaInfo,r,"internal-error");default:_assert(n.email,r,"internal-error")}let s=null;return n.mfaInfo&&(s=MultiFactorInfoImpl._fromServerResponse(_castAuth(r),n.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===n.requestType?n.newEmail:n.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===n.requestType?n.email:n.newEmail)||null,multiFactorInfo:s},operation:i}}async function verifyPasswordResetCode(e,t){const{data:r}=await checkActionCode(getModularInstance(e),t);return r.email}async function createUserWithEmailAndPassword(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t),s=handleRecaptchaFlow(i,{returnSecureToken:!0,email:r,password:n,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",signUp,"EMAIL_PASSWORD_PROVIDER"),o=await s.catch((e=>{throw"auth/password-does-not-meet-requirements"===e.code&&recachePasswordPolicy(t),e})),a=await UserCredentialImpl._fromIdTokenResponse(i,"signIn",o);return await i._updateCurrentUser(a.user),a}function signInWithEmailAndPassword(t,r,n){return e(t.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t)):signInWithCredential(getModularInstance(t),EmailAuthProvider.credential(r,n)).catch((async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&recachePasswordPolicy(t),e}))}async function sendSignInLinkToEmail(e,t,r){const n=_castAuth(e),i={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};!function setActionCodeSettings(e,t){_assert(t.handleCodeInApp,n,"argument-error"),t&&_setActionCodeSettingsOnRequest(n,e,t)}(i,r),await handleRecaptchaFlow(n,i,"getOobCode",sendSignInLinkToEmail$1,"EMAIL_PASSWORD_PROVIDER")}function isSignInWithEmailLink(e,t){const r=ActionCodeURL.parseLink(t);return"EMAIL_SIGNIN"===r?.operation}async function signInWithEmailLink(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=getModularInstance(t),s=EmailAuthProvider.credentialWithLink(r,n||_getCurrentUrl());return _assert(s._tenantId===(i.tenantId||null),i,"tenant-id-mismatch"),signInWithCredential(i,s)}async function fetchSignInMethodsForEmail(e,t){const r={identifier:t,continueUri:_isHttpOrHttps()?_getCurrentUrl():"http://localhost"},{signinMethods:n}=await async function createAuthUri(e,t){return _performApiRequest(e,"POST","/v1/accounts:createAuthUri",_addTidIfNecessary(e,t))}(getModularInstance(e),r);return n||[]}async function sendEmailVerification(e,t){const r=getModularInstance(e),n={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&_setActionCodeSettingsOnRequest(r.auth,n,t);const{email:i}=await async function sendEmailVerification$1(e,t){return sendOobCode(e,t)}(r.auth,n);i!==e.email&&await e.reload()}async function verifyBeforeUpdateEmail(e,t,r){const n=getModularInstance(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};r&&_setActionCodeSettingsOnRequest(n.auth,i,r);const{email:s}=await async function verifyAndChangeEmail(e,t){return sendOobCode(e,t)}(n.auth,i);s!==e.email&&await e.reload()}async function updateProfile(e,{displayName:t,photoURL:r}){if(void 0===t&&void 0===r)return;const n=getModularInstance(e),i={idToken:await n.getIdToken(),displayName:t,photoUrl:r,returnSecureToken:!0},s=await _logoutIfInvalidated(n,async function updateProfile$1(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}(n.auth,i));n.displayName=s.displayName||null,n.photoURL=s.photoUrl||null;const o=n.providerData.find((({providerId:e})=>"password"===e));o&&(o.displayName=n.displayName,o.photoURL=n.photoURL),await n._updateTokensIfNecessary(s)}function updateEmail(t,r){const n=getModularInstance(t);return e(n.auth.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth)):updateEmailOrPassword(n,r,null)}function updatePassword(e,t){return updateEmailOrPassword(getModularInstance(e),null,t)}async function updateEmailOrPassword(e,t,r){const{auth:n}=e,i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),r&&(i.password=r);const s=await _logoutIfInvalidated(e,async function updateEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}(n,i));await e._updateTokensIfNecessary(s,!0)}class GenericAdditionalUserInfo{constructor(e,t,r={}){this.isNewUser=e,this.providerId=t,this.profile=r}}class FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo{constructor(e,t,r,n){super(e,t,r),this.username=n}}class FacebookAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,"facebook.com",t)}}class GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t){super(e,"github.com",t,"string"==typeof t?.login?t?.login:null)}}class GoogleAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,"google.com",t)}}class TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t,r){super(e,"twitter.com",t,r)}}function getAdditionalUserInfo(e){const{user:t,_tokenResponse:r}=e;return t.isAnonymous&&!r?{providerId:null,isNewUser:!1,profile:null}:function _fromIdTokenResponse(e){if(!e)return null;const{providerId:t}=e,r=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},n=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!t&&e?.idToken){const t=_parseToken(e.idToken)?.firebase?.sign_in_provider;if(t)return new GenericAdditionalUserInfo(n,"anonymous"!==t&&"custom"!==t?t:null)}if(!t)return null;switch(t){case"facebook.com":return new FacebookAdditionalUserInfo(n,r);case"github.com":return new GithubAdditionalUserInfo(n,r);case"google.com":return new GoogleAdditionalUserInfo(n,r);case"twitter.com":return new TwitterAdditionalUserInfo(n,r,e.screenName||null);case"custom":case"anonymous":return new GenericAdditionalUserInfo(n,null);default:return new GenericAdditionalUserInfo(n,t,r)}}(r)}function setPersistence(e,t){return getModularInstance(e).setPersistence(t)}function initializeRecaptchaConfig(e){return _initializeRecaptchaConfig(e)}async function validatePassword(e,t){return _castAuth(e).validatePassword(t)}function onIdTokenChanged(e,t,r,n){return getModularInstance(e).onIdTokenChanged(t,r,n)}function beforeAuthStateChanged(e,t,r){return getModularInstance(e).beforeAuthStateChanged(t,r)}function onAuthStateChanged(e,t,r,n){return getModularInstance(e).onAuthStateChanged(t,r,n)}function useDeviceLanguage(e){getModularInstance(e).useDeviceLanguage()}function updateCurrentUser(e,t){return getModularInstance(e).updateCurrentUser(t)}function signOut(e){return getModularInstance(e).signOut()}function revokeAccessToken(e,t){return _castAuth(e).revokeAccessToken(t)}async function deleteUser(e){return getModularInstance(e).delete()}class MultiFactorSessionImpl{constructor(e,t,r){this.type=e,this.credential=t,this.user=r}static _fromIdtoken(e,t){return new MultiFactorSessionImpl("enroll",e,t)}static _fromMfaPendingCredential(e){return new MultiFactorSessionImpl("signin",e)}toJSON(){const e="enroll"===this.type?"idToken":"pendingCredential";return{multiFactorSession:{[e]:this.credential}}}static fromJSON(e){if(e?.multiFactorSession){if(e.multiFactorSession?.pendingCredential)return MultiFactorSessionImpl._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(e.multiFactorSession?.idToken)return MultiFactorSessionImpl._fromIdtoken(e.multiFactorSession.idToken)}return null}}class MultiFactorResolverImpl{constructor(e,t,r){this.session=e,this.hints=t,this.signInResolver=r}static _fromError(e,t){const r=_castAuth(e),n=t.customData._serverResponse,i=(n.mfaInfo||[]).map((e=>MultiFactorInfoImpl._fromServerResponse(r,e)));_assert(n.mfaPendingCredential,r,"internal-error");const s=MultiFactorSessionImpl._fromMfaPendingCredential(n.mfaPendingCredential);return new MultiFactorResolverImpl(s,i,(async e=>{const i=await e._process(r,s);delete n.mfaInfo,delete n.mfaPendingCredential;const o={...n,idToken:i.idToken,refreshToken:i.refreshToken};switch(t.operationType){case"signIn":const e=await UserCredentialImpl._fromIdTokenResponse(r,t.operationType,o);return await r._updateCurrentUser(e.user),e;case"reauthenticate":return _assert(t.user,r,"internal-error"),UserCredentialImpl._forOperation(t.user,t.operationType,o);default:_fail(r,"internal-error")}}))}async resolveSignIn(e){const t=e;return this.signInResolver(t)}}function getMultiFactorResolver(e,t){const r=getModularInstance(e),n=t;return _assert(t.customData.operationType,r,"argument-error"),_assert(n.customData._serverResponse?.mfaPendingCredential,r,"argument-error"),MultiFactorResolverImpl._fromError(r,n)}function startEnrollPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:start",_addTidIfNecessary(e,t))}class MultiFactorUserImpl{constructor(e){this.user=e,this.enrolledFactors=[],e._onReload((t=>{t.mfaInfo&&(this.enrolledFactors=t.mfaInfo.map((t=>MultiFactorInfoImpl._fromServerResponse(e.auth,t))))}))}static _fromUser(e){return new MultiFactorUserImpl(e)}async getSession(){return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){const r=e,n=await this.getSession(),i=await _logoutIfInvalidated(this.user,r._process(this.user.auth,n,t));return await this.user._updateTokensIfNecessary(i),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid,r=await this.user.getIdToken();try{const e=await _logoutIfInvalidated(this.user,function withdrawMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:withdraw",_addTidIfNecessary(e,t))}(this.user.auth,{idToken:r,mfaEnrollmentId:t}));this.enrolledFactors=this.enrolledFactors.filter((({uid:e})=>e!==t)),await this.user._updateTokensIfNecessary(e),await this.user.reload()}catch(e){throw e}}}const N=new WeakMap;function multiFactor(e){const t=getModularInstance(e);return N.has(t)||N.set(t,MultiFactorUserImpl._fromUser(t)),N.get(t)}const O="__sak";class BrowserPersistenceClass{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(O,"1"),this.storage.removeItem(O),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class BrowserLocalPersistence extends BrowserPersistenceClass{constructor(){super((()=>window.localStorage),"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=_isMobileBrowser(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const r=this.storage.getItem(t),n=this.localCache[t];r!==n&&e(t,n,r)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys(((e,t,r)=>{this.notifyListeners(e,r)}));const r=e.key;t?this.detachListener():this.stopPolling();const triggerListeners=()=>{const e=this.storage.getItem(r);(t||this.localCache[r]!==e)&&this.notifyListeners(r,e)},n=this.storage.getItem(r);_isIE10()&&n!==e.newValue&&e.newValue!==e.oldValue?setTimeout(triggerListeners,10):triggerListeners()}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const e of Array.from(r))e(t?JSON.parse(t):t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:r}),!0)}))}),1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}BrowserLocalPersistence.type="LOCAL";const D=BrowserLocalPersistence;function getDocumentCookie(e){const t=e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),r=RegExp(`${t}=([^;]+)`);return document.cookie.match(r)?.[1]??null}function getCookieName(e){return`${"http:"===window.location.protocol?"__dev_":"__HOST-"}FIREBASE_${e.split(":")[3]}`}class CookiePersistence{constructor(){this.type="COOKIE",this.listenerUnsubscribes=new Map}_getFinalTarget(e){if(void 0===typeof window)return e;const t=new URL(`${window.location.origin}/__cookies__`);return t.searchParams.set("finalTarget",e),t}async _isAvailable(){return!("boolean"==typeof isSecureContext&&!isSecureContext)&&("undefined"!=typeof navigator&&"undefined"!=typeof document&&(navigator.cookieEnabled??!0))}async _set(e,t){}async _get(e){if(!this._isAvailable())return null;const t=getCookieName(e);if(window.cookieStore){const e=await window.cookieStore.get(t);return e?.value}return getDocumentCookie(t)}async _remove(e){if(!this._isAvailable())return;if(!await this._get(e))return;const t=getCookieName(e);document.cookie=`${t}=;Max-Age=34560000;Partitioned;Secure;SameSite=Strict;Path=/;Priority=High`,await fetch("/__cookies__",{method:"DELETE"}).catch((()=>{}))}_addListener(e,t){if(!this._isAvailable())return;const r=getCookieName(e);if(window.cookieStore){const cb=e=>{const n=e.changed.find((e=>e.name===r));n&&t(n.value);e.deleted.find((e=>e.name===r))&&t(null)},unsubscribe=()=>window.cookieStore.removeEventListener("change",cb);return this.listenerUnsubscribes.set(t,unsubscribe),window.cookieStore.addEventListener("change",cb)}let n=getDocumentCookie(r);const i=setInterval((()=>{const e=getDocumentCookie(r);e!==n&&(t(e),n=e)}),1e3);this.listenerUnsubscribes.set(t,(()=>clearInterval(i)))}_removeListener(e,t){const r=this.listenerUnsubscribes.get(t);r&&(r(),this.listenerUnsubscribes.delete(t))}}CookiePersistence.type="COOKIE";const L=CookiePersistence;class BrowserSessionPersistence extends BrowserPersistenceClass{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){}_removeListener(e,t){}}BrowserSessionPersistence.type="SESSION";const M=BrowserSessionPersistence;class Receiver{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t)return t;const r=new Receiver(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:r,eventType:n,data:i}=t.data,s=this.handlersMap[n];if(!s?.size)return;t.ports[0].postMessage({status:"ack",eventId:r,eventType:n});const o=Array.from(s).map((async e=>e(t.origin,i))),a=await function _allSettled(e){return Promise.all(e.map((async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})))}(o);t.ports[0].postMessage({status:"done",eventId:r,eventType:n,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function _generateEventId(e="",t=10){let r="";for(let e=0;e<t;e++)r+=Math.floor(10*Math.random());return e+r}Receiver.receivers=[];class Sender{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,r=50){const n="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!n)throw new Error("connection_unavailable");let i,s;return new Promise(((o,a)=>{const c=_generateEventId("",20);n.port1.start();const u=setTimeout((()=>{a(new Error("unsupported_event"))}),r);s={messageChannel:n,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(u),i=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(i),o(t.data.response);break;default:clearTimeout(u),clearTimeout(i),a(new Error("invalid_response"))}}},this.handlers.add(s),n.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[n.port2])})).finally((()=>{s&&this.removeMessageHandler(s)}))}}function _window(){return window}function _isWorker(){return void 0!==_window().WorkerGlobalScope&&"function"==typeof _window().importScripts}const U="firebaseLocalStorageDb",F="firebaseLocalStorage",V="fbase_key";class DBPromise{constructor(e){this.request=e}toPromise(){return new Promise(((e,t)=>{this.request.addEventListener("success",(()=>{e(this.request.result)})),this.request.addEventListener("error",(()=>{t(this.request.error)}))}))}}function getObjectStore(e,t){return e.transaction([F],t?"readwrite":"readonly").objectStore(F)}function _openDatabase(){const e=indexedDB.open(U,1);return new Promise(((t,r)=>{e.addEventListener("error",(()=>{r(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(F,{keyPath:V})}catch(e){r(e)}})),e.addEventListener("success",(async()=>{const r=e.result;r.objectStoreNames.contains(F)?t(r):(r.close(),await function _deleteDatabase(){const e=indexedDB.deleteDatabase(U);return new DBPromise(e).toPromise()}(),t(await _openDatabase()))}))}))}async function _putObject(e,t,r){const n=getObjectStore(e,!0).put({[V]:t,value:r});return new DBPromise(n).toPromise()}function _deleteObject(e,t){const r=getObjectStore(e,!0).delete(t);return new DBPromise(r).toPromise()}class IndexedDBLocalPersistence{constructor(){this.type="LOCAL",this.dbPromise=null,this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then((()=>{}),(()=>{}))}async _openDb(){return this.dbPromise||(this.dbPromise=_openDatabase(),this.dbPromise.catch((()=>{this.dbPromise=null}))),this.dbPromise}async _withRetries(e){let t=0;for(;;)try{const t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;if(this.dbPromise){(await this.dbPromise).close(),this.dbPromise=null}}}async initializeServiceWorkerMessaging(){return _isWorker()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Receiver._getInstance(function _getWorkerGlobalScope(){return _isWorker()?self:null}()),this.receiver._subscribe("keyChanged",(async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)}))),this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){if(this.activeServiceWorker=await async function _getActiveServiceWorker(){if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}(),!this.activeServiceWorker)return;this.sender=new Sender(this.activeServiceWorker);const e=await this.sender._send("ping",{},800);e&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&function _getServiceWorkerController(){return navigator?.serviceWorker?.controller||null}()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{return!!indexedDB&&(await this._withRetries((async e=>{await _putObject(e,O,"1"),await _deleteObject(e,O)})),!0)}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>(await this._withRetries((r=>_putObject(r,e,t))),this.localCache[e]=t,this.notifyServiceWorker(e))))}async _get(e){const t=await this._withRetries((t=>async function getObject(e,t){const r=getObjectStore(e,!1).get(t),n=await new DBPromise(r).toPromise();return void 0===n?null:n.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>_deleteObject(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=getObjectStore(e,!1).getAll();return new DBPromise(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],r=new Set;if(0!==e.length)for(const{fbase_key:n,value:i}of e)r.add(n),JSON.stringify(this.localCache[n])!==JSON.stringify(i)&&(this.notifyListeners(n,i),t.push(n));for(const e of Object.keys(this.localCache))this.localCache[e]&&!r.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const e of Array.from(r))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}IndexedDBLocalPersistence.type="LOCAL";const W=IndexedDBLocalPersistence;function startSignInPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:start",_addTidIfNecessary(e,t))}const x=_generateCallbackName("rcb"),H=new Delay(3e4,6e4);class ReCaptchaLoaderImpl{constructor(){this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!_window().grecaptcha?.render}load(e,t=""){return _assert(function isHostLanguageValid(e){return e.length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e)}(t),e,"argument-error"),this.shouldResolveImmediately(t)&&isV2(_window().grecaptcha)?Promise.resolve(_window().grecaptcha):new Promise(((r,n)=>{const i=_window().setTimeout((()=>{n(_createError(e,"network-request-failed"))}),H.get());_window()[x]=()=>{_window().clearTimeout(i),delete _window()[x];const s=_window().grecaptcha;if(!s||!isV2(s))return void n(_createError(e,"internal-error"));const o=s.render;s.render=(e,t)=>{const r=o(e,t);return this.counter++,r},this.hostLanguage=t,r(s)};_loadJS(`${function _recaptchaV2ScriptUrl(){return P.recaptchaV2Script}()}?${querystring({onload:x,render:"explicit",hl:t})}`).catch((()=>{clearTimeout(i),n(_createError(e,"internal-error"))}))}))}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!_window().grecaptcha?.render&&(e===this.hostLanguage||this.counter>0||this.librarySeparatelyLoaded)}}class MockReCaptchaLoaderImpl{async load(e){return new MockReCaptcha(e)}clearedOneInstance(){}}const q="recaptcha",j={theme:"light",type:"image"};class RecaptchaVerifier{constructor(e,t,r={...j}){this.parameters=r,this.type=q,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=_castAuth(e),this.isInvisible="invisible"===this.parameters.size,_assert("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");const n="string"==typeof t?document.getElementById(t):t;_assert(n,this.auth,"argument-error"),this.container=n,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=this.auth.settings.appVerificationDisabledForTesting?new MockReCaptchaLoaderImpl:new ReCaptchaLoaderImpl,this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),t=this.getAssertedRecaptcha(),r=t.getResponse(e);return r||new Promise((r=>{const tokenChange=e=>{e&&(this.tokenChangeListeners.delete(tokenChange),r(e))};this.tokenChangeListeners.add(tokenChange),this.isInvisible&&t.execute(e)}))}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch((e=>{throw this.renderPromise=null,e}))),this.renderPromise}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach((e=>{this.container.removeChild(e)}))}validateStartingState(){_assert(!this.parameters.sitekey,this.auth,"argument-error"),_assert(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),_assert("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(e){return t=>{if(this.tokenChangeListeners.forEach((e=>e(t))),"function"==typeof e)e(t);else if("string"==typeof e){const r=_window()[e];"function"==typeof r&&r(t)}}}assertNotDestroyed(){_assert(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;if(!this.isInvisible){const t=document.createElement("div");e.appendChild(t),e=t}this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){_assert(_isHttpOrHttps()&&!_isWorker(),this.auth,"internal-error"),await function domReady(){let e=null;return new Promise((t=>{"complete"!==document.readyState?(e=()=>t(),window.addEventListener("load",e)):t()})).catch((t=>{throw e&&window.removeEventListener("load",e),t}))}(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);const e=await async function getRecaptchaParams(e){return(await _performApiRequest(e,"GET","/v1/recaptchaParams")).recaptchaSiteKey||""}(this.auth);_assert(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return _assert(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class ConfirmationResultImpl{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){const t=PhoneAuthCredential._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function signInWithPhoneNumber(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t),s=await _verifyPhoneNumber(i,r,getModularInstance(n));return new ConfirmationResultImpl(s,(e=>signInWithCredential(i,e)))}async function linkWithPhoneNumber(e,t,r){const n=getModularInstance(e);await _assertLinkedStatus(!1,n,"phone");const i=await _verifyPhoneNumber(n.auth,t,getModularInstance(r));return new ConfirmationResultImpl(i,(e=>linkWithCredential(n,e)))}async function reauthenticateWithPhoneNumber(t,r,n){const i=getModularInstance(t);if(e(i.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i.auth));const s=await _verifyPhoneNumber(i.auth,r,getModularInstance(n));return new ConfirmationResultImpl(s,(e=>reauthenticateWithCredential(i,e)))}async function _verifyPhoneNumber(e,t,r){if(!e._getRecaptchaConfig())try{await _initializeRecaptchaConfig(e)}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}try{let n;if(n="string"==typeof t?{phoneNumber:t}:t,"session"in n){const t=n.session;if("phoneNumber"in n){_assert("enroll"===t.type,e,"internal-error");const i={idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:n.phoneNumber,clientType:"CLIENT_TYPE_WEB"}},s=handleRecaptchaFlow(e,i,"mfaSmsEnrollment",(async(e,t)=>{if(t.phoneEnrollmentInfo.captchaResponse===k){_assert(r?.type===q,e,"argument-error");return startEnrollPhoneMfa(e,await injectRecaptchaV2Token(e,t,r))}return startEnrollPhoneMfa(e,t)}),"PHONE_PROVIDER");return(await s.catch((e=>Promise.reject(e)))).phoneSessionInfo.sessionInfo}{_assert("signin"===t.type,e,"internal-error");const i=n.multiFactorHint?.uid||n.multiFactorUid;_assert(i,e,"missing-multi-factor-info");const s={mfaPendingCredential:t.credential,mfaEnrollmentId:i,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}},o=handleRecaptchaFlow(e,s,"mfaSmsSignIn",(async(e,t)=>{if(t.phoneSignInInfo.captchaResponse===k){_assert(r?.type===q,e,"argument-error");return startSignInPhoneMfa(e,await injectRecaptchaV2Token(e,t,r))}return startSignInPhoneMfa(e,t)}),"PHONE_PROVIDER");return(await o.catch((e=>Promise.reject(e)))).phoneResponseInfo.sessionInfo}}{const t={phoneNumber:n.phoneNumber,clientType:"CLIENT_TYPE_WEB"},i=handleRecaptchaFlow(e,t,"sendVerificationCode",(async(e,t)=>{if(t.captchaResponse===k){_assert(r?.type===q,e,"argument-error");return sendPhoneVerificationCode(e,await injectRecaptchaV2Token(e,t,r))}return sendPhoneVerificationCode(e,t)}),"PHONE_PROVIDER");return(await i.catch((e=>Promise.reject(e)))).sessionInfo}}finally{r?._reset()}}async function updatePhoneNumber(t,r){const n=getModularInstance(t);if(e(n.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth));await _link$1(n,r)}async function injectRecaptchaV2Token(e,t,r){_assert(r.type===q,e,"argument-error");const n=await r.verify();_assert("string"==typeof n,e,"argument-error");const i={...t};if("phoneEnrollmentInfo"in i){const e=i.phoneEnrollmentInfo.phoneNumber,t=i.phoneEnrollmentInfo.captchaResponse,r=i.phoneEnrollmentInfo.clientType,s=i.phoneEnrollmentInfo.recaptchaVersion;return Object.assign(i,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:n,captchaResponse:t,clientType:r,recaptchaVersion:s}}),i}if("phoneSignInInfo"in i){const e=i.phoneSignInInfo.captchaResponse,t=i.phoneSignInInfo.clientType,r=i.phoneSignInInfo.recaptchaVersion;return Object.assign(i,{phoneSignInInfo:{recaptchaToken:n,captchaResponse:e,clientType:t,recaptchaVersion:r}}),i}return Object.assign(i,{recaptchaToken:n}),i}class PhoneAuthProvider{constructor(e){this.providerId=PhoneAuthProvider.PROVIDER_ID,this.auth=_castAuth(e)}verifyPhoneNumber(e,t){return _verifyPhoneNumber(this.auth,e,getModularInstance(t))}static credential(e,t){return PhoneAuthCredential._fromVerification(e,t)}static credentialFromResult(e){const t=e;return PhoneAuthProvider.credentialFromTaggedObject(t)}static credentialFromError(e){return PhoneAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:r}=e;return t&&r?PhoneAuthCredential._fromTokenResponse(t,r):null}}function _withDefaultResolver(e,t){return t?_getInstance(t):(_assert(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}PhoneAuthProvider.PROVIDER_ID="phone",PhoneAuthProvider.PHONE_SIGN_IN_METHOD="phone";class IdpCredential extends AuthCredential{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return signInWithIdp(e,this._buildIdpRequest())}_linkToIdToken(e,t){return signInWithIdp(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return signInWithIdp(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function _signIn(e){return _signInWithCredential(e.auth,new IdpCredential(e),e.bypassAuthState)}function _reauth(e){const{auth:t,user:r}=e;return _assert(r,t,"internal-error"),_reauthenticate(r,new IdpCredential(e),e.bypassAuthState)}async function _link(e){const{auth:t,user:r}=e;return _assert(r,t,"internal-error"),_link$1(r,new IdpCredential(e),e.bypassAuthState)}class AbstractPopupRedirectOperation{constructor(e,t,r,n,i=!1){this.auth=e,this.resolver=r,this.user=n,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:r,postBody:n,tenantId:i,error:s,type:o}=e;if(s)return void this.reject(s);const a={auth:this.auth,requestUri:t,sessionId:r,tenantId:i||void 0,postBody:n||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return _signIn;case"linkViaPopup":case"linkViaRedirect":return _link;case"reauthViaPopup":case"reauthViaRedirect":return _reauth;default:_fail(this.auth,"internal-error")}}resolve(e){debugAssert(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){debugAssert(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const G=new Delay(2e3,1e4);async function signInWithPopup(t,r,n){if(e(t.app))return Promise.reject(_createError(t,"operation-not-supported-in-this-environment"));const i=_castAuth(t);_assertInstanceOf(t,r,FederatedAuthProvider);const s=_withDefaultResolver(i,n);return new PopupOperation(i,"signInViaPopup",r,s).executeNotNull()}async function reauthenticateWithPopup(t,r,n){const i=getModularInstance(t);if(e(i.auth.app))return Promise.reject(_createError(i.auth,"operation-not-supported-in-this-environment"));_assertInstanceOf(i.auth,r,FederatedAuthProvider);const s=_withDefaultResolver(i.auth,n);return new PopupOperation(i.auth,"reauthViaPopup",r,s,i).executeNotNull()}async function linkWithPopup(e,t,r){const n=getModularInstance(e);_assertInstanceOf(n.auth,t,FederatedAuthProvider);const i=_withDefaultResolver(n.auth,r);return new PopupOperation(n.auth,"linkViaPopup",t,i,n).executeNotNull()}class PopupOperation extends AbstractPopupRedirectOperation{constructor(e,t,r,n,i){super(e,t,n,i),this.provider=r,this.authWindow=null,this.pollId=null,PopupOperation.currentPopupAction&&PopupOperation.currentPopupAction.cancel(),PopupOperation.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return _assert(e,this.auth,"internal-error"),e}async onExecution(){debugAssert(1===this.filter.length,"Popup operations only handle one event");const e=_generateEventId();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch((e=>{this.reject(e)})),this.resolver._isIframeWebStorageSupported(this.auth,(e=>{e||this.reject(_createError(this.auth,"web-storage-unsupported"))})),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(_createError(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,PopupOperation.currentPopupAction=null}pollUserCancellation(){const poll=()=>{this.authWindow?.window?.closed?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(_createError(this.auth,"popup-closed-by-user"))}),8e3):this.pollId=window.setTimeout(poll,G.get())};poll()}}PopupOperation.currentPopupAction=null;const B=new Map;class RedirectAction extends AbstractPopupRedirectOperation{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let e=B.get(this.auth._key());if(!e){try{const t=await async function _getAndClearPendingRedirectStatus(e,t){const r=pendingRedirectKey(t),n=resolverPersistence(e);if(!await n._isAvailable())return!1;const i="true"===await n._get(r);return await n._remove(r),i}(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}B.set(this.auth._key(),e)}return this.bypassAuthState||B.set(this.auth._key(),(()=>Promise.resolve(null))),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function _setPendingRedirectStatus(e,t){return resolverPersistence(e)._set(pendingRedirectKey(t),"true")}function _overrideRedirectResult(e,t){B.set(e._key(),t)}function resolverPersistence(e){return _getInstance(e._redirectPersistence)}function pendingRedirectKey(e){return _persistenceKeyName("pendingRedirect",e.config.apiKey,e.name)}function signInWithRedirect(t,r,n){return async function _signInWithRedirect(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t);_assertInstanceOf(t,r,FederatedAuthProvider),await i._initializationPromise;const s=_withDefaultResolver(i,n);return await _setPendingRedirectStatus(s,i),s._openRedirect(i,r,"signInViaRedirect")}(t,r,n)}function reauthenticateWithRedirect(t,r,n){return async function _reauthenticateWithRedirect(t,r,n){const i=getModularInstance(t);if(_assertInstanceOf(i.auth,r,FederatedAuthProvider),e(i.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i.auth));await i.auth._initializationPromise;const s=_withDefaultResolver(i.auth,n);await _setPendingRedirectStatus(s,i.auth);const o=await prepareUserForRedirect(i);return s._openRedirect(i.auth,r,"reauthViaRedirect",o)}(t,r,n)}function linkWithRedirect(e,t,r){return async function _linkWithRedirect(e,t,r){const n=getModularInstance(e);_assertInstanceOf(n.auth,t,FederatedAuthProvider),await n.auth._initializationPromise;const i=_withDefaultResolver(n.auth,r);await _assertLinkedStatus(!1,n,t.providerId),await _setPendingRedirectStatus(i,n.auth);const s=await prepareUserForRedirect(n);return i._openRedirect(n.auth,t,"linkViaRedirect",s)}(e,t,r)}async function getRedirectResult(e,t){return await _castAuth(e)._initializationPromise,_getRedirectResult(e,t,!1)}async function _getRedirectResult(t,r,n=!1){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t),s=_withDefaultResolver(i,r),o=new RedirectAction(i,s,n),a=await o.execute();return a&&!n&&(delete a.user._redirectEventId,await i._persistUserIfCurrent(a.user),await i._setRedirectUser(null,r)),a}async function prepareUserForRedirect(e){const t=_generateEventId(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class AuthEventManager{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach((r=>{this.isEventForConsumer(e,r)&&(t=!0,this.sendToConsumer(e,r),this.saveEventToCache(e))})),this.hasHandledPotentialRedirect||!function isRedirectEvent(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return isNullRedirectEvent(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){if(e.error&&!isNullRedirectEvent(e)){const r=e.error.code?.split("auth/")[1]||"internal-error";t.onError(_createError(this.auth,r))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const r=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(eventUid(e))}saveEventToCache(e){this.cachedEventUids.add(eventUid(e)),this.lastProcessedEventTime=Date.now()}}function eventUid(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function isNullRedirectEvent({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===t?.code}const z=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,K=/^https?/;async function _validateOrigin(e){if(e.config.emulator)return;const{authorizedDomains:t}=await async function _getProjectConfig(e,t={}){return _performApiRequest(e,"GET","/v1/projects",t)}(e);for(const e of t)try{if(matchDomain(e))return}catch{}_fail(e,"unauthorized-domain")}function matchDomain(e){const t=_getCurrentUrl(),{protocol:r,hostname:n}=new URL(t);if(e.startsWith("chrome-extension://")){const i=new URL(e);return""===i.hostname&&""===n?"chrome-extension:"===r&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===r&&i.hostname===n}if(!K.test(r))return!1;if(z.test(e))return n===e;const i=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+i+"|"+i+")$","i").test(n)}const $=new Delay(3e4,6e4);function resetUnloadedGapiModules(){const e=_window().___jsl;if(e?.H)for(const t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let t=0;t<e.CP.length;t++)e.CP[t]=null}function loadGapi(e){return new Promise(((t,r)=>{function loadGapiIframe(){resetUnloadedGapiModules(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{resetUnloadedGapiModules(),r(_createError(e,"network-request-failed"))},timeout:$.get()})}if(_window().gapi?.iframes?.Iframe)t(gapi.iframes.getContext());else{if(!_window().gapi?.load){const t=_generateCallbackName("iframefcb");return _window()[t]=()=>{gapi.load?loadGapiIframe():r(_createError(e,"network-request-failed"))},_loadJS(`${function _gapiScriptUrl(){return P.gapiScript}()}?onload=${t}`).catch((e=>r(e)))}loadGapiIframe()}})).catch((e=>{throw J=null,e}))}let J=null;const Y=new Delay(5e3,15e3),X={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Q=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function getIframeUrl(e){const t=e.config;_assert(t.authDomain,e,"auth-domain-config-required");const r=t.emulator?_emulatorUrl(t,"emulator/auth/iframe"):`https://${e.config.authDomain}/__/auth/iframe`,n={apiKey:t.apiKey,appName:e.name,v:i},s=Q.get(e.config.apiHost);s&&(n.eid=s);const o=e._getFrameworks();return o.length&&(n.fw=o.join(",")),`${r}?${querystring(n).slice(1)}`}async function _openIframe(e){const t=await function _loadGapi(e){return J=J||loadGapi(e),J}(e),r=_window().gapi;return _assert(r,e,"internal-error"),t.open({where:document.body,url:getIframeUrl(e),messageHandlersFilter:r.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:X,dontclear:!0},(t=>new Promise((async(r,n)=>{await t.restyle({setHideOnLeave:!1});const i=_createError(e,"network-request-failed"),s=_window().setTimeout((()=>{n(i)}),Y.get());function clearTimerAndResolve(){_window().clearTimeout(s),r(t)}t.ping(clearTimerAndResolve).then(clearTimerAndResolve,(()=>{n(i)}))}))))}const Z={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class AuthPopup{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function _open(e,t,r,n=500,i=600){const s=Math.max((window.screen.availHeight-i)/2,0).toString(),o=Math.max((window.screen.availWidth-n)/2,0).toString();let a="";const c={...Z,width:n.toString(),height:i.toString(),top:s,left:o},u=getUA().toLowerCase();r&&(a=_isChromeIOS(u)?"_blank":r),_isFirefox(u)&&(t=t||"http://localhost",c.scrollbars="yes");const d=Object.entries(c).reduce(((e,[t,r])=>`${e}${t}=${r},`),"");if(function _isIOSStandalone(e=getUA()){return _isIOS(e)&&!!window.navigator?.standalone}(u)&&"_self"!==a)return function openAsNewWindowIOS(e,t){const r=document.createElement("a");r.href=e,r.target=t;const n=document.createEvent("MouseEvent");n.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),r.dispatchEvent(n)}(t||"",a),new AuthPopup(null);const l=window.open(t||"",a,d);_assert(l,e,"popup-blocked");try{l.focus()}catch(e){}return new AuthPopup(l)}const ee="__/auth/handler",te="emulator/auth/handler",re=encodeURIComponent("fac");async function _getRedirectUrl(e,t,r,n,s,o){_assert(e.config.authDomain,e,"auth-domain-config-required"),_assert(e.config.apiKey,e,"invalid-api-key");const a={apiKey:e.config.apiKey,appName:e.name,authType:r,redirectUrl:n,v:i,eventId:s};if(t instanceof FederatedAuthProvider){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",function isEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(o||{}))a[e]=t}if(t instanceof BaseOAuthProvider){const e=t.getScopes().filter((e=>""!==e));e.length>0&&(a.scopes=e.join(","))}e.tenantId&&(a.tid=e.tenantId);const c=a;for(const e of Object.keys(c))void 0===c[e]&&delete c[e];const u=await e._getAppCheckToken(),d=u?`#${re}=${encodeURIComponent(u)}`:"";return`${function getHandlerBase({config:e}){if(!e.emulator)return`https://${e.authDomain}/${ee}`;return _emulatorUrl(e,te)}(e)}?${querystring(c).slice(1)}${d}`}const ne="webStorageSupport";const ie=class BrowserPopupRedirectResolver{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=M,this._completeRedirectFn=_getRedirectResult,this._overrideRedirectResult=_overrideRedirectResult}async _openPopup(e,t,r,n){debugAssert(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()");return _open(e,await _getRedirectUrl(e,t,r,_getCurrentUrl(),n),_generateEventId())}async _openRedirect(e,t,r,n){await this._originValidation(e);return function _setWindowLocation(e){_window().location.href=e}(await _getRedirectUrl(e,t,r,_getCurrentUrl(),n)),new Promise((()=>{}))}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:r}=this.eventManagers[t];return e?Promise.resolve(e):(debugAssert(r,"If manager is not set, promise should be"),r)}const r=this.initAndGetManager(e);return this.eventManagers[t]={promise:r},r.catch((()=>{delete this.eventManagers[t]})),r}async initAndGetManager(e){const t=await _openIframe(e),r=new AuthEventManager(e);return t.register("authEvent",(t=>{_assert(t?.authEvent,e,"invalid-auth-event");return{status:r.onEvent(t.authEvent)?"ACK":"ERROR"}}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:r},this.iframes[e._key()]=t,r}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(ne,{type:ne},(r=>{const n=r?.[0]?.[ne];void 0!==n&&t(!!n),_fail(e,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=_validateOrigin(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return _isMobileBrowser()||_isSafari()||_isIOS()}};class MultiFactorAssertionImpl{constructor(e){this.factorId=e}_process(e,t,r){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,r);case"signin":return this._finalizeSignIn(e,t.credential);default:return debugFail("unexpected MultiFactorSessionType")}}}class PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new PhoneMultiFactorAssertionImpl(e)}_finalizeEnroll(e,t,r){return function finalizeEnrollPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,t))}(e,{idToken:t,displayName:r,phoneVerificationInfo:this.credential._makeVerificationRequest()})}_finalizeSignIn(e,t){return function finalizeSignInPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,t))}(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()})}}class PhoneMultiFactorGenerator{constructor(){}static assertion(e){return PhoneMultiFactorAssertionImpl._fromCredential(e)}}PhoneMultiFactorGenerator.FACTOR_ID="phone";class TotpMultiFactorGenerator{static assertionForEnrollment(e,t){return TotpMultiFactorAssertionImpl._fromSecret(e,t)}static assertionForSignIn(e,t){return TotpMultiFactorAssertionImpl._fromEnrollmentId(e,t)}static async generateSecret(e){const t=e;_assert(void 0!==t.user?.auth,"internal-error");const r=await function startEnrollTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:start",_addTidIfNecessary(e,t))}(t.user.auth,{idToken:t.credential,totpEnrollmentInfo:{}});return TotpSecret._fromStartTotpMfaEnrollmentResponse(r,t.user.auth)}}TotpMultiFactorGenerator.FACTOR_ID="totp";class TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e,t,r){super("totp"),this.otp=e,this.enrollmentId=t,this.secret=r}static _fromSecret(e,t){return new TotpMultiFactorAssertionImpl(t,void 0,e)}static _fromEnrollmentId(e,t){return new TotpMultiFactorAssertionImpl(t,e)}async _finalizeEnroll(e,t,r){return _assert(void 0!==this.secret,e,"argument-error"),function finalizeEnrollTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,t))}(e,{idToken:t,displayName:r,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,t){_assert(void 0!==this.enrollmentId&&void 0!==this.otp,e,"argument-error");const r={verificationCode:this.otp};return function finalizeSignInTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,t))}(e,{mfaPendingCredential:t,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:r})}}class TotpSecret{constructor(e,t,r,n,i,s,o){this.sessionInfo=s,this.auth=o,this.secretKey=e,this.hashingAlgorithm=t,this.codeLength=r,this.codeIntervalSeconds=n,this.enrollmentCompletionDeadline=i}static _fromStartTotpMfaEnrollmentResponse(e,t){return new TotpSecret(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,t)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,t){let r=!1;return(_isEmptyString(e)||_isEmptyString(t))&&(r=!0),r&&(_isEmptyString(e)&&(e=this.auth.currentUser?.email||"unknownuser"),_isEmptyString(t)&&(t=this.auth.name)),`otpauth://totp/${t}:${e}?secret=${this.secretKey}&issuer=${t}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}}function _isEmptyString(e){return void 0===e||0===e?.length}var se="@firebase/auth",oe="1.13.3";class AuthInterop{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){if(this.assertAuthConfigured(),await this.auth._initializationPromise,!this.auth.currentUser)return null;return{accessToken:await this.auth.currentUser.getIdToken(e)}}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged((t=>{e(t?.stsTokenManager.accessToken||null)}));this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){_assert(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}const ae=getExperimentalSetting("authIdTokenMaxAge")||300;let ce=null;function getAuth(e=n()){const t=_getProvider(e,"auth");if(t.isInitialized())return t.getImmediate();const r=initializeAuth(e,{popupRedirectResolver:ie,persistence:[W,D,M]}),i=getExperimentalSetting("authTokenSyncURL");if(i&&"boolean"==typeof isSecureContext&&isSecureContext){const e=new URL(i,location.origin);if(location.origin===e.origin){const t=(s=e.toString(),async e=>{const t=e&&await e.getIdTokenResult(),r=t&&((new Date).getTime()-Date.parse(t.issuedAtTime))/1e3;if(r&&r>ae)return;const n=t?.token;ce!==n&&(ce=n,await fetch(s,{method:n?"POST":"DELETE",headers:n?{Authorization:`Bearer ${n}`}:{}}))});beforeAuthStateChanged(r,t,(()=>t(r.currentUser))),onIdTokenChanged(r,(e=>t(e)))}}var s;const o=(a="auth",getDefaults()?.emulatorHosts?.[a]);var a;return o&&connectAuthEmulator(r,`http://${o}`),r}!function _setExternalJSProvider(e){P=e}({loadJS:e=>new Promise(((t,r)=>{const n=document.createElement("script");n.setAttribute("src",e),n.onload=t,n.onerror=e=>{const t=_createError("internal-error");t.customData=e,r(t)},n.type="text/javascript",n.charset="UTF-8",function getScriptParentElement(){return document.getElementsByTagName("head")?.[0]??document}().appendChild(n)})),gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="}),function registerAuth(e){t(new Component("auth",((t,{options:r})=>{const n=t.getProvider("app").getImmediate(),i=t.getProvider("heartbeat"),s=t.getProvider("app-check-internal"),{apiKey:o,authDomain:a}=n.options;_assert(o&&!o.includes(":"),"invalid-api-key",{appName:n.name});const c={apiKey:o,authDomain:a,clientPlatform:e,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:_getClientVersion(e)},u=new AuthImpl(n,i,s,c);return function _initializeAuthInstance(e,t){const r=t?.persistence||[],n=(Array.isArray(r)?r:[r]).map(_getInstance);t?.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(n,t?.popupRedirectResolver)}(u,r),u}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,r)=>{e.getProvider("auth-internal").initialize()}))),t(new Component("auth-internal",(e=>(e=>new AuthInterop(e))(_castAuth(e.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),r(se,oe,function getVersionForPlatform(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}(e)),r(se,oe,"esm2020")}("Browser");export{m as ActionCodeOperation,ActionCodeURL,AuthCredential,v as AuthErrorCodes,EmailAuthCredential,EmailAuthProvider,FacebookAuthProvider,l as FactorId,GithubAuthProvider,GoogleAuthProvider,OAuthCredential,OAuthProvider,f as OperationType,PhoneAuthCredential,PhoneAuthProvider,PhoneMultiFactorGenerator,h as ProviderId,RecaptchaVerifier,SAMLAuthProvider,p as SignInMethod,TotpMultiFactorGenerator,TotpSecret,TwitterAuthProvider,applyActionCode,beforeAuthStateChanged,L as browserCookiePersistence,D as browserLocalPersistence,ie as browserPopupRedirectResolver,M as browserSessionPersistence,checkActionCode,confirmPasswordReset,connectAuthEmulator,createUserWithEmailAndPassword,g as debugErrorMap,deleteUser,fetchSignInMethodsForEmail,getAdditionalUserInfo,getAuth,getIdToken,getIdTokenResult,getMultiFactorResolver,getRedirectResult,S as inMemoryPersistence,W as indexedDBLocalPersistence,initializeAuth,initializeRecaptchaConfig,isSignInWithEmailLink,linkWithCredential,linkWithPhoneNumber,linkWithPopup,linkWithRedirect,multiFactor,onAuthStateChanged,onIdTokenChanged,parseActionCodeURL,_ as prodErrorMap,reauthenticateWithCredential,reauthenticateWithPhoneNumber,reauthenticateWithPopup,reauthenticateWithRedirect,reload,revokeAccessToken,sendEmailVerification,sendPasswordResetEmail,sendSignInLinkToEmail,setPersistence,signInAnonymously,signInWithCredential,signInWithCustomToken,signInWithEmailAndPassword,signInWithEmailLink,signInWithPhoneNumber,signInWithPopup,signInWithRedirect,signOut,unlink,updateCurrentUser,updateEmail,updatePassword,updatePhoneNumber,updateProfile,useDeviceLanguage,validatePassword,verifyBeforeUpdateEmail,verifyPasswordResetCode};
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(Xa,ei){try{!(function(){function A(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var x,F=A(Xa);function B(){try{return"object"==typeof indexedDB}catch(e){return!1}}class L extends Error{constructor(e,t,a){super(t),this.code=e,this.customData=a,this.name="FirebaseError",Object.setPrototypeOf(this,L.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,i.prototype.create)}}class i{constructor(e,t,a){this.service=e,this.serviceName=t,this.errors=a}create(e,...t){var i,a=t[0]||{},n=this.service+"/"+e,r=this.errors[e],r=r?(i=a,r.replace(H,(e,t)=>{var a=i[t];return null!=a?String(a):`<${t}?>`})):"Error",r=this.serviceName+`: ${r} (${n}).`;return new L(n,r,a)}}let H=/\{\$([^}]+)}/g;function n(e){return e&&e._delegate?e._delegate:e}class e{constructor(e,t,a){this.name=e,this.instanceFactory=t,this.type=a,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let U=(t,e)=>e.some(e=>t instanceof e),q,V;let W=new WeakMap,$=new WeakMap,Q=new WeakMap,G=new WeakMap,J=new WeakMap;let z={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return $.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Q.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return c(e[t])},set(e,t,a){return e[t]=a,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function Z(i){return i!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(V=V||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(i)?function(...e){return i.apply(X(this),e),c(W.get(this))}:function(...e){return c(i.apply(X(this),e))}:function(e,...t){var a=i.call(X(this),e,...t);return Q.set(a,e.sort?e.sort():[e]),c(a)}}function Y(e){var r,t;return"function"==typeof e?Z(e):(e instanceof IDBTransaction&&(r=e,$.has(r)||(t=new Promise((e,t)=>{let a=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",n),r.removeEventListener("abort",n)},i=()=>{e(),a()},n=()=>{t(r.error||new DOMException("AbortError","AbortError")),a()};r.addEventListener("complete",i),r.addEventListener("error",n),r.addEventListener("abort",n)}),$.set(r,t))),U(e,q=q||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,z):e)}function c(e){var r,t;return e instanceof IDBRequest?(r=e,(t=new Promise((e,t)=>{let a=()=>{r.removeEventListener("success",i),r.removeEventListener("error",n)},i=()=>{e(c(r.result)),a()},n=()=>{t(r.error),a()};r.addEventListener("success",i),r.addEventListener("error",n)})).then(e=>{e instanceof IDBCursor&&W.set(e,r)}).catch(()=>{}),J.set(t,r),t):G.has(e)?G.get(e):((t=Y(e))!==e&&(G.set(e,t),J.set(t,e)),t)}let X=e=>J.get(e);function t(e,t,{blocked:a,upgrade:i,blocking:n,terminated:r}={}){let o=indexedDB.open(e,t);var s=c(o);return i&&o.addEventListener("upgradeneeded",e=>{i(c(o.result),e.oldVersion,e.newVersion,c(o.transaction),e)}),a&&o.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),s.then(e=>{r&&e.addEventListener("close",()=>r()),n&&e.addEventListener("versionchange",e=>n(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}function a(e,{blocked:t}={}){var a=indexedDB.deleteDatabase(e);return t&&a.addEventListener("blocked",e=>t(e.oldVersion,e)),c(a).then(()=>{})}let ee=["get","getKey","getAll","getAllKeys","count"],te=["put","add","delete","clear"],ae=new Map;function ie(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(ae.get(t))return ae.get(t);let n=t.replace(/FromIndex$/,""),r=t!==n,o=te.includes(n);var a;return n in(r?IDBIndex:IDBObjectStore).prototype&&(o||ee.includes(n))?(a=async function(e,...t){var a=this.transaction(e,o?"readwrite":"readonly");let i=a.store;return r&&(i=i.index(t.shift())),(await Promise.all([i[n](...t),o&&a.done]))[0]},ae.set(t,a),a):void 0}}z={...x=z,get:(e,t,a)=>ie(e,t)||x.get(e,t,a),has:(e,t)=>!!ie(e,t)||x.has(e,t)};var ne="@firebase/installations",re="0.6.22";let oe=1e4,se="w:"+re,ce="FIS_v2",de="https://firebaseinstallations.googleapis.com/v1",le=36e5;var r,o,d,s;let l=new i("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function pe(e){return e instanceof L&&e.code.includes("request-failed")}function ue({projectId:e}){return de+`/projects/${e}/installations`}function fe(e){return{token:e.token,requestStatus:2,expiresIn:Number(e.expiresIn.replace("s","000")),creationTime:Date.now()}}async function ge(e,t){var a=(await t.json()).error;return l.create("request-failed",{requestName:e,serverCode:a.code,serverMessage:a.message,serverStatus:a.status})}function he({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function we(e,{refreshToken:t}){var a=he(e);return a.append("Authorization",(e=t,ce+" "+e)),a}async function be(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function me(t){return new Promise(e=>{setTimeout(e,t)})}let ve=/^[cdef][\w-]{21}$/,ye="";function ke(){try{var e=new Uint8Array(17),t=((self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16,(e=>btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_"))(e).substr(0,22));return ve.test(t)?t:ye}catch{return ye}}function p(e){return e.appName+"!"+e.appId}let u=new Map;function Ie(e,t){var a=p(e),e=(Se(a,t),a),a=Te();a&&a.postMessage({key:e,fid:t}),De()}function Se(e,t){var a=u.get(e);if(a)for(var i of a)i(t)}let f=null;function Te(){return!f&&"BroadcastChannel"in self&&((f=new BroadcastChannel("[Firebase] FID Change")).onmessage=e=>{Se(e.data.key,e.data.fid)}),f}function De(){0===u.size&&f&&(f.close(),f=null)}let Ce="firebase-installations-database",_e=1,g="firebase-installations-store",Ee=null;function Me(){return Ee=Ee||t(Ce,_e,{upgrade:(e,t)=>{0===t&&e.createObjectStore(g)}})}async function h(e,t){var a=p(e),i=(await Me()).transaction(g,"readwrite"),n=i.objectStore(g),r=await n.get(a);return await n.put(t,a),await i.done,r&&r.fid===t.fid||Ie(e,t.fid),t}async function je(e){var t=p(e),a=(await Me()).transaction(g,"readwrite");await a.objectStore(g).delete(t),await a.done}async function w(e,t){var a=p(e),i=(await Me()).transaction(g,"readwrite"),n=i.objectStore(g),r=await n.get(a),o=t(r);return void 0===o?await n.delete(a):await n.put(o,a),await i.done,!o||r&&r.fid===o.fid||Ie(e,o.fid),o}async function Pe(a){let i;var e=await w(a.appConfig,e=>{var t=Ne(e||{fid:ke(),registrationStatus:0}),t=((e,t)=>{var a,i;return 0===t.registrationStatus?navigator.onLine?(a={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},i=(async(t,a)=>{try{var e=await(async({appConfig:e,heartbeatServiceProvider:t},{fid:a})=>{let i=ue(e);var n=he(e),r=((r=t.getImmediate({optional:!0}))&&(r=await r.getHeartbeatsHeader())&&n.append("x-firebase-client",r),{fid:a,authVersion:ce,appId:e.appId,sdkVersion:se});let o={method:"POST",headers:n,body:JSON.stringify(r)};if((n=await be(()=>fetch(i,o))).ok)return{fid:(r=await n.json()).fid||a,registrationStatus:2,refreshToken:r.refreshToken,authToken:fe(r.authToken)};throw await ge("Create Installation",n)})(t,a);return h(t.appConfig,e)}catch(e){throw pe(e)&&409===e.customData.serverCode?await je(t.appConfig):await h(t.appConfig,{fid:a.fid,registrationStatus:0}),e}})(e,a),{installationEntry:a,registrationPromise:i}):(a=Promise.reject(l.create("app-offline")),{installationEntry:t,registrationPromise:a}):1===t.registrationStatus?{installationEntry:t,registrationPromise:(async e=>{let t=await Ke(e.appConfig);for(;1===t.registrationStatus;)await me(100),t=await Ke(e.appConfig);var a,i;return 0!==t.registrationStatus?t:({installationEntry:a,registrationPromise:i}=await Pe(e),i||a)})(e)}:{installationEntry:t}})(a,t);return i=t.registrationPromise,t.installationEntry});return e.fid===ye?{installationEntry:await i}:{installationEntry:e,registrationPromise:i}}function Ke(e){return w(e,e=>{if(e)return Ne(e);throw l.create("installation-not-found")})}function Ne(e){var t;return 1===(t=e).registrationStatus&&t.registrationTime+oe<Date.now()?{fid:e.fid,registrationStatus:0}:e}async function Oe({appConfig:e,heartbeatServiceProvider:t},a){[n,r]=[e,a.fid];let i=ue(n)+`/${r}/authTokens:generate`;var n,r,o=we(e,a),s=t.getImmediate({optional:!0}),s=(s&&(s=await s.getHeartbeatsHeader())&&o.append("x-firebase-client",s),{installation:{sdkVersion:se,appId:e.appId}});let c={method:"POST",headers:o,body:JSON.stringify(s)};o=await be(()=>fetch(i,c));if(o.ok)return fe(await o.json());throw await ge("Generate Auth Token",o)}async function Re(i,n=!1){let r;var e=await w(i.appConfig,e=>{if(!xe(e))throw l.create("not-registered");var t,a=e.authToken;if(n||2!==(t=a).requestStatus||(e=>{var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+le})(t)){if(1===a.requestStatus)return r=(async(e,t)=>{let a=await Ae(e.appConfig);for(;1===a.authToken.requestStatus;)await me(100),a=await Ae(e.appConfig);var i=a.authToken;return 0===i.requestStatus?Re(e,t):i})(i,n),e;if(navigator.onLine)return t=e,a={requestStatus:1,requestTime:Date.now()},a={...t,authToken:a},r=(async(t,a)=>{try{var e=await Oe(t,a),i={...a,authToken:e};return await h(t.appConfig,i),e}catch(e){var n;throw!pe(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(n={...a,authToken:{requestStatus:0}},await h(t.appConfig,n)):await je(t.appConfig),e}})(i,a),a;throw l.create("app-offline")}return e});return r?await r:e.authToken}function Ae(e){return w(e,e=>{var t,a;if(xe(e))return t=e.authToken,1===(a=t).requestStatus&&a.requestTime+oe<Date.now()?{...e,authToken:{requestStatus:0}}:e;throw l.create("not-registered")})}function xe(e){return void 0!==e&&2===e.registrationStatus}async function Fe(e,t=!1){var a=e,i=(await(!(i=(await Pe(a)).registrationPromise)||!await i),await Re(a,t));return i.token}function Be(t,n){let r=t.appConfig;{t=r;var a=n,i=(Te(),p(t));let e=u.get(i);e||(e=new Set,u.set(i,e)),e.add(a)}return()=>{var e,t,a,i;e=r,t=n,a=p(e),(i=u.get(a))&&(i.delete(t),0===i.size&&u.delete(a),De())}}function Le(e){return l.create("missing-app-config-values",{valueName:e})}let He="installations",Ue=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:(e=>{if(!e||!e.options)throw Le("App Configuration");if(!e.name)throw Le("App Name");var t;for(t of["projectId","apiKey","appId"])if(!e.options[t])throw Le(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}})(t),heartbeatServiceProvider:ei._getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},qe=e=>{var t=e.getProvider("app").getImmediate();let a=ei._getProvider(t,He).getImmediate();return{getId:()=>(async e=>{var t=e,{installationEntry:a,registrationPromise:i}=await Pe(t);return(i||Re(t)).catch(console.error),a.fid})(a),getToken:e=>Fe(a,e)}};ei._registerComponent(new e(He,Ue,"PUBLIC")),ei._registerComponent(new e("installations-internal",qe,"PRIVATE")),ei.registerVersion(ne,re),ei.registerVersion(ne,re,"esm2020");let Ve="/firebase-messaging-sw.js",We="/firebase-cloud-messaging-push-scope",$e="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",Qe="https://fcmregistrations.googleapis.com/v1",Ge="google.c.a.c_id",Je="google.c.a.c_l",ze="google.c.a.ts",Ze="google.c.a.e",Ye=1e4;function b(e){var t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Xe(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),a=atob(t),i=new Uint8Array(a.length);for(let n=0;n<a.length;++n)i[n]=a.charCodeAt(n);return i}(s=r=r||{}).PUSH_RECEIVED="push-received",s.NOTIFICATION_CLICKED="notification-clicked",s.FID_REGISTERED="fid-registered";let et="fcm_token_details_db",tt=5,at="fcm_token_object_Store";async function it(o){if("databases"in indexedDB&&!(await indexedDB.databases()).map(e=>e.name).includes(et))return null;let s=null;return(await t(et,tt,{upgrade:async(e,t,a,i)=>{var n,r;t<2||e.objectStoreNames.contains(at)&&(n=await(r=i.objectStore(at)).index("fcmSenderId").get(o),await r.clear(),n)&&(2===t?(r=n).auth&&r.p256dh&&r.endpoint&&(s={token:r.fcmToken,createTime:r.createTime??Date.now(),subscriptionOptions:{auth:r.auth,p256dh:r.p256dh,endpoint:r.endpoint,swScope:r.swScope,vapidKey:"string"==typeof r.vapidKey?r.vapidKey:b(r.vapidKey)}}):3===t?(r=n,s={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:b(r.auth),p256dh:b(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:b(r.vapidKey)}}):4===t&&(r=n,s={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:b(r.auth),p256dh:b(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:b(r.vapidKey)}}))}})).close(),await a(et),await a("fcm_vapid_details_db"),await a("undefined"),(e=>{var t;if(e&&e.subscriptionOptions)return t=e.subscriptionOptions,"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length})(s)?s:null}let m=new i("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","fid-registration-failed":"A problem occurred while creating an FCM registration via FID: {$errorInfo}","fid-unregister-failed":"A problem occurred while unregistering the FCM registration via FID: {$errorInfo}","fid-registration-idb-schema-unavailable":"Unable to read or persist FID registration metadata because the messaging IndexedDB schema is unavailable (for example, the database could not be upgraded to the latest version).","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used.","invalid-on-registered-handler":"No onRegistered callback handler was provided or registered. Implement onRegistered() before register()."}),nt="firebase-messaging-database",rt=2,v="firebase-messaging-store",y="firebase-messaging-fid-registration-store",ot={openDB:t,deleteDB:a},k=null;function st(n){return{upgrade:(e,t)=>{var a=e,i=n;switch(t){case 0:if(a.createObjectStore(v),1===i)break;case 1:2===i&&a.createObjectStore(y)}},blocked:()=>{},blocking:(e,t,a)=>{k=null,a.target?.close()},terminated:()=>{k=null}}}function I(){var e;return k||(e=ot.openDB(nt,rt,st(2)),k=e.catch(()=>ot.openDB(nt,rt-1,st(1)))),k}function ct(e,t){return e.objectStoreNames.contains(t)}function dt(e){if(!ct(e,y))throw m.create("fid-registration-idb-schema-unavailable")}async function lt(e){var t=S(e),t=await(await I()).transaction(v).objectStore(v).get(t);return t||((t=await it(e.appConfig.senderId))?(await pt(e,t),t):void 0)}async function pt(e,t){var a=S(e),i=await I(),n=[v],r=ct(i,y),i=(r&&n.push(y),i.transaction(n,"readwrite"));return await i.objectStore(v).put(t,a),r&&await i.objectStore(y).delete(a),await i.done,t}async function ut(e){var t=S(e),a=await I();return dt(a),a.transaction(y).objectStore(y).get(t)}function S({appConfig:e}){return e.appId}let ft="@firebase/messaging",gt="0.13.0",ht=3,wt=1e3;async function bt(e,t){var a=await D(e),i=yt(t,e.appConfig.appName,!0);let n={method:"POST",headers:a,body:JSON.stringify(i)},r;try{r=await(async(e,t,a)=>{let i;for(let n=0;n<t;n++)try{return await e()}catch(e){if(i=e,n<t-1){let t=a*Math.pow(2,n);await new Promise(e=>setTimeout(e,t))}}throw i})(()=>fetch(T(e.appConfig),n),ht,wt)}catch(e){throw m.create("fid-registration-failed",{errorInfo:e?.toString()})}if(r.ok)return{responseFid:await(async e=>{var t=await e.text();if(!t.trim())throw m.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is empty"});let a;try{a=JSON.parse(t)}catch{throw m.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is not valid JSON"})}if("string"!=typeof(t=a.name)||0===t.length)throw m.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response did not include a non-empty name"});if(-1!==(t=(e=t).indexOf(mt))){t=e.slice(t+mt.length);if(0<t.length)return t}throw m.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response name is not a valid registration resource name"})})(r)};let o;try{o=await r.json()}catch(e){throw m.create("fid-registration-failed",{errorInfo:r.statusText})}a=o.error?.message??r.statusText;throw m.create("fid-registration-failed",{errorInfo:a})}let mt="/registrations/";async function vt(e,t){var a={method:"DELETE",headers:await D(e)};try{var i,n=await(await fetch(T(e.appConfig)+"/"+t,a)).json();if(n.error)throw i=n.error.message,m.create("token-unsubscribe-failed",{errorInfo:i})}catch(e){throw m.create("token-unsubscribe-failed",{errorInfo:e?.toString()})}}function T({projectId:e}){return Qe+`/projects/${e}/registrations`}async function D({appConfig:e,installations:t}){var a=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":"FIS "+a})}function yt({p256dh:e,auth:t,endpoint:a,vapidKey:i,swScope:n},r,o){var s={web:{origin:((e,t)=>{try{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e))return new URL(e).host}catch{}try{if("undefined"!=typeof self&&self.location?.href)return new URL(e,self.location.origin).host}catch{}return"undefined"!=typeof self&&self.location?.host?self.location.host:t})(n,r),endpoint:a,auth:t,p256dh:e}};return o&&(s.fcm_sdk_version=gt),i!==$e&&(s.web.applicationPubKey=i),s}let kt=6048e5;async function It(e){var t,a,i,n,r,o=await(async(e,t)=>{var a=await e.pushManager.getSubscription();return a||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Xe(t)})})(e.swRegistration,e.vapidKey),o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:o.endpoint,auth:b(o.getKey("auth")),p256dh:b(o.getKey("p256dh"))},s=await lt(e.firebaseDependencies);if(s){if(t=s.subscriptionOptions,a=o.vapidKey===t.vapidKey,i=o.endpoint===t.endpoint,n=o.auth===t.auth,r=o.p256dh===t.p256dh,a&&i&&n&&r)return Date.now()>=s.createTime+kt?(async(e,t)=>{try{var a=await(async(e,t)=>{var a=await D(e),i=yt(t.subscriptionOptions,e.appConfig.appName,!1),a={method:"PATCH",headers:a,body:JSON.stringify(i)};let n;try{var r=await fetch(T(e.appConfig)+"/"+t.token,a);n=await r.json()}catch(e){throw m.create("token-update-failed",{errorInfo:e?.toString()})}if(n.error)throw i=n.error.message,m.create("token-update-failed",{errorInfo:i});if(n.token)return n.token;throw m.create("token-update-no-token")})(e.firebaseDependencies,t),i={...t,token:a,createTime:Date.now()};return await pt(e.firebaseDependencies,i),a}catch(e){throw e}})(e,{token:s.token,createTime:Date.now(),subscriptionOptions:o}):s.token;try{await vt(e.firebaseDependencies,s.token)}catch(e){console.warn(e)}}return Dt(e.firebaseDependencies,o)}async function St(e,t){var a,i;await vt(e.firebaseDependencies,t.token),a=S(e.firebaseDependencies),await(i=(await I()).transaction(v,"readwrite")).objectStore(v).delete(a),await i.done,await Ct(e.firebaseDependencies)}async function Tt(e){var a=(await ut(e.firebaseDependencies).catch(()=>{}))?.fid;if(a){{var i=e.firebaseDependencies;var n=a;var r={method:"DELETE",headers:await D(i)};let t;try{t=await fetch(T(i.appConfig)+"/"+n,r)}catch(e){throw m.create("fid-unregister-failed",{errorInfo:e?.toString()})}if(!t.ok)try{throw(await t.json()).error?.message??t.statusText}catch(e){throw m.create("fid-unregister-failed",{errorInfo:"string"==typeof e&&e||t.statusText||e?.toString()})}}await 0}await Ct(e.firebaseDependencies),a&&(i=a,r=e.onUnregisteredHandler)&&("function"==typeof r?r(i):r.next(i))}async function Dt(e,t){var a={token:await(async(e,t)=>{var a=await D(e),i=yt(t,e.appConfig.appName,!1),a={method:"POST",headers:a,body:JSON.stringify(i)};let n;try{var r=await fetch(T(e.appConfig),a);n=await r.json()}catch(e){throw m.create("token-subscribe-failed",{errorInfo:e?.toString()})}if(n.error)throw i=n.error.message,m.create("token-subscribe-failed",{errorInfo:i});if(n.token)return n.token;throw m.create("token-subscribe-no-token")})(e,t),createTime:Date.now(),subscriptionOptions:t};return await pt(e,a),a.token}async function Ct(e){try{t=S(e),dt(a=await I()),await(a=a.transaction(y,"readwrite")).objectStore(y).delete(t),await a.done}catch{}var t,a}async function _t(e){try{e.swRegistration=await navigator.serviceWorker.register(Ve,{scope:We}),e.swRegistration.update().catch(()=>{}),n=e.swRegistration,await new Promise((t,e)=>{let a=setTimeout(()=>e(new Error(`Service worker not registered after ${Ye} ms`)),Ye),i=n.installing||n.waiting;n.active?(clearTimeout(a),t()):i?i.onstatechange=e=>{"activated"===e.target?.state&&(i.onstatechange=null,clearTimeout(a),t())}:(clearTimeout(a),e(new Error("No incoming service worker found.")))})}catch(e){throw m.create("failed-service-worker-registration",{browserErrorMessage:e?.message})}var n}async function Et(e,t){if(t||e.swRegistration||await _t(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw m.create("invalid-sw-registration");e.swRegistration=t}}async function Mt(e,t){t?e.vapidKey=t:e.vapidKey||(e.vapidKey=$e)}let jt=3;async function Pt(e,t){var a=await(async(e,t)=>{var a=await e.pushManager.getSubscription();return a||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Xe(t)})})(e.swRegistration,e.vapidKey),i={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:a.endpoint,auth:b(a.getKey("auth")),p256dh:b(a.getKey("p256dh"))},n=e.firebaseDependencies.installations;for(let o=0;o<jt;o++){var r=(await bt(e.firebaseDependencies,i)).responseFid;if(r===t)return;o<jt-1&&await n.getToken(!0)}throw m.create("fid-registration-failed",{errorInfo:"CreateRegistration response FID does not match Firebase Installation ID"})}let Kt=6048e5;async function Nt(r,e){if(!navigator)throw m.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw m.create("permission-blocked");if(!r.onRegisteredHandler)throw m.create("invalid-on-registered-handler");await Mt(r,e?.vapidKey),await Et(r,e?.serviceWorkerRegistration);var t=r._registerNotifyChain.catch(()=>{});return r._registerNotifyChain=t.then(async()=>{var e,t,a=await r.firebaseDependencies.installations.getId(),i=await ut(r.firebaseDependencies),n=Date.now(),i=((!i||i.fid!==a||n>=i.lastRegisterTime+Kt)&&(await Pt(r,a),t=r.firebaseDependencies,e={fid:a,lastRegisterTime:n,vapidKey:r.vapidKey},i=S(t),dt(n=await I()),await(n=n.transaction([v,y],"readwrite")).objectStore(y).put(e,i),await n.objectStore(v).delete(i),await n.done,await e),r.onRegisteredHandler);if(!i)throw m.create("invalid-on-registered-handler");t=a,(n=r.onRegisteredHandler)&&("function"==typeof n?n(t):n.next(t))}),r._registerNotifyChain}function Ot(e){var t,a,i,n={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return a=n,(t=e).notification&&(a.notification={},(i=t.notification.title)&&(a.notification.title=i),(i=t.notification.body)&&(a.notification.body=i),(i=t.notification.image)&&(a.notification.image=i),i=t.notification.icon)&&(a.notification.icon=i),t=n,(a=e).data&&(t.data=a.data),t=n,((a=e).fcmOptions||a.notification?.click_action)&&(t.fcmOptions={},(i=a.fcmOptions?.link??a.notification?.click_action)&&(t.fcmOptions.link=i),i=a.fcmOptions?.analytics_label)&&(t.fcmOptions.analyticsLabel=i),n}var Rt="AzSCbw63g1R0nCw85jG8",At="Iaya3yLKwmgvh7cF0q4",xt=[];for(let R=0;R<Rt.length;R++)xt.push(Rt.charAt(R)),R<At.length&&xt.push(At.charAt(R));function Ft(e){return m.create("missing-app-config-values",{valueName:e})}xt.join("");class Bt{constructor(e,t,a){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.onRegisteredHandler=null,this.onUnregisteredHandler=null,this._registerNotifyChain=Promise.resolve(),this._fidChangeUnsubscribe=null,this.logEvents=[],this.logQueue={state:"stopped"};var i=(e=>{if(!e||!e.options)throw Ft("App Configuration Object");if(!e.name)throw Ft("App Name");var t,a=e.options;for(t of["projectId","apiKey","appId","messagingSenderId"])if(!a[t])throw Ft(t);return{appName:e.name,projectId:a.projectId,apiKey:a.apiKey,appId:a.appId,senderId:a.messagingSenderId}})(e);this.firebaseDependencies={app:e,appConfig:i,installations:t,analyticsProvider:a}}_delete(){return this._fidChangeUnsubscribe&&(this._fidChangeUnsubscribe(),this._fidChangeUnsubscribe=null),"scheduled"===this.logQueue.state&&clearTimeout(this.logQueue.timerId),this.logQueue={state:"stopped"},Promise.resolve()}}async function Lt(e,t){if(!navigator)throw m.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw m.create("permission-blocked");return await Mt(e,t?.vapidKey),await Et(e,t?.serviceWorkerRegistration),It(e)}async function Ht(e,t,a){var i=(e=>{switch(e){case r.NOTIFICATION_CLICKED:return"notification_open";case r.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}})(t);(await e.firebaseDependencies.analyticsProvider.get()).logEvent(i,{message_id:a[Ge],message_name:a[Je],message_time:a[ze],message_device_time:Math.floor(Date.now()/1e3)})}async function Ut(e,t){var a,i=t.data;i.isFirebaseMessaging&&(e.onMessageHandler&&i.messageType===r.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(Ot(i)):e.onMessageHandler.next(Ot(i))),e.onRegisteredHandler&&i.messageType===r.FID_REGISTERED&&(a=i.fid,"function"==typeof e.onRegisteredHandler?e.onRegisteredHandler(a):e.onRegisteredHandler.next(a)),"object"==typeof(t=a=i.data))&&t&&Ge in t&&"1"===a[Ze]&&await Ht(e,i.messageType,a)}let qt=e=>{let t=new Bt(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));var a;return navigator.serviceWorker.addEventListener("message",e=>Ut(t,e)),t._fidChangeUnsubscribe=(a=t,Be(e.getProvider("installations").getImmediate(),()=>{(async()=>{a.onRegisteredHandler&&await ut(a.firebaseDependencies)&&await Nt(a).catch(()=>{})})()})),t},Vt=e=>{let t=e.getProvider("messaging").getImmediate();return{getToken:e=>Lt(t,e),register:e=>Nt(t,e)}};async function Wt(e){if(navigator)return e.swRegistration||await _t(e),(async e=>{var t=await lt(e.firebaseDependencies);return t?await St(e,t):await Tt(e),!(t=await e.swRegistration.pushManager.getSubscription())||t.unsubscribe()})(e);throw m.create("only-available-in-window")}function $t(e,t){var a=e=n(e),e=t;if(navigator)return a.onMessageHandler=e,()=>{a.onMessageHandler=null};throw m.create("only-available-in-window")}ei._registerComponent(new e("messaging",qt,"PUBLIC")),ei._registerComponent(new e("messaging-internal",Vt,"PRIVATE")),ei.registerVersion(ft,gt),ei.registerVersion(ft,gt,"esm2020");let Qt="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",Gt="https://fcmregistrations.googleapis.com/v1",Jt="FCM_MSG",zt="google.c.a.c_id",Zt=1e3,Yt=3,Xt=864e5,ea=5e3,ta=1249,aa=3,ia=1;function C(e){var t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function na(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),a=atob(t),i=new Uint8Array(a.length);for(let n=0;n<a.length;++n)i[n]=a.charCodeAt(n);return i}(s=o=o||{})[s.DATA_MESSAGE=1]="DATA_MESSAGE",s[s.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(s=d=d||{}).PUSH_RECEIVED="push-received",s.NOTIFICATION_CLICKED="notification-clicked",s.FID_REGISTERED="fid-registered";let ra="fcm_token_details_db",oa=5,sa="fcm_token_object_Store";async function ca(o){if("databases"in indexedDB&&!(await indexedDB.databases()).map(e=>e.name).includes(ra))return null;let s=null;return(await t(ra,oa,{upgrade:async(e,t,a,i)=>{var n,r;t<2||e.objectStoreNames.contains(sa)&&(n=await(r=i.objectStore(sa)).index("fcmSenderId").get(o),await r.clear(),n)&&(2===t?(r=n).auth&&r.p256dh&&r.endpoint&&(s={token:r.fcmToken,createTime:r.createTime??Date.now(),subscriptionOptions:{auth:r.auth,p256dh:r.p256dh,endpoint:r.endpoint,swScope:r.swScope,vapidKey:"string"==typeof r.vapidKey?r.vapidKey:C(r.vapidKey)}}):3===t?(r=n,s={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:C(r.auth),p256dh:C(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:C(r.vapidKey)}}):4===t&&(r=n,s={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:C(r.auth),p256dh:C(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:C(r.vapidKey)}}))}})).close(),await a(ra),await a("fcm_vapid_details_db"),await a("undefined"),(e=>{var t;if(e&&e.subscriptionOptions)return t=e.subscriptionOptions,"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length})(s)?s:null}let _=new i("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","fid-registration-failed":"A problem occurred while creating an FCM registration via FID: {$errorInfo}","fid-unregister-failed":"A problem occurred while unregistering the FCM registration via FID: {$errorInfo}","fid-registration-idb-schema-unavailable":"Unable to read or persist FID registration metadata because the messaging IndexedDB schema is unavailable (for example, the database could not be upgraded to the latest version).","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used.","invalid-on-registered-handler":"No onRegistered callback handler was provided or registered. Implement onRegistered() before register()."}),da="firebase-messaging-database",la=2,E="firebase-messaging-store",M="firebase-messaging-fid-registration-store",pa={openDB:t,deleteDB:a},j=null;function ua(n){return{upgrade:(e,t)=>{var a=e,i=n;switch(t){case 0:if(a.createObjectStore(E),1===i)break;case 1:2===i&&a.createObjectStore(M)}},blocked:()=>{},blocking:(e,t,a)=>{j=null,a.target?.close()},terminated:()=>{j=null}}}function P(){var e;return j||(e=pa.openDB(da,la,ua(2)),j=e.catch(()=>pa.openDB(da,la-1,ua(1)))),j}function fa(e,t){return e.objectStoreNames.contains(t)}function ga(e){if(!fa(e,M))throw _.create("fid-registration-idb-schema-unavailable")}async function ha(e){var t=K(e),t=await(await P()).transaction(E).objectStore(E).get(t);return t||((t=await ca(e.appConfig.senderId))?(await wa(e,t),t):void 0)}async function wa(e,t){var a=K(e),i=await P(),n=[E],r=fa(i,M),i=(r&&n.push(M),i.transaction(n,"readwrite"));return await i.objectStore(E).put(t,a),r&&await i.objectStore(M).delete(a),await i.done,t}async function ba(e){var t=K(e),a=await P();return ga(a),a.transaction(M).objectStore(M).get(t)}function K({appConfig:e}){return e.appId}let ma="0.13.0",va=3,ya=1e3;async function ka(e,t){var a=await O(e),i=Ta(t,e.appConfig.appName,!0);let n={method:"POST",headers:a,body:JSON.stringify(i)},r;try{r=await(async(e,t,a)=>{let i;for(let n=0;n<t;n++)try{return await e()}catch(e){if(i=e,n<t-1){let t=a*Math.pow(2,n);await new Promise(e=>setTimeout(e,t))}}throw i})(()=>fetch(N(e.appConfig),n),va,ya)}catch(e){throw _.create("fid-registration-failed",{errorInfo:e?.toString()})}if(r.ok)return{responseFid:await(async e=>{var t=await e.text();if(!t.trim())throw _.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is empty"});let a;try{a=JSON.parse(t)}catch{throw _.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is not valid JSON"})}if("string"!=typeof(t=a.name)||0===t.length)throw _.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response did not include a non-empty name"});if(-1!==(t=(e=t).indexOf(Ia))){t=e.slice(t+Ia.length);if(0<t.length)return t}throw _.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response name is not a valid registration resource name"})})(r)};let o;try{o=await r.json()}catch(e){throw _.create("fid-registration-failed",{errorInfo:r.statusText})}a=o.error?.message??r.statusText;throw _.create("fid-registration-failed",{errorInfo:a})}let Ia="/registrations/";async function Sa(e,t){var a={method:"DELETE",headers:await O(e)};try{var i,n=await(await fetch(N(e.appConfig)+"/"+t,a)).json();if(n.error)throw i=n.error.message,_.create("token-unsubscribe-failed",{errorInfo:i})}catch(e){throw _.create("token-unsubscribe-failed",{errorInfo:e?.toString()})}}function N({projectId:e}){return Gt+`/projects/${e}/registrations`}async function O({appConfig:e,installations:t}){var a=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":"FIS "+a})}function Ta({p256dh:e,auth:t,endpoint:a,vapidKey:i,swScope:n},r,o){var s={web:{origin:((e,t)=>{try{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e))return new URL(e).host}catch{}try{if("undefined"!=typeof self&&self.location?.href)return new URL(e,self.location.origin).host}catch{}return"undefined"!=typeof self&&self.location?.host?self.location.host:t})(n,r),endpoint:a,auth:t,p256dh:e}};return o&&(s.fcm_sdk_version=ma),i!==Qt&&(s.web.applicationPubKey=i),s}let Da=6048e5;async function Ca(e){var t,a,i,n,r,o=await(async(e,t)=>{var a=await e.pushManager.getSubscription();return a||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:na(t)})})(e.swRegistration,e.vapidKey),o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:o.endpoint,auth:C(o.getKey("auth")),p256dh:C(o.getKey("p256dh"))},s=await ha(e.firebaseDependencies);if(s){if(t=s.subscriptionOptions,a=o.vapidKey===t.vapidKey,i=o.endpoint===t.endpoint,n=o.auth===t.auth,r=o.p256dh===t.p256dh,a&&i&&n&&r)return Date.now()>=s.createTime+Da?(async(e,t)=>{try{var a=await(async(e,t)=>{var a=await O(e),i=Ta(t.subscriptionOptions,e.appConfig.appName,!1),a={method:"PATCH",headers:a,body:JSON.stringify(i)};let n;try{var r=await fetch(N(e.appConfig)+"/"+t.token,a);n=await r.json()}catch(e){throw _.create("token-update-failed",{errorInfo:e?.toString()})}if(n.error)throw i=n.error.message,_.create("token-update-failed",{errorInfo:i});if(n.token)return n.token;throw _.create("token-update-no-token")})(e.firebaseDependencies,t),i={...t,token:a,createTime:Date.now()};return await wa(e.firebaseDependencies,i),a}catch(e){throw e}})(e,{token:s.token,createTime:Date.now(),subscriptionOptions:o}):s.token;try{await Sa(e.firebaseDependencies,s.token)}catch(e){console.warn(e)}}return ja(e.firebaseDependencies,o)}async function _a(e,t){var a,i;await Sa(e.firebaseDependencies,t.token),a=K(e.firebaseDependencies),await(i=(await P()).transaction(E,"readwrite")).objectStore(E).delete(a),await i.done,await Pa(e.firebaseDependencies)}async function Ea(e){var a=(await ba(e.firebaseDependencies).catch(()=>{}))?.fid;if(a){{var i=e.firebaseDependencies;var n=a;var r={method:"DELETE",headers:await O(i)};let t;try{t=await fetch(N(i.appConfig)+"/"+n,r)}catch(e){throw _.create("fid-unregister-failed",{errorInfo:e?.toString()})}if(!t.ok)try{throw(await t.json()).error?.message??t.statusText}catch(e){throw _.create("fid-unregister-failed",{errorInfo:"string"==typeof e&&e||t.statusText||e?.toString()})}}await 0}await Pa(e.firebaseDependencies),a&&(i=a,r=e.onUnregisteredHandler)&&("function"==typeof r?r(i):r.next(i))}async function Ma(e){var t=await ha(e.firebaseDependencies),t=(t?await _a(e,t):await Ea(e),await e.swRegistration.pushManager.getSubscription());return!t||t.unsubscribe()}async function ja(e,t){var a={token:await(async(e,t)=>{var a=await O(e),i=Ta(t,e.appConfig.appName,!1),a={method:"POST",headers:a,body:JSON.stringify(i)};let n;try{var r=await fetch(N(e.appConfig),a);n=await r.json()}catch(e){throw _.create("token-subscribe-failed",{errorInfo:e?.toString()})}if(n.error)throw i=n.error.message,_.create("token-subscribe-failed",{errorInfo:i});if(n.token)return n.token;throw _.create("token-subscribe-no-token")})(e,t),createTime:Date.now(),subscriptionOptions:t};return await wa(e,a),a.token}async function Pa(e){try{t=K(e),ga(a=await P()),await(a=a.transaction(M,"readwrite")).objectStore(M).delete(t),await a.done}catch{}var t,a}let Ka=3;async function Na(e,t){var a=await(async(e,t)=>{var a=await e.pushManager.getSubscription();return a||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:na(t)})})(e.swRegistration,e.vapidKey),i={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:a.endpoint,auth:C(a.getKey("auth")),p256dh:C(a.getKey("p256dh"))},n=e.firebaseDependencies.installations;for(let o=0;o<Ka;o++){var r=(await ka(e.firebaseDependencies,i)).responseFid;if(r===t)return;o<Ka-1&&await n.getToken(!0)}throw _.create("fid-registration-failed",{errorInfo:"CreateRegistration response FID does not match Firebase Installation ID"})}async function Oa(e){var t,a,i,n,r=await ba(e.firebaseDependencies).catch(()=>{});if(r)return t=e,await!((i=r.vapidKey)?t.vapidKey=i:t.vapidKey||(t.vapidKey=Qt)),r=await e.firebaseDependencies.installations.getId(),await Na(e,r),i=e.firebaseDependencies,t={fid:r,lastRegisterTime:Date.now(),vapidKey:e.vapidKey},n=K(i),ga(a=await P()),await(a=a.transaction([E,M],"readwrite")).objectStore(M).put(t,n),await a.objectStore(E).delete(n),await a.done,await t,i=r,(n=e.onRegisteredHandler)&&("function"==typeof n?n(i):n.next(i)),r}let Ra="https://play.google.com/log?format=json_proto3",Aa=0,xa=((e,t)=>{var a=[];for(let i=0;i<e.length;i++)a.push(e.charAt(i)),i<t.length&&a.push(t.charAt(i));return a.join("")})("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");function Fa(o,e){"scheduled"===o.logQueue.state&&clearTimeout(o.logQueue.timerId),o.logQueue={state:"stopped"},o.deliveryMetricsExportedToBigQueryEnabled?o.logQueue={state:"scheduled",timerId:setTimeout(async()=>{if(o.logQueue={state:"flushing"},!o.logEvents.length)return Fa(o,Xt);var e=o,t=e.logEvents;e.logEvents=[];for(let r=0,a=t.length;r<a;r+=Zt){var i=t.slice(r,r+Zt);if(!i.length)break;var n=(e=>{var t={};return t.log_source=ta.toString(),t.log_event=e,t})(i);let a=0,e={};do{try{if((e=await fetch(Ra.concat("&key=",xa),{method:"POST",body:JSON.stringify(n)})).ok||!e.ok&&!Ba(e))break;if(!e.ok&&Ba(e))throw new Error("a retriable Non-200 code is returned in fetch to Firelog endpoint. Retry")}catch(e){if(a===Yt)break}let t;try{t=Number((await e.json()).nextRequestWaitMillis)}catch(e){t=ea}await new Promise(e=>setTimeout(e,t)),a++}while(a<Yt)}Fa(e,e.logEvents.length?Aa:Xt)},e)}:o.logEvents=[]}function Ba(e){var t=e.status;return 429===t||500===t||503===t||504===t}async function La(e,t){var a=((e,t)=>{var a={};return e.from&&(a.project_number=e.from),e.fcmMessageId&&(a.message_id=e.fcmMessageId),a.instance_id=t,a.message_type=(e.notification?o.DISPLAY_NOTIFICATION:o.DATA_MESSAGE).toString(),a.sdk_platform=aa.toString(),a.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(a.collapse_key=e.collapse_key),a.event=ia.toString(),e.fcmOptions?.analytics_label&&(a.analytics_label=e.fcmOptions?.analytics_label),a})(t,await e.firebaseDependencies.installations.getId()),i=e,n=a,t=t.productId,a={};a.event_time_ms=Math.floor(Date.now()).toString(),a.source_extension_json_proto3=JSON.stringify({messaging_client_event:n}),t&&(a.compliance_data=(e=>({privacy_context:{prequest:{origin_associated_product_id:e}}}))(t)),i.logEvents.push(a),"stopped"===(n=e).logQueue.state&&0<n.logEvents.length&&Fa(n,Aa)}async function Ha(e,t){t.swRegistration||(t.swRegistration=self.registration);var a=e.newSubscription;if(a)if(await ba(t.firebaseDependencies).catch(()=>{})){a=await Oa(t).catch(()=>{});if(a){var i=await Wa();if(Va(i)){var n,e=i,r=a,o={isFirebaseMessaging:!0,messageType:d.FID_REGISTERED,fid:r};for(n of e)n.postMessage(o)}}}else{i=await ha(t.firebaseDependencies);await Ma(t),t.vapidKey=i?.subscriptionOptions?.vapidKey??Qt,await Ca(t)}else await Ma(t)}async function Ua(e,t){var a=(({data:e})=>{if(!e)return null;try{return e.json()}catch(e){return null}})(e);if(a){t.deliveryMetricsExportedToBigQueryEnabled&&await La(t,a);var i,n,r,o=await Wa();if(Va(o)){var s,e=o,c=a;c.isFirebaseMessaging=!0,c.messageType=d.PUSH_RECEIVED;for(s of e)s.postMessage(c)}else a.notification&&await(e=>{var t=e.actions,a=Notification.maxActions;return t&&a&&t.length>a&&console.warn(`This browser only supports ${a} actions. The remaining actions will not be displayed.`),self.registration.showNotification(e.title??"",e)})(((o={...(e=a).notification}).data={[Jt]:e},o)),t&&t.onBackgroundMessageHandler&&(o={from:(e=a).from,collapseKey:e.collapse_key,messageId:e.fcmMessageId},n=o,(i=e).notification&&(n.notification={},(r=i.notification.title)&&(n.notification.title=r),(r=i.notification.body)&&(n.notification.body=r),(r=i.notification.image)&&(n.notification.image=r),r=i.notification.icon)&&(n.notification.icon=r),i=o,(n=e).data&&(i.data=n.data),i=o,((n=e).fcmOptions||n.notification?.click_action)&&(i.fcmOptions={},(r=n.fcmOptions?.link??n.notification?.click_action)&&(i.fcmOptions.link=r),r=n.fcmOptions?.analytics_label)&&(i.fcmOptions.analyticsLabel=r),a=o,"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(a):t.onBackgroundMessageHandler.next(a))}}async function qa(e){var t=e.notification?.data?.[Jt];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var a=(e=>{var t=e.fcmOptions?.link??e.notification?.click_action;return t||((e=>"object"==typeof e&&e&&zt in e)(e.data)?self.location.origin:null)})(t);if(a){var i,n=new URL(a,self.location.href),r=new URL(self.location.origin);if(n.host===r.host){let e=await(async e=>{var t;for(t of await Wa()){var a=new URL(t.url,self.location.href);if(e.host===a.host)return t}return null})(n);if(e?e=await e.focus():(e=await self.clients.openWindow(a),i=3e3,await new Promise(e=>{setTimeout(e,i)})),e)return t.messageType=d.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function Va(e){return e.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://"))}function Wa(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function $a(e){return _.create("missing-app-config-values",{valueName:e})}class Qa{constructor(e,t,a){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.onRegisteredHandler=null,this.onUnregisteredHandler=null,this._registerNotifyChain=Promise.resolve(),this._fidChangeUnsubscribe=null,this.logEvents=[],this.logQueue={state:"stopped"};var i=(e=>{if(!e||!e.options)throw $a("App Configuration Object");if(!e.name)throw $a("App Name");var t,a=e.options;for(t of["projectId","apiKey","appId","messagingSenderId"])if(!a[t])throw $a(t);return{appName:e.name,projectId:a.projectId,apiKey:a.apiKey,appId:a.appId,senderId:a.messagingSenderId}})(e);this.firebaseDependencies={app:e,appConfig:i,installations:t,analyticsProvider:a}}_delete(){return this._fidChangeUnsubscribe&&(this._fidChangeUnsubscribe(),this._fidChangeUnsubscribe=null),"scheduled"===this.logQueue.state&&clearTimeout(this.logQueue.timerId),this.logQueue={state:"stopped"},Promise.resolve()}}let Ga=e=>{let t=new Qa(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(Ua(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(Ha(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(qa(e))}),t};function Ja(e,t){var a=e=n(e),e=t;if(void 0!==self.document)throw _.create("only-available-in-sw");return a.onBackgroundMessageHandler=e,()=>{a.onBackgroundMessageHandler=null}}ei._registerComponent(new e("messaging-sw",Ga,"PUBLIC"));class za{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return(async(e,t)=>Lt(e=n(e),t))(this._delegate,e)}async deleteToken(){return Wt(n(this._delegate))}onMessage(e){return $t(this._delegate,e)}onBackgroundMessage(e){return Ja(this._delegate,e)}}let Za=e=>self&&"ServiceWorkerGlobalScope"in self?new za(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new za(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),Ya={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?B()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&B()&&!("undefined"==typeof navigator||!navigator.cookieEnabled)&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};F.default.INTERNAL.registerComponent(new e("messaging-compat",Za,"PUBLIC").setServiceProps(Ya)),F.default.registerVersion("@firebase/messaging-compat","0.2.27")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-messaging-compat.js - be sure to load firebase-app.js first.")}});
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(Xa,ei){try{!(function(){function A(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var x,F=A(Xa);function B(){try{return"object"==typeof indexedDB}catch(e){return!1}}class L extends Error{constructor(e,t,a){super(t),this.code=e,this.customData=a,this.name="FirebaseError",Object.setPrototypeOf(this,L.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,i.prototype.create)}}class i{constructor(e,t,a){this.service=e,this.serviceName=t,this.errors=a}create(e,...t){var i,a=t[0]||{},n=this.service+"/"+e,r=this.errors[e],r=r?(i=a,r.replace(H,(e,t)=>{var a=i[t];return null!=a?String(a):`<${t}?>`})):"Error",r=this.serviceName+`: ${r} (${n}).`;return new L(n,r,a)}}let H=/\{\$([^}]+)}/g;function n(e){return e&&e._delegate?e._delegate:e}class e{constructor(e,t,a){this.name=e,this.instanceFactory=t,this.type=a,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let U=(t,e)=>e.some(e=>t instanceof e),q,V;let W=new WeakMap,$=new WeakMap,Q=new WeakMap,G=new WeakMap,J=new WeakMap;let z={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return $.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Q.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return c(e[t])},set(e,t,a){return e[t]=a,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function Z(i){return i!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(V=V||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(i)?function(...e){return i.apply(X(this),e),c(W.get(this))}:function(...e){return c(i.apply(X(this),e))}:function(e,...t){var a=i.call(X(this),e,...t);return Q.set(a,e.sort?e.sort():[e]),c(a)}}function Y(e){var r,t;return"function"==typeof e?Z(e):(e instanceof IDBTransaction&&(r=e,$.has(r)||(t=new Promise((e,t)=>{let a=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",n),r.removeEventListener("abort",n)},i=()=>{e(),a()},n=()=>{t(r.error||new DOMException("AbortError","AbortError")),a()};r.addEventListener("complete",i),r.addEventListener("error",n),r.addEventListener("abort",n)}),$.set(r,t))),U(e,q=q||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,z):e)}function c(e){var r,t;return e instanceof IDBRequest?(r=e,(t=new Promise((e,t)=>{let a=()=>{r.removeEventListener("success",i),r.removeEventListener("error",n)},i=()=>{e(c(r.result)),a()},n=()=>{t(r.error),a()};r.addEventListener("success",i),r.addEventListener("error",n)})).then(e=>{e instanceof IDBCursor&&W.set(e,r)}).catch(()=>{}),J.set(t,r),t):G.has(e)?G.get(e):((t=Y(e))!==e&&(G.set(e,t),J.set(t,e)),t)}let X=e=>J.get(e);function t(e,t,{blocked:a,upgrade:i,blocking:n,terminated:r}={}){let o=indexedDB.open(e,t);var s=c(o);return i&&o.addEventListener("upgradeneeded",e=>{i(c(o.result),e.oldVersion,e.newVersion,c(o.transaction),e)}),a&&o.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),s.then(e=>{r&&e.addEventListener("close",()=>r()),n&&e.addEventListener("versionchange",e=>n(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}function a(e,{blocked:t}={}){var a=indexedDB.deleteDatabase(e);return t&&a.addEventListener("blocked",e=>t(e.oldVersion,e)),c(a).then(()=>{})}let ee=["get","getKey","getAll","getAllKeys","count"],te=["put","add","delete","clear"],ae=new Map;function ie(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(ae.get(t))return ae.get(t);let n=t.replace(/FromIndex$/,""),r=t!==n,o=te.includes(n);var a;return n in(r?IDBIndex:IDBObjectStore).prototype&&(o||ee.includes(n))?(a=async function(e,...t){var a=this.transaction(e,o?"readwrite":"readonly");let i=a.store;return r&&(i=i.index(t.shift())),(await Promise.all([i[n](...t),o&&a.done]))[0]},ae.set(t,a),a):void 0}}z={...x=z,get:(e,t,a)=>ie(e,t)||x.get(e,t,a),has:(e,t)=>!!ie(e,t)||x.has(e,t)};var ne="@firebase/installations",re="0.6.22";let oe=1e4,se="w:"+re,ce="FIS_v2",de="https://firebaseinstallations.googleapis.com/v1",le=36e5;var r,o,d,s;let l=new i("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function pe(e){return e instanceof L&&e.code.includes("request-failed")}function ue({projectId:e}){return de+`/projects/${e}/installations`}function fe(e){return{token:e.token,requestStatus:2,expiresIn:Number(e.expiresIn.replace("s","000")),creationTime:Date.now()}}async function ge(e,t){var a=(await t.json()).error;return l.create("request-failed",{requestName:e,serverCode:a.code,serverMessage:a.message,serverStatus:a.status})}function he({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function we(e,{refreshToken:t}){var a=he(e);return a.append("Authorization",(e=t,ce+" "+e)),a}async function be(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function me(t){return new Promise(e=>{setTimeout(e,t)})}let ve=/^[cdef][\w-]{21}$/,ye="";function ke(){try{var e=new Uint8Array(17),t=((self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16,(e=>btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_"))(e).substr(0,22));return ve.test(t)?t:ye}catch{return ye}}function p(e){return e.appName+"!"+e.appId}let u=new Map;function Ie(e,t){var a=p(e),e=(Se(a,t),a),a=Te();a&&a.postMessage({key:e,fid:t}),De()}function Se(e,t){var a=u.get(e);if(a)for(var i of a)i(t)}let f=null;function Te(){return!f&&"BroadcastChannel"in self&&((f=new BroadcastChannel("[Firebase] FID Change")).onmessage=e=>{Se(e.data.key,e.data.fid)}),f}function De(){0===u.size&&f&&(f.close(),f=null)}let Ce="firebase-installations-database",_e=1,g="firebase-installations-store",Ee=null;function Me(){return Ee=Ee||t(Ce,_e,{upgrade:(e,t)=>{0===t&&e.createObjectStore(g)}})}async function h(e,t){var a=p(e),i=(await Me()).transaction(g,"readwrite"),n=i.objectStore(g),r=await n.get(a);return await n.put(t,a),await i.done,r&&r.fid===t.fid||Ie(e,t.fid),t}async function je(e){var t=p(e),a=(await Me()).transaction(g,"readwrite");await a.objectStore(g).delete(t),await a.done}async function w(e,t){var a=p(e),i=(await Me()).transaction(g,"readwrite"),n=i.objectStore(g),r=await n.get(a),o=t(r);return void 0===o?await n.delete(a):await n.put(o,a),await i.done,!o||r&&r.fid===o.fid||Ie(e,o.fid),o}async function Pe(a){let i;var e=await w(a.appConfig,e=>{var t=Ne(e||{fid:ke(),registrationStatus:0}),t=((e,t)=>{var a,i;return 0===t.registrationStatus?navigator.onLine?(a={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},i=(async(t,a)=>{try{var e=await(async({appConfig:e,heartbeatServiceProvider:t},{fid:a})=>{let i=ue(e);var n=he(e),r=((r=t.getImmediate({optional:!0}))&&(r=await r.getHeartbeatsHeader())&&n.append("x-firebase-client",r),{fid:a,authVersion:ce,appId:e.appId,sdkVersion:se});let o={method:"POST",headers:n,body:JSON.stringify(r)};if((n=await be(()=>fetch(i,o))).ok)return{fid:(r=await n.json()).fid||a,registrationStatus:2,refreshToken:r.refreshToken,authToken:fe(r.authToken)};throw await ge("Create Installation",n)})(t,a);return h(t.appConfig,e)}catch(e){throw pe(e)&&409===e.customData.serverCode?await je(t.appConfig):await h(t.appConfig,{fid:a.fid,registrationStatus:0}),e}})(e,a),{installationEntry:a,registrationPromise:i}):(a=Promise.reject(l.create("app-offline")),{installationEntry:t,registrationPromise:a}):1===t.registrationStatus?{installationEntry:t,registrationPromise:(async e=>{let t=await Ke(e.appConfig);for(;1===t.registrationStatus;)await me(100),t=await Ke(e.appConfig);var a,i;return 0!==t.registrationStatus?t:({installationEntry:a,registrationPromise:i}=await Pe(e),i||a)})(e)}:{installationEntry:t}})(a,t);return i=t.registrationPromise,t.installationEntry});return e.fid===ye?{installationEntry:await i}:{installationEntry:e,registrationPromise:i}}function Ke(e){return w(e,e=>{if(e)return Ne(e);throw l.create("installation-not-found")})}function Ne(e){var t;return 1===(t=e).registrationStatus&&t.registrationTime+oe<Date.now()?{fid:e.fid,registrationStatus:0}:e}async function Oe({appConfig:e,heartbeatServiceProvider:t},a){[n,r]=[e,a.fid];let i=ue(n)+`/${r}/authTokens:generate`;var n,r,o=we(e,a),s=t.getImmediate({optional:!0}),s=(s&&(s=await s.getHeartbeatsHeader())&&o.append("x-firebase-client",s),{installation:{sdkVersion:se,appId:e.appId}});let c={method:"POST",headers:o,body:JSON.stringify(s)};o=await be(()=>fetch(i,c));if(o.ok)return fe(await o.json());throw await ge("Generate Auth Token",o)}async function Re(i,n=!1){let r;var e=await w(i.appConfig,e=>{if(!xe(e))throw l.create("not-registered");var t,a=e.authToken;if(n||2!==(t=a).requestStatus||(e=>{var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+le})(t)){if(1===a.requestStatus)return r=(async(e,t)=>{let a=await Ae(e.appConfig);for(;1===a.authToken.requestStatus;)await me(100),a=await Ae(e.appConfig);var i=a.authToken;return 0===i.requestStatus?Re(e,t):i})(i,n),e;if(navigator.onLine)return t=e,a={requestStatus:1,requestTime:Date.now()},a={...t,authToken:a},r=(async(t,a)=>{try{var e=await Oe(t,a),i={...a,authToken:e};return await h(t.appConfig,i),e}catch(e){var n;throw!pe(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(n={...a,authToken:{requestStatus:0}},await h(t.appConfig,n)):await je(t.appConfig),e}})(i,a),a;throw l.create("app-offline")}return e});return r?await r:e.authToken}function Ae(e){return w(e,e=>{var t,a;if(xe(e))return t=e.authToken,1===(a=t).requestStatus&&a.requestTime+oe<Date.now()?{...e,authToken:{requestStatus:0}}:e;throw l.create("not-registered")})}function xe(e){return void 0!==e&&2===e.registrationStatus}async function Fe(e,t=!1){var a=e,i=(await(!(i=(await Pe(a)).registrationPromise)||!await i),await Re(a,t));return i.token}function Be(t,n){let r=t.appConfig;{t=r;var a=n,i=(Te(),p(t));let e=u.get(i);e||(e=new Set,u.set(i,e)),e.add(a)}return()=>{var e,t,a,i;e=r,t=n,a=p(e),(i=u.get(a))&&(i.delete(t),0===i.size&&u.delete(a),De())}}function Le(e){return l.create("missing-app-config-values",{valueName:e})}let He="installations",Ue=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:(e=>{if(!e||!e.options)throw Le("App Configuration");if(!e.name)throw Le("App Name");var t;for(t of["projectId","apiKey","appId"])if(!e.options[t])throw Le(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}})(t),heartbeatServiceProvider:ei._getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},qe=e=>{var t=e.getProvider("app").getImmediate();let a=ei._getProvider(t,He).getImmediate();return{getId:()=>(async e=>{var t=e,{installationEntry:a,registrationPromise:i}=await Pe(t);return(i||Re(t)).catch(console.error),a.fid})(a),getToken:e=>Fe(a,e)}};ei._registerComponent(new e(He,Ue,"PUBLIC")),ei._registerComponent(new e("installations-internal",qe,"PRIVATE")),ei.registerVersion(ne,re),ei.registerVersion(ne,re,"esm2020");let Ve="/firebase-messaging-sw.js",We="/firebase-cloud-messaging-push-scope",$e="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",Qe="https://fcmregistrations.googleapis.com/v1",Ge="google.c.a.c_id",Je="google.c.a.c_l",ze="google.c.a.ts",Ze="google.c.a.e",Ye=1e4;function b(e){var t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Xe(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),a=atob(t),i=new Uint8Array(a.length);for(let n=0;n<a.length;++n)i[n]=a.charCodeAt(n);return i}(s=r=r||{}).PUSH_RECEIVED="push-received",s.NOTIFICATION_CLICKED="notification-clicked",s.FID_REGISTERED="fid-registered";let et="fcm_token_details_db",tt=5,at="fcm_token_object_Store";async function it(o){if("databases"in indexedDB&&!(await indexedDB.databases()).map(e=>e.name).includes(et))return null;let s=null;return(await t(et,tt,{upgrade:async(e,t,a,i)=>{var n,r;t<2||e.objectStoreNames.contains(at)&&(n=await(r=i.objectStore(at)).index("fcmSenderId").get(o),await r.clear(),n)&&(2===t?(r=n).auth&&r.p256dh&&r.endpoint&&(s={token:r.fcmToken,createTime:r.createTime??Date.now(),subscriptionOptions:{auth:r.auth,p256dh:r.p256dh,endpoint:r.endpoint,swScope:r.swScope,vapidKey:"string"==typeof r.vapidKey?r.vapidKey:b(r.vapidKey)}}):3===t?(r=n,s={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:b(r.auth),p256dh:b(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:b(r.vapidKey)}}):4===t&&(r=n,s={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:b(r.auth),p256dh:b(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:b(r.vapidKey)}}))}})).close(),await a(et),await a("fcm_vapid_details_db"),await a("undefined"),(e=>{var t;if(e&&e.subscriptionOptions)return t=e.subscriptionOptions,"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length})(s)?s:null}let m=new i("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","fid-registration-failed":"A problem occurred while creating an FCM registration via FID: {$errorInfo}","fid-unregister-failed":"A problem occurred while unregistering the FCM registration via FID: {$errorInfo}","fid-registration-idb-schema-unavailable":"Unable to read or persist FID registration metadata because the messaging IndexedDB schema is unavailable (for example, the database could not be upgraded to the latest version).","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used.","invalid-on-registered-handler":"No onRegistered callback handler was provided or registered. Implement onRegistered() before register()."}),nt="firebase-messaging-database",rt=2,v="firebase-messaging-store",y="firebase-messaging-fid-registration-store",ot={openDB:t,deleteDB:a},k=null;function st(n){return{upgrade:(e,t)=>{var a=e,i=n;switch(t){case 0:if(a.createObjectStore(v),1===i)break;case 1:2===i&&a.createObjectStore(y)}},blocked:()=>{},blocking:(e,t,a)=>{k=null,a.target?.close()},terminated:()=>{k=null}}}function I(){var e;return k||(e=ot.openDB(nt,rt,st(2)),k=e.catch(()=>ot.openDB(nt,rt-1,st(1)))),k}function ct(e,t){return e.objectStoreNames.contains(t)}function dt(e){if(!ct(e,y))throw m.create("fid-registration-idb-schema-unavailable")}async function lt(e){var t=S(e),t=await(await I()).transaction(v).objectStore(v).get(t);return t||((t=await it(e.appConfig.senderId))?(await pt(e,t),t):void 0)}async function pt(e,t){var a=S(e),i=await I(),n=[v],r=ct(i,y),i=(r&&n.push(y),i.transaction(n,"readwrite"));return await i.objectStore(v).put(t,a),r&&await i.objectStore(y).delete(a),await i.done,t}async function ut(e){var t=S(e),a=await I();return dt(a),a.transaction(y).objectStore(y).get(t)}function S({appConfig:e}){return e.appId}let ft="@firebase/messaging",gt="0.13.0",ht=3,wt=1e3;async function bt(e,t){var a=await D(e),i=yt(t,e.appConfig.appName,!0);let n={method:"POST",headers:a,body:JSON.stringify(i)},r;try{r=await(async(e,t,a)=>{let i;for(let n=0;n<t;n++)try{return await e()}catch(e){if(i=e,n<t-1){let t=a*Math.pow(2,n);await new Promise(e=>setTimeout(e,t))}}throw i})(()=>fetch(T(e.appConfig),n),ht,wt)}catch(e){throw m.create("fid-registration-failed",{errorInfo:e?.toString()})}if(r.ok)return{responseFid:await(async e=>{var t=await e.text();if(!t.trim())throw m.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is empty"});let a;try{a=JSON.parse(t)}catch{throw m.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is not valid JSON"})}if("string"!=typeof(t=a.name)||0===t.length)throw m.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response did not include a non-empty name"});if(-1!==(t=(e=t).indexOf(mt))){t=e.slice(t+mt.length);if(0<t.length)return t}throw m.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response name is not a valid registration resource name"})})(r)};let o;try{o=await r.json()}catch(e){throw m.create("fid-registration-failed",{errorInfo:r.statusText})}a=o.error?.message??r.statusText;throw m.create("fid-registration-failed",{errorInfo:a})}let mt="/registrations/";async function vt(e,t){var a={method:"DELETE",headers:await D(e)};try{var i,n=await(await fetch(T(e.appConfig)+"/"+t,a)).json();if(n.error)throw i=n.error.message,m.create("token-unsubscribe-failed",{errorInfo:i})}catch(e){throw m.create("token-unsubscribe-failed",{errorInfo:e?.toString()})}}function T({projectId:e}){return Qe+`/projects/${e}/registrations`}async function D({appConfig:e,installations:t}){var a=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":"FIS "+a})}function yt({p256dh:e,auth:t,endpoint:a,vapidKey:i,swScope:n},r,o){var s={web:{origin:((e,t)=>{try{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e))return new URL(e).host}catch{}try{if("undefined"!=typeof self&&self.location?.href)return new URL(e,self.location.origin).host}catch{}return"undefined"!=typeof self&&self.location?.host?self.location.host:t})(n,r),endpoint:a,auth:t,p256dh:e}};return o&&(s.fcm_sdk_version=gt),i!==$e&&(s.web.applicationPubKey=i),s}let kt=6048e5;async function It(e){var t,a,i,n,r,o=await(async(e,t)=>{var a=await e.pushManager.getSubscription();return a||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Xe(t)})})(e.swRegistration,e.vapidKey),o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:o.endpoint,auth:b(o.getKey("auth")),p256dh:b(o.getKey("p256dh"))},s=await lt(e.firebaseDependencies);if(s){if(t=s.subscriptionOptions,a=o.vapidKey===t.vapidKey,i=o.endpoint===t.endpoint,n=o.auth===t.auth,r=o.p256dh===t.p256dh,a&&i&&n&&r)return Date.now()>=s.createTime+kt?(async(e,t)=>{try{var a=await(async(e,t)=>{var a=await D(e),i=yt(t.subscriptionOptions,e.appConfig.appName,!1),a={method:"PATCH",headers:a,body:JSON.stringify(i)};let n;try{var r=await fetch(T(e.appConfig)+"/"+t.token,a);n=await r.json()}catch(e){throw m.create("token-update-failed",{errorInfo:e?.toString()})}if(n.error)throw i=n.error.message,m.create("token-update-failed",{errorInfo:i});if(n.token)return n.token;throw m.create("token-update-no-token")})(e.firebaseDependencies,t),i={...t,token:a,createTime:Date.now()};return await pt(e.firebaseDependencies,i),a}catch(e){throw e}})(e,{token:s.token,createTime:Date.now(),subscriptionOptions:o}):s.token;try{await vt(e.firebaseDependencies,s.token)}catch(e){console.warn(e)}}return Dt(e.firebaseDependencies,o)}async function St(e,t){var a,i;await vt(e.firebaseDependencies,t.token),a=S(e.firebaseDependencies),await(i=(await I()).transaction(v,"readwrite")).objectStore(v).delete(a),await i.done,await Ct(e.firebaseDependencies)}async function Tt(e){var a=(await ut(e.firebaseDependencies).catch(()=>{}))?.fid;if(a){{var i=e.firebaseDependencies;var n=a;var r={method:"DELETE",headers:await D(i)};let t;try{t=await fetch(T(i.appConfig)+"/"+n,r)}catch(e){throw m.create("fid-unregister-failed",{errorInfo:e?.toString()})}if(!t.ok)try{throw(await t.json()).error?.message??t.statusText}catch(e){throw m.create("fid-unregister-failed",{errorInfo:"string"==typeof e&&e||t.statusText||e?.toString()})}}await 0}await Ct(e.firebaseDependencies),a&&(i=a,r=e.onUnregisteredHandler)&&("function"==typeof r?r(i):r.next(i))}async function Dt(e,t){var a={token:await(async(e,t)=>{var a=await D(e),i=yt(t,e.appConfig.appName,!1),a={method:"POST",headers:a,body:JSON.stringify(i)};let n;try{var r=await fetch(T(e.appConfig),a);n=await r.json()}catch(e){throw m.create("token-subscribe-failed",{errorInfo:e?.toString()})}if(n.error)throw i=n.error.message,m.create("token-subscribe-failed",{errorInfo:i});if(n.token)return n.token;throw m.create("token-subscribe-no-token")})(e,t),createTime:Date.now(),subscriptionOptions:t};return await pt(e,a),a.token}async function Ct(e){try{t=S(e),dt(a=await I()),await(a=a.transaction(y,"readwrite")).objectStore(y).delete(t),await a.done}catch{}var t,a}async function _t(e){try{e.swRegistration=await navigator.serviceWorker.register(Ve,{scope:We}),e.swRegistration.update().catch(()=>{}),n=e.swRegistration,await new Promise((t,e)=>{let a=setTimeout(()=>e(new Error(`Service worker not registered after ${Ye} ms`)),Ye),i=n.installing||n.waiting;n.active?(clearTimeout(a),t()):i?i.onstatechange=e=>{"activated"===e.target?.state&&(i.onstatechange=null,clearTimeout(a),t())}:(clearTimeout(a),e(new Error("No incoming service worker found.")))})}catch(e){throw m.create("failed-service-worker-registration",{browserErrorMessage:e?.message})}var n}async function Et(e,t){if(t||e.swRegistration||await _t(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw m.create("invalid-sw-registration");e.swRegistration=t}}async function Mt(e,t){t?e.vapidKey=t:e.vapidKey||(e.vapidKey=$e)}let jt=3;async function Pt(e,t){var a=await(async(e,t)=>{var a=await e.pushManager.getSubscription();return a||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Xe(t)})})(e.swRegistration,e.vapidKey),i={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:a.endpoint,auth:b(a.getKey("auth")),p256dh:b(a.getKey("p256dh"))},n=e.firebaseDependencies.installations;for(let o=0;o<jt;o++){var r=(await bt(e.firebaseDependencies,i)).responseFid;if(r===t)return;o<jt-1&&await n.getToken(!0)}throw m.create("fid-registration-failed",{errorInfo:"CreateRegistration response FID does not match Firebase Installation ID"})}let Kt=6048e5;async function Nt(r,e){if(!navigator)throw m.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw m.create("permission-blocked");if(!r.onRegisteredHandler)throw m.create("invalid-on-registered-handler");await Mt(r,e?.vapidKey),await Et(r,e?.serviceWorkerRegistration);var t=r._registerNotifyChain.catch(()=>{});return r._registerNotifyChain=t.then(async()=>{var e,t,a=await r.firebaseDependencies.installations.getId(),i=await ut(r.firebaseDependencies),n=Date.now(),i=((!i||i.fid!==a||n>=i.lastRegisterTime+Kt)&&(await Pt(r,a),t=r.firebaseDependencies,e={fid:a,lastRegisterTime:n,vapidKey:r.vapidKey},i=S(t),dt(n=await I()),await(n=n.transaction([v,y],"readwrite")).objectStore(y).put(e,i),await n.objectStore(v).delete(i),await n.done,await e),r.onRegisteredHandler);if(!i)throw m.create("invalid-on-registered-handler");t=a,(n=r.onRegisteredHandler)&&("function"==typeof n?n(t):n.next(t))}),r._registerNotifyChain}function Ot(e){var t,a,i,n={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return a=n,(t=e).notification&&(a.notification={},(i=t.notification.title)&&(a.notification.title=i),(i=t.notification.body)&&(a.notification.body=i),(i=t.notification.image)&&(a.notification.image=i),i=t.notification.icon)&&(a.notification.icon=i),t=n,(a=e).data&&(t.data=a.data),t=n,((a=e).fcmOptions||a.notification?.click_action)&&(t.fcmOptions={},(i=a.fcmOptions?.link??a.notification?.click_action)&&(t.fcmOptions.link=i),i=a.fcmOptions?.analytics_label)&&(t.fcmOptions.analyticsLabel=i),n}var Rt="AzSCbw63g1R0nCw85jG8",At="Iaya3yLKwmgvh7cF0q4",xt=[];for(let R=0;R<Rt.length;R++)xt.push(Rt.charAt(R)),R<At.length&&xt.push(At.charAt(R));function Ft(e){return m.create("missing-app-config-values",{valueName:e})}xt.join("");class Bt{constructor(e,t,a){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.onRegisteredHandler=null,this.onUnregisteredHandler=null,this._registerNotifyChain=Promise.resolve(),this._fidChangeUnsubscribe=null,this.logEvents=[],this.logQueue={state:"stopped"};var i=(e=>{if(!e||!e.options)throw Ft("App Configuration Object");if(!e.name)throw Ft("App Name");var t,a=e.options;for(t of["projectId","apiKey","appId","messagingSenderId"])if(!a[t])throw Ft(t);return{appName:e.name,projectId:a.projectId,apiKey:a.apiKey,appId:a.appId,senderId:a.messagingSenderId}})(e);this.firebaseDependencies={app:e,appConfig:i,installations:t,analyticsProvider:a}}_delete(){return this._fidChangeUnsubscribe&&(this._fidChangeUnsubscribe(),this._fidChangeUnsubscribe=null),"scheduled"===this.logQueue.state&&clearTimeout(this.logQueue.timerId),this.logQueue={state:"stopped"},Promise.resolve()}}async function Lt(e,t){if(!navigator)throw m.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw m.create("permission-blocked");return await Mt(e,t?.vapidKey),await Et(e,t?.serviceWorkerRegistration),It(e)}async function Ht(e,t,a){var i=(e=>{switch(e){case r.NOTIFICATION_CLICKED:return"notification_open";case r.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}})(t);(await e.firebaseDependencies.analyticsProvider.get()).logEvent(i,{message_id:a[Ge],message_name:a[Je],message_time:a[ze],message_device_time:Math.floor(Date.now()/1e3)})}async function Ut(e,t){var a,i=t.data;i.isFirebaseMessaging&&(e.onMessageHandler&&i.messageType===r.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(Ot(i)):e.onMessageHandler.next(Ot(i))),e.onRegisteredHandler&&i.messageType===r.FID_REGISTERED&&(a=i.fid,"function"==typeof e.onRegisteredHandler?e.onRegisteredHandler(a):e.onRegisteredHandler.next(a)),"object"==typeof(t=a=i.data))&&t&&Ge in t&&"1"===a[Ze]&&await Ht(e,i.messageType,a)}let qt=e=>{let t=new Bt(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));var a;return navigator.serviceWorker.addEventListener("message",e=>Ut(t,e)),t._fidChangeUnsubscribe=(a=t,Be(e.getProvider("installations").getImmediate(),()=>{(async()=>{a.onRegisteredHandler&&await ut(a.firebaseDependencies)&&await Nt(a).catch(()=>{})})()})),t},Vt=e=>{let t=e.getProvider("messaging").getImmediate();return{getToken:e=>Lt(t,e),register:e=>Nt(t,e)}};async function Wt(e){if(navigator)return e.swRegistration||await _t(e),(async e=>{var t=await lt(e.firebaseDependencies);return t?await St(e,t):await Tt(e),!(t=await e.swRegistration.pushManager.getSubscription())||t.unsubscribe()})(e);throw m.create("only-available-in-window")}function $t(e,t){var a=e=n(e),e=t;if(navigator)return a.onMessageHandler=e,()=>{a.onMessageHandler=null};throw m.create("only-available-in-window")}ei._registerComponent(new e("messaging",qt,"PUBLIC")),ei._registerComponent(new e("messaging-internal",Vt,"PRIVATE")),ei.registerVersion(ft,gt),ei.registerVersion(ft,gt,"esm2020");let Qt="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",Gt="https://fcmregistrations.googleapis.com/v1",Jt="FCM_MSG",zt="google.c.a.c_id",Zt=1e3,Yt=3,Xt=864e5,ea=5e3,ta=1249,aa=3,ia=1;function C(e){var t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function na(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),a=atob(t),i=new Uint8Array(a.length);for(let n=0;n<a.length;++n)i[n]=a.charCodeAt(n);return i}(s=o=o||{})[s.DATA_MESSAGE=1]="DATA_MESSAGE",s[s.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(s=d=d||{}).PUSH_RECEIVED="push-received",s.NOTIFICATION_CLICKED="notification-clicked",s.FID_REGISTERED="fid-registered";let ra="fcm_token_details_db",oa=5,sa="fcm_token_object_Store";async function ca(o){if("databases"in indexedDB&&!(await indexedDB.databases()).map(e=>e.name).includes(ra))return null;let s=null;return(await t(ra,oa,{upgrade:async(e,t,a,i)=>{var n,r;t<2||e.objectStoreNames.contains(sa)&&(n=await(r=i.objectStore(sa)).index("fcmSenderId").get(o),await r.clear(),n)&&(2===t?(r=n).auth&&r.p256dh&&r.endpoint&&(s={token:r.fcmToken,createTime:r.createTime??Date.now(),subscriptionOptions:{auth:r.auth,p256dh:r.p256dh,endpoint:r.endpoint,swScope:r.swScope,vapidKey:"string"==typeof r.vapidKey?r.vapidKey:C(r.vapidKey)}}):3===t?(r=n,s={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:C(r.auth),p256dh:C(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:C(r.vapidKey)}}):4===t&&(r=n,s={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:C(r.auth),p256dh:C(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:C(r.vapidKey)}}))}})).close(),await a(ra),await a("fcm_vapid_details_db"),await a("undefined"),(e=>{var t;if(e&&e.subscriptionOptions)return t=e.subscriptionOptions,"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length})(s)?s:null}let _=new i("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","fid-registration-failed":"A problem occurred while creating an FCM registration via FID: {$errorInfo}","fid-unregister-failed":"A problem occurred while unregistering the FCM registration via FID: {$errorInfo}","fid-registration-idb-schema-unavailable":"Unable to read or persist FID registration metadata because the messaging IndexedDB schema is unavailable (for example, the database could not be upgraded to the latest version).","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used.","invalid-on-registered-handler":"No onRegistered callback handler was provided or registered. Implement onRegistered() before register()."}),da="firebase-messaging-database",la=2,E="firebase-messaging-store",M="firebase-messaging-fid-registration-store",pa={openDB:t,deleteDB:a},j=null;function ua(n){return{upgrade:(e,t)=>{var a=e,i=n;switch(t){case 0:if(a.createObjectStore(E),1===i)break;case 1:2===i&&a.createObjectStore(M)}},blocked:()=>{},blocking:(e,t,a)=>{j=null,a.target?.close()},terminated:()=>{j=null}}}function P(){var e;return j||(e=pa.openDB(da,la,ua(2)),j=e.catch(()=>pa.openDB(da,la-1,ua(1)))),j}function fa(e,t){return e.objectStoreNames.contains(t)}function ga(e){if(!fa(e,M))throw _.create("fid-registration-idb-schema-unavailable")}async function ha(e){var t=K(e),t=await(await P()).transaction(E).objectStore(E).get(t);return t||((t=await ca(e.appConfig.senderId))?(await wa(e,t),t):void 0)}async function wa(e,t){var a=K(e),i=await P(),n=[E],r=fa(i,M),i=(r&&n.push(M),i.transaction(n,"readwrite"));return await i.objectStore(E).put(t,a),r&&await i.objectStore(M).delete(a),await i.done,t}async function ba(e){var t=K(e),a=await P();return ga(a),a.transaction(M).objectStore(M).get(t)}function K({appConfig:e}){return e.appId}let ma="0.13.0",va=3,ya=1e3;async function ka(e,t){var a=await O(e),i=Ta(t,e.appConfig.appName,!0);let n={method:"POST",headers:a,body:JSON.stringify(i)},r;try{r=await(async(e,t,a)=>{let i;for(let n=0;n<t;n++)try{return await e()}catch(e){if(i=e,n<t-1){let t=a*Math.pow(2,n);await new Promise(e=>setTimeout(e,t))}}throw i})(()=>fetch(N(e.appConfig),n),va,ya)}catch(e){throw _.create("fid-registration-failed",{errorInfo:e?.toString()})}if(r.ok)return{responseFid:await(async e=>{var t=await e.text();if(!t.trim())throw _.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is empty"});let a;try{a=JSON.parse(t)}catch{throw _.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is not valid JSON"})}if("string"!=typeof(t=a.name)||0===t.length)throw _.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response did not include a non-empty name"});if(-1!==(t=(e=t).indexOf(Ia))){t=e.slice(t+Ia.length);if(0<t.length)return t}throw _.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response name is not a valid registration resource name"})})(r)};let o;try{o=await r.json()}catch(e){throw _.create("fid-registration-failed",{errorInfo:r.statusText})}a=o.error?.message??r.statusText;throw _.create("fid-registration-failed",{errorInfo:a})}let Ia="/registrations/";async function Sa(e,t){var a={method:"DELETE",headers:await O(e)};try{var i,n=await(await fetch(N(e.appConfig)+"/"+t,a)).json();if(n.error)throw i=n.error.message,_.create("token-unsubscribe-failed",{errorInfo:i})}catch(e){throw _.create("token-unsubscribe-failed",{errorInfo:e?.toString()})}}function N({projectId:e}){return Gt+`/projects/${e}/registrations`}async function O({appConfig:e,installations:t}){var a=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":"FIS "+a})}function Ta({p256dh:e,auth:t,endpoint:a,vapidKey:i,swScope:n},r,o){var s={web:{origin:((e,t)=>{try{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e))return new URL(e).host}catch{}try{if("undefined"!=typeof self&&self.location?.href)return new URL(e,self.location.origin).host}catch{}return"undefined"!=typeof self&&self.location?.host?self.location.host:t})(n,r),endpoint:a,auth:t,p256dh:e}};return o&&(s.fcm_sdk_version=ma),i!==Qt&&(s.web.applicationPubKey=i),s}let Da=6048e5;async function Ca(e){var t,a,i,n,r,o=await(async(e,t)=>{var a=await e.pushManager.getSubscription();return a||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:na(t)})})(e.swRegistration,e.vapidKey),o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:o.endpoint,auth:C(o.getKey("auth")),p256dh:C(o.getKey("p256dh"))},s=await ha(e.firebaseDependencies);if(s){if(t=s.subscriptionOptions,a=o.vapidKey===t.vapidKey,i=o.endpoint===t.endpoint,n=o.auth===t.auth,r=o.p256dh===t.p256dh,a&&i&&n&&r)return Date.now()>=s.createTime+Da?(async(e,t)=>{try{var a=await(async(e,t)=>{var a=await O(e),i=Ta(t.subscriptionOptions,e.appConfig.appName,!1),a={method:"PATCH",headers:a,body:JSON.stringify(i)};let n;try{var r=await fetch(N(e.appConfig)+"/"+t.token,a);n=await r.json()}catch(e){throw _.create("token-update-failed",{errorInfo:e?.toString()})}if(n.error)throw i=n.error.message,_.create("token-update-failed",{errorInfo:i});if(n.token)return n.token;throw _.create("token-update-no-token")})(e.firebaseDependencies,t),i={...t,token:a,createTime:Date.now()};return await wa(e.firebaseDependencies,i),a}catch(e){throw e}})(e,{token:s.token,createTime:Date.now(),subscriptionOptions:o}):s.token;try{await Sa(e.firebaseDependencies,s.token)}catch(e){console.warn(e)}}return ja(e.firebaseDependencies,o)}async function _a(e,t){var a,i;await Sa(e.firebaseDependencies,t.token),a=K(e.firebaseDependencies),await(i=(await P()).transaction(E,"readwrite")).objectStore(E).delete(a),await i.done,await Pa(e.firebaseDependencies)}async function Ea(e){var a=(await ba(e.firebaseDependencies).catch(()=>{}))?.fid;if(a){{var i=e.firebaseDependencies;var n=a;var r={method:"DELETE",headers:await O(i)};let t;try{t=await fetch(N(i.appConfig)+"/"+n,r)}catch(e){throw _.create("fid-unregister-failed",{errorInfo:e?.toString()})}if(!t.ok)try{throw(await t.json()).error?.message??t.statusText}catch(e){throw _.create("fid-unregister-failed",{errorInfo:"string"==typeof e&&e||t.statusText||e?.toString()})}}await 0}await Pa(e.firebaseDependencies),a&&(i=a,r=e.onUnregisteredHandler)&&("function"==typeof r?r(i):r.next(i))}async function Ma(e){var t=await ha(e.firebaseDependencies),t=(t?await _a(e,t):await Ea(e),await e.swRegistration.pushManager.getSubscription());return!t||t.unsubscribe()}async function ja(e,t){var a={token:await(async(e,t)=>{var a=await O(e),i=Ta(t,e.appConfig.appName,!1),a={method:"POST",headers:a,body:JSON.stringify(i)};let n;try{var r=await fetch(N(e.appConfig),a);n=await r.json()}catch(e){throw _.create("token-subscribe-failed",{errorInfo:e?.toString()})}if(n.error)throw i=n.error.message,_.create("token-subscribe-failed",{errorInfo:i});if(n.token)return n.token;throw _.create("token-subscribe-no-token")})(e,t),createTime:Date.now(),subscriptionOptions:t};return await wa(e,a),a.token}async function Pa(e){try{t=K(e),ga(a=await P()),await(a=a.transaction(M,"readwrite")).objectStore(M).delete(t),await a.done}catch{}var t,a}let Ka=3;async function Na(e,t){var a=await(async(e,t)=>{var a=await e.pushManager.getSubscription();return a||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:na(t)})})(e.swRegistration,e.vapidKey),i={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:a.endpoint,auth:C(a.getKey("auth")),p256dh:C(a.getKey("p256dh"))},n=e.firebaseDependencies.installations;for(let o=0;o<Ka;o++){var r=(await ka(e.firebaseDependencies,i)).responseFid;if(r===t)return;o<Ka-1&&await n.getToken(!0)}throw _.create("fid-registration-failed",{errorInfo:"CreateRegistration response FID does not match Firebase Installation ID"})}async function Oa(e){var t,a,i,n,r=await ba(e.firebaseDependencies).catch(()=>{});if(r)return t=e,await!((i=r.vapidKey)?t.vapidKey=i:t.vapidKey||(t.vapidKey=Qt)),r=await e.firebaseDependencies.installations.getId(),await Na(e,r),i=e.firebaseDependencies,t={fid:r,lastRegisterTime:Date.now(),vapidKey:e.vapidKey},n=K(i),ga(a=await P()),await(a=a.transaction([E,M],"readwrite")).objectStore(M).put(t,n),await a.objectStore(E).delete(n),await a.done,await t,i=r,(n=e.onRegisteredHandler)&&("function"==typeof n?n(i):n.next(i)),r}let Ra="https://play.google.com/log?format=json_proto3",Aa=0,xa=((e,t)=>{var a=[];for(let i=0;i<e.length;i++)a.push(e.charAt(i)),i<t.length&&a.push(t.charAt(i));return a.join("")})("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");function Fa(o,e){"scheduled"===o.logQueue.state&&clearTimeout(o.logQueue.timerId),o.logQueue={state:"stopped"},o.deliveryMetricsExportedToBigQueryEnabled?o.logQueue={state:"scheduled",timerId:setTimeout(async()=>{if(o.logQueue={state:"flushing"},!o.logEvents.length)return Fa(o,Xt);var e=o,t=e.logEvents;e.logEvents=[];for(let r=0,a=t.length;r<a;r+=Zt){var i=t.slice(r,r+Zt);if(!i.length)break;var n=(e=>{var t={};return t.log_source=ta.toString(),t.log_event=e,t})(i);let a=0,e={};do{try{if((e=await fetch(Ra.concat("&key=",xa),{method:"POST",body:JSON.stringify(n)})).ok||!e.ok&&!Ba(e))break;if(!e.ok&&Ba(e))throw new Error("a retriable Non-200 code is returned in fetch to Firelog endpoint. Retry")}catch(e){if(a===Yt)break}let t;try{t=Number((await e.json()).nextRequestWaitMillis)}catch(e){t=ea}await new Promise(e=>setTimeout(e,t)),a++}while(a<Yt)}Fa(e,e.logEvents.length?Aa:Xt)},e)}:o.logEvents=[]}function Ba(e){var t=e.status;return 429===t||500===t||503===t||504===t}async function La(e,t){var a=((e,t)=>{var a={};return e.from&&(a.project_number=e.from),e.fcmMessageId&&(a.message_id=e.fcmMessageId),a.instance_id=t,a.message_type=(e.notification?o.DISPLAY_NOTIFICATION:o.DATA_MESSAGE).toString(),a.sdk_platform=aa.toString(),a.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(a.collapse_key=e.collapse_key),a.event=ia.toString(),e.fcmOptions?.analytics_label&&(a.analytics_label=e.fcmOptions?.analytics_label),a})(t,await e.firebaseDependencies.installations.getId()),i=e,n=a,t=t.productId,a={};a.event_time_ms=Math.floor(Date.now()).toString(),a.source_extension_json_proto3=JSON.stringify({messaging_client_event:n}),t&&(a.compliance_data=(e=>({privacy_context:{prequest:{origin_associated_product_id:e}}}))(t)),i.logEvents.push(a),"stopped"===(n=e).logQueue.state&&0<n.logEvents.length&&Fa(n,Aa)}async function Ha(e,t){t.swRegistration||(t.swRegistration=self.registration);var a=e.newSubscription;if(a)if(await ba(t.firebaseDependencies).catch(()=>{})){a=await Oa(t).catch(()=>{});if(a){var i=await Wa();if(Va(i)){var n,e=i,r=a,o={isFirebaseMessaging:!0,messageType:d.FID_REGISTERED,fid:r};for(n of e)n.postMessage(o)}}}else{i=await ha(t.firebaseDependencies);await Ma(t),t.vapidKey=i?.subscriptionOptions?.vapidKey??Qt,await Ca(t)}else await Ma(t)}async function Ua(e,t){var a=(({data:e})=>{if(!e)return null;try{return e.json()}catch(e){return null}})(e);if(a){t.deliveryMetricsExportedToBigQueryEnabled&&await La(t,a);var i,n,r,o=await Wa();if(Va(o)){var s,e=o,c=a;c.isFirebaseMessaging=!0,c.messageType=d.PUSH_RECEIVED;for(s of e)s.postMessage(c)}else a.notification&&await(e=>{var t=e.actions,a=Notification.maxActions;return t&&a&&t.length>a&&console.warn(`This browser only supports ${a} actions. The remaining actions will not be displayed.`),self.registration.showNotification(e.title??"",e)})(((o={...(e=a).notification}).data={[Jt]:e},o)),t&&t.onBackgroundMessageHandler&&(o={from:(e=a).from,collapseKey:e.collapse_key,messageId:e.fcmMessageId},n=o,(i=e).notification&&(n.notification={},(r=i.notification.title)&&(n.notification.title=r),(r=i.notification.body)&&(n.notification.body=r),(r=i.notification.image)&&(n.notification.image=r),r=i.notification.icon)&&(n.notification.icon=r),i=o,(n=e).data&&(i.data=n.data),i=o,((n=e).fcmOptions||n.notification?.click_action)&&(i.fcmOptions={},(r=n.fcmOptions?.link??n.notification?.click_action)&&(i.fcmOptions.link=r),r=n.fcmOptions?.analytics_label)&&(i.fcmOptions.analyticsLabel=r),a=o,"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(a):t.onBackgroundMessageHandler.next(a))}}async function qa(e){var t=e.notification?.data?.[Jt];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var a=(e=>{var t=e.fcmOptions?.link??e.notification?.click_action;return t||((e=>"object"==typeof e&&e&&zt in e)(e.data)?self.location.origin:null)})(t);if(a){var i,n=new URL(a,self.location.href),r=new URL(self.location.origin);if(n.host===r.host){let e=await(async e=>{var t;for(t of await Wa()){var a=new URL(t.url,self.location.href);if(e.host===a.host)return t}return null})(n);if(e?e=await e.focus():(e=await self.clients.openWindow(a),i=3e3,await new Promise(e=>{setTimeout(e,i)})),e)return t.messageType=d.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function Va(e){return e.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://"))}function Wa(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function $a(e){return _.create("missing-app-config-values",{valueName:e})}class Qa{constructor(e,t,a){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.onRegisteredHandler=null,this.onUnregisteredHandler=null,this._registerNotifyChain=Promise.resolve(),this._fidChangeUnsubscribe=null,this.logEvents=[],this.logQueue={state:"stopped"};var i=(e=>{if(!e||!e.options)throw $a("App Configuration Object");if(!e.name)throw $a("App Name");var t,a=e.options;for(t of["projectId","apiKey","appId","messagingSenderId"])if(!a[t])throw $a(t);return{appName:e.name,projectId:a.projectId,apiKey:a.apiKey,appId:a.appId,senderId:a.messagingSenderId}})(e);this.firebaseDependencies={app:e,appConfig:i,installations:t,analyticsProvider:a}}_delete(){return this._fidChangeUnsubscribe&&(this._fidChangeUnsubscribe(),this._fidChangeUnsubscribe=null),"scheduled"===this.logQueue.state&&clearTimeout(this.logQueue.timerId),this.logQueue={state:"stopped"},Promise.resolve()}}let Ga=e=>{let t=new Qa(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(Ua(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(Ha(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(qa(e))}),t};function Ja(e,t){var a=e=n(e),e=t;if(void 0!==self.document)throw _.create("only-available-in-sw");return a.onBackgroundMessageHandler=e,()=>{a.onBackgroundMessageHandler=null}}ei._registerComponent(new e("messaging-sw",Ga,"PUBLIC"));class za{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return(async(e,t)=>Lt(e=n(e),t))(this._delegate,e)}async deleteToken(){return Wt(n(this._delegate))}onMessage(e){return $t(this._delegate,e)}onBackgroundMessage(e){return Ja(this._delegate,e)}}let Za=e=>self&&"ServiceWorkerGlobalScope"in self?new za(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new za(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),Ya={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?B()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&B()&&!("undefined"==typeof navigator||!navigator.cookieEnabled)&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};F.default.INTERNAL.registerComponent(new e("messaging-compat",Za,"PUBLIC").setServiceProps(Ya)),F.default.registerVersion("@firebase/messaging-compat","0.2.27")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-messaging-compat.js - be sure to load firebase-app.js first.")}});
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},i=`${this.service}/${e}`,o=this.errors[e],a=o?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",s=`${this.serviceName}: ${a} (${i}).`;return new FirebaseError(i,s,n)}}const r=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let i,o;const a=new WeakMap,s=new WeakMap,c=new WeakMap,u=new WeakMap,d=new WeakMap;let l={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return s.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return o||(o=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(a.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return c.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(s.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));s.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,l):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&a.set(t,e)})).catch((()=>{})),d.set(t,e),t}(e);if(u.has(e))return u.get(e);const t=transformCachableValue(e);return t!==e&&(u.set(e,t),d.set(t,e)),t}const unwrap=e=>d.get(e);function openDB(e,t,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){const a=indexedDB.open(e,t),s=wrap(a);return r&&a.addEventListener("upgradeneeded",(e=>{r(wrap(a.result),e.oldVersion,e.newVersion,wrap(a.transaction),e)})),n&&a.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{o&&e.addEventListener("close",(()=>o())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}function deleteDB(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),wrap(n).then((()=>{}))}const p=["get","getKey","getAll","getAllKeys","count"],g=["put","add","delete","clear"],f=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(f.get(t))return f.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=g.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!p.includes(n))return;const method=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let a=o.store;return r&&(a=a.index(t.shift())),(await Promise.all([a[n](...t),i&&o.done]))[0]};return f.set(t,method),method}!function replaceTraps(e){l=e(l)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const h="@firebase/installations",w="0.6.22",y=1e4,b=`w:${w}`,m="FIS_v2",v=36e5,I=new ErrorFactory("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const n=(await t.json()).error;return I.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function getHeaders$1({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const n=getHeaders$1(e);return n.append("Authorization",function getAuthorizationHeader(e){return`${m} ${e}`}(t)),n}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep$1(e){return new Promise((t=>{setTimeout(t,e)}))}const k=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return k.test(t)?t:""}catch{return""}}function getKey$1(e){return`${e.appName}!${e.appId}`}const T=new Map;function fidChanged(e,t){const n=getKey$1(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!S&&"BroadcastChannel"in self&&(S=new BroadcastChannel("[Firebase] FID Change"),S.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return S}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===T.size&&S&&(S.close(),S=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=T.get(e);if(n)for(const e of n)e(t)}let S=null;const E="firebase-installations-store";let D=null;function getDbPromise$1(){return D||(D=openDB("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(E)}})),D}async function set(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(E,"readwrite"),i=r.objectStore(E),o=await i.get(n);return await i.put(t,n),await r.done,o&&o.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey$1(e),n=(await getDbPromise$1()).transaction(E,"readwrite");await n.objectStore(E).delete(t),await n.done}async function update(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(E,"readwrite"),i=r.objectStore(E),o=await i.get(n),a=t(o);return void 0===a?await i.delete(n):await i.put(a,n),await r.done,!a||o&&o.fid===a.fid||fidChanged(e,a.fid),a}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(n),i=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(I.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),i=getHeaders$1(e),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&i.append("x-firebase-client",e)}const a={fid:n,authVersion:m,appId:e.appId,sdkVersion:b},s={method:"POST",headers:i,body:JSON.stringify(a)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=i.registrationPromise,i.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep$1(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw I.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+y<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),i=getHeadersWithAuth(e,n),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&i.append("x-firebase-client",e)}const a={installation:{sdkVersion:b,appId:e.appId}},s={method:"POST",headers:i,body:JSON.stringify(a)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw I.create("not-registered");const i=r.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+v}(e)}(i))return r;if(1===i.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep$1(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw I.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r={...t,authToken:n};return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n={...t,authToken:{requestStatus:0}};await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw I.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+y<Date.now()}(e.authToken)?{...e,authToken:{requestStatus:0}}:e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError$1(e){return I.create("missing-app-config-values",{valueName:e})}const C="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=function extractAppConfig$1(e){if(!e||!e.options)throw getMissingValueError$1("App Configuration");if(!e.name)throw getMissingValueError$1("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw getMissingValueError$1(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,C).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component(C,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(h,w),e(h,w,"esm2020");const R="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",M="FCM_MSG",F=1e3,A=864e5;var B,P;function arrayToBase64(e){const t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function base64ToArray(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;++e)r[e]=n.charCodeAt(e);return r}!function(e){e[e.DATA_MESSAGE=1]="DATA_MESSAGE",e[e.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION"}(B||(B={})),function(e){e.PUSH_RECEIVED="push-received",e.NOTIFICATION_CLICKED="notification-clicked",e.FID_REGISTERED="fid-registered"}(P||(P={}));const O="fcm_token_details_db",_="fcm_token_object_Store";const x=new ErrorFactory("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","fid-registration-failed":"A problem occurred while creating an FCM registration via FID: {$errorInfo}","fid-unregister-failed":"A problem occurred while unregistering the FCM registration via FID: {$errorInfo}","fid-registration-idb-schema-unavailable":"Unable to read or persist FID registration metadata because the messaging IndexedDB schema is unavailable (for example, the database could not be upgraded to the latest version).","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used.","invalid-on-registered-handler":"No onRegistered callback handler was provided or registered. Implement onRegistered() before register()."}),j="firebase-messaging-database",K="firebase-messaging-store",N="firebase-messaging-fid-registration-store";let $={openDB:openDB,deleteDB:deleteDB},L=null;function createOpenDbOptions(e){return{upgrade:(t,n)=>{!function migrateMessagingDb(e,t,n){switch(t){case 0:if(e.createObjectStore(K),1===n)break;case 1:2===n&&e.createObjectStore(N)}}(t,n,e)},blocked:()=>{},blocking:(e,t,n)=>{L=null,n.target?.close()},terminated:()=>{L=null}}}function getDbPromise(){if(!L){const e=$.openDB(j,2,createOpenDbOptions(2));L=e.catch((()=>$.openDB(j,1,createOpenDbOptions(1))))}return L}function hasObjectStore(e,t){return e.objectStoreNames.contains(t)}function assertFidRegistrationObjectStore(e){if(!hasObjectStore(e,N))throw x.create("fid-registration-idb-schema-unavailable")}async function dbGet(e){const t=getKey(e),n=await getDbPromise(),r=await n.transaction(K).objectStore(K).get(t);if(r)return r;{const t=await async function migrateOldDatabase(e){if("databases"in indexedDB){const e=(await indexedDB.databases()).map((e=>e.name));if(!e.includes(O))return null}let t=null;return(await openDB(O,5,{upgrade:async(n,r,i,o)=>{if(r<2)return;if(!n.objectStoreNames.contains(_))return;const a=o.objectStore(_),s=await a.index("fcmSenderId").get(e);if(await a.clear(),s)if(2===r){const e=s;if(!e.auth||!e.p256dh||!e.endpoint)return;t={token:e.fcmToken,createTime:e.createTime??Date.now(),subscriptionOptions:{auth:e.auth,p256dh:e.p256dh,endpoint:e.endpoint,swScope:e.swScope,vapidKey:"string"==typeof e.vapidKey?e.vapidKey:arrayToBase64(e.vapidKey)}}}else if(3===r){const e=s;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}else if(4===r){const e=s;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}}})).close(),await deleteDB(O),await deleteDB("fcm_vapid_details_db"),await deleteDB("undefined"),function checkTokenDetails(e){if(!e||!e.subscriptionOptions)return!1;const{subscriptionOptions:t}=e;return"number"==typeof e.createTime&&e.createTime>0&&"string"==typeof e.token&&e.token.length>0&&"string"==typeof t.auth&&t.auth.length>0&&"string"==typeof t.p256dh&&t.p256dh.length>0&&"string"==typeof t.endpoint&&t.endpoint.length>0&&"string"==typeof t.swScope&&t.swScope.length>0&&"string"==typeof t.vapidKey&&t.vapidKey.length>0}(t)?t:null}(e.appConfig.senderId);if(t)return await dbSet(e,t),t}}async function dbSet(e,t){const n=getKey(e),r=await getDbPromise(),i=[K],o=hasObjectStore(r,N);o&&i.push(N);const a=r.transaction(i,"readwrite");return await a.objectStore(K).put(t,n),o&&await a.objectStore(N).delete(n),await a.done,t}async function dbGetFidRegistration(e){const t=getKey(e),n=await getDbPromise();return assertFidRegistrationObjectStore(n),await n.transaction(N).objectStore(N).get(t)}function getKey({appConfig:e}){return e.appId}async function requestCreateRegistration(e,t){const n=await getHeaders(e),r=getBody(t,e.appConfig.appName,!0),i={method:"POST",headers:n,body:JSON.stringify(r)};let o,a;try{o=await async function fetchWithExponentialRetry(e,t,n){let r;for(let i=0;i<t;i++)try{return await e()}catch(e){if(r=e,i<t-1){const e=n*Math.pow(2,i);await new Promise((t=>setTimeout(t,e)))}}throw r}((()=>fetch(getEndpoint(e.appConfig),i)),3,1e3)}catch(e){throw x.create("fid-registration-failed",{errorInfo:e?.toString()})}if(o.ok){const e=await async function parseCreateRegistrationSuccessFid(e){const t=await e.text();if(!t.trim())throw x.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is empty"});let n;try{n=JSON.parse(t)}catch{throw x.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is not valid JSON"})}const r=n.name;if("string"!=typeof r||0===r.length)throw x.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response did not include a non-empty name"});return function parseFidFromRegistrationResourceName(e){const t=e.indexOf(q);if(-1!==t){const n=e.slice(t+q.length);if(n.length>0)return n}throw x.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response name is not a valid registration resource name"})}(r)}(o);return{responseFid:e}}try{a=await o.json()}catch(e){throw x.create("fid-registration-failed",{errorInfo:o.statusText})}const s=a.error?.message??o.statusText;throw x.create("fid-registration-failed",{errorInfo:s})}const q="/registrations/";async function requestDeleteToken(e,t){const n={method:"DELETE",headers:await getHeaders(e)};try{const r=await fetch(`${getEndpoint(e.appConfig)}/${t}`,n),i=await r.json();if(i.error){const e=i.error.message;throw x.create("token-unsubscribe-failed",{errorInfo:e})}}catch(e){throw x.create("token-unsubscribe-failed",{errorInfo:e?.toString()})}}function getEndpoint({projectId:e}){return`https://fcmregistrations.googleapis.com/v1/projects/${e}/registrations`}async function getHeaders({appConfig:e,installations:t}){const n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function getRegistrationOrigin(e,t){try{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e))return new URL(e).host}catch{}try{if("undefined"!=typeof self&&self.location?.href)return new URL(e,self.location.origin).host}catch{}return"undefined"!=typeof self&&self.location?.host?self.location.host:t}function getBody({p256dh:e,auth:t,endpoint:n,vapidKey:r,swScope:i},o,a){const s={web:{origin:getRegistrationOrigin(i,o),endpoint:n,auth:t,p256dh:e}};return a&&(s.fcm_sdk_version="0.13.0"),r!==R&&(s.web.applicationPubKey=r),s}async function getTokenInternal(e){const t=await async function getPushSubscription$1(e,t){const n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:base64ToArray(t)})}(e.swRegistration,e.vapidKey),n={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:arrayToBase64(t.getKey("auth")),p256dh:arrayToBase64(t.getKey("p256dh"))},r=await dbGet(e.firebaseDependencies);if(r){if(function isTokenValid(e,t){const n=t.vapidKey===e.vapidKey,r=t.endpoint===e.endpoint,i=t.auth===e.auth,o=t.p256dh===e.p256dh;return n&&r&&i&&o}(r.subscriptionOptions,n))return Date.now()>=r.createTime+6048e5?async function updateToken(e,t){try{const n=await async function requestUpdateToken(e,t){const n=await getHeaders(e),r=getBody(t.subscriptionOptions,e.appConfig.appName,!1),i={method:"PATCH",headers:n,body:JSON.stringify(r)};let o;try{const n=await fetch(`${getEndpoint(e.appConfig)}/${t.token}`,i);o=await n.json()}catch(e){throw x.create("token-update-failed",{errorInfo:e?.toString()})}if(o.error){const e=o.error.message;throw x.create("token-update-failed",{errorInfo:e})}if(!o.token)throw x.create("token-update-no-token");return o.token}(e.firebaseDependencies,t),r={...t,token:n,createTime:Date.now()};return await dbSet(e.firebaseDependencies,r),n}catch(e){throw e}}(e,{token:r.token,createTime:Date.now(),subscriptionOptions:n}):r.token;try{await requestDeleteToken(e.firebaseDependencies,r.token)}catch(e){console.warn(e)}return getNewToken(e.firebaseDependencies,n)}return getNewToken(e.firebaseDependencies,n)}async function revokeLegacyFcmTokenAndClearCaches(e,t){await requestDeleteToken(e.firebaseDependencies,t.token),await async function dbRemove(e){const t=getKey(e),n=(await getDbPromise()).transaction(K,"readwrite");await n.objectStore(K).delete(t),await n.done}(e.firebaseDependencies),await removeFidRegistrationBestEffort(e.firebaseDependencies)}async function revokeFidRegistrationIfStored(e){const t=await dbGetFidRegistration(e.firebaseDependencies).catch((()=>{})),n=t?.fid;n&&await async function requestDeleteRegistration(e,t){const n={method:"DELETE",headers:await getHeaders(e)};let r;try{r=await fetch(`${getEndpoint(e.appConfig)}/${t}`,n)}catch(e){throw x.create("fid-unregister-failed",{errorInfo:e?.toString()})}if(!r.ok)try{const e=await r.json();throw e.error?.message??r.statusText}catch(e){throw x.create("fid-unregister-failed",{errorInfo:"string"==typeof e&&e||r.statusText||e?.toString()})}}(e.firebaseDependencies,n),await removeFidRegistrationBestEffort(e.firebaseDependencies),n&&function notifyOnUnregistered(e,t){const n=e.onUnregisteredHandler;if(!n)return;"function"==typeof n?n(t):n.next(t)}(e,n)}async function revokeRegistrationInternal(e){const t=await dbGet(e.firebaseDependencies);t?await revokeLegacyFcmTokenAndClearCaches(e,t):await revokeFidRegistrationIfStored(e);const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function getNewToken(e,t){const n=await async function requestGetToken(e,t){const n=await getHeaders(e),r=getBody(t,e.appConfig.appName,!1),i={method:"POST",headers:n,body:JSON.stringify(r)};let o;try{const t=await fetch(getEndpoint(e.appConfig),i);o=await t.json()}catch(e){throw x.create("token-subscribe-failed",{errorInfo:e?.toString()})}if(o.error){const e=o.error.message;throw x.create("token-subscribe-failed",{errorInfo:e})}if(!o.token)throw x.create("token-subscribe-no-token");return o.token}(e,t),r={token:n,createTime:Date.now(),subscriptionOptions:t};return await dbSet(e,r),r.token}async function removeFidRegistrationBestEffort(e){try{await async function dbRemoveFidRegistration(e){const t=getKey(e),n=await getDbPromise();assertFidRegistrationObjectStore(n);const r=n.transaction(N,"readwrite");await r.objectStore(N).delete(t),await r.done}(e)}catch{}}async function registerFcmRegistrationWithFid(e,t){const n=await async function getPushSubscription(e,t){const n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:base64ToArray(t)})}(e.swRegistration,e.vapidKey),r={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:n.endpoint,auth:arrayToBase64(n.getKey("auth")),p256dh:arrayToBase64(n.getKey("p256dh"))},i=e.firebaseDependencies.installations;for(let n=0;n<3;n++){const{responseFid:o}=await requestCreateRegistration(e.firebaseDependencies,r);if(o===t)return;n<2&&await i.getToken(!0)}throw x.create("fid-registration-failed",{errorInfo:"CreateRegistration response FID does not match Firebase Installation ID"})}async function refreshFidRegistrationIfStored(e){const t=await dbGetFidRegistration(e.firebaseDependencies).catch((()=>{}));if(!t)return;await async function updateVapidKey(e,t){t?e.vapidKey=t:e.vapidKey||(e.vapidKey=R)}(e,t.vapidKey);const n=await e.firebaseDependencies.installations.getId();return await registerFcmRegistrationWithFid(e,n),await async function dbSetFidRegistration(e,t){const n=getKey(e),r=await getDbPromise();assertFidRegistrationObjectStore(r);const i=r.transaction([K,N],"readwrite");return await i.objectStore(N).put(t,n),await i.objectStore(K).delete(n),await i.done,t}(e.firebaseDependencies,{fid:n,lastRegisterTime:Date.now(),vapidKey:e.vapidKey}),function notifyOnRegistered(e,t){const n=e.onRegisteredHandler;n&&("function"==typeof n?n(t):n.next(t))}(e,n),n}const H="https://play.google.com/log?format=json_proto3",U=function _mergeStrings(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");function startLoggingService(e){"stopped"===e.logQueue.state&&e.logEvents.length>0&&_processQueue(e,0)}function _processQueue(e,t){"scheduled"===e.logQueue.state&&clearTimeout(e.logQueue.timerId),e.logQueue={state:"stopped"},e.deliveryMetricsExportedToBigQueryEnabled?e.logQueue={state:"scheduled",timerId:setTimeout((async()=>{if(e.logQueue={state:"flushing"},!e.logEvents.length)return _processQueue(e,A);await async function _dispatchLogEvents(e){const t=e.logEvents;e.logEvents=[];for(let e=0,n=t.length;e<n;e+=F){const n=t.slice(e,e+F);if(!n.length)break;const r=_createLogRequest(n);let i=0,o={};do{try{if(o=await fetch(H.concat("&key=",U),{method:"POST",body:JSON.stringify(r)}),o.ok||!o.ok&&!isRetriableError(o))break;if(!o.ok&&isRetriableError(o))throw new Error("a retriable Non-200 code is returned in fetch to Firelog endpoint. Retry")}catch(e){if(3===i)break}let e;try{e=Number((await o.json()).nextRequestWaitMillis)}catch(t){e=5e3}await new Promise((t=>setTimeout(t,e))),i++}while(i<3)}_processQueue(e,e.logEvents.length?0:A)}(e)}),t)}:e.logEvents=[]}function isRetriableError(e){const t=e.status;return 429===t||500===t||503===t||504===t}async function stageLog(e,t){const n=function createFcmEvent(e,t){const n={};e.from&&(n.project_number=e.from);e.fcmMessageId&&(n.message_id=e.fcmMessageId);n.instance_id=t,e.notification?n.message_type=B.DISPLAY_NOTIFICATION.toString():n.message_type=B.DATA_MESSAGE.toString();n.sdk_platform=3..toString(),n.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),!e.collapse_key||(n.collapse_key=e.collapse_key);n.event=1..toString(),!e.fcmOptions?.analytics_label||(n.analytics_label=e.fcmOptions?.analytics_label);return n}(t,await e.firebaseDependencies.installations.getId());!function createAndEnqueueLogEvent(e,t,n){const r={};r.event_time_ms=Math.floor(Date.now()).toString(),r.source_extension_json_proto3=JSON.stringify({messaging_client_event:t}),!n||(r.compliance_data=function buildComplianceData(e){const t={privacy_context:{prequest:{origin_associated_product_id:e}}};return t}(n));e.logEvents.push(r)}(e,n,t.productId),startLoggingService(e)}function _createLogRequest(e){const t={};return t.log_source=1249..toString(),t.log_event=e,t}async function onSubChange(e,t){t.swRegistration||(t.swRegistration=self.registration);const{newSubscription:n}=e;if(!n)return void await revokeRegistrationInternal(t);if(await dbGetFidRegistration(t.firebaseDependencies).catch((()=>{}))){const e=await refreshFidRegistrationIfStored(t).catch((()=>{}));if(e){const t=await getClientList();hasVisibleClients(t)&&function sendFidRegisteredToWindows(e,t){const n={isFirebaseMessaging:!0,messageType:P.FID_REGISTERED,fid:t};for(const t of e)t.postMessage(n)}(t,e)}return}const r=await dbGet(t.firebaseDependencies);await revokeRegistrationInternal(t),t.vapidKey=r?.subscriptionOptions?.vapidKey??R,await getTokenInternal(t)}async function onPush(e,t){const n=function getMessagePayloadInternal({data:e}){if(!e)return null;try{return e.json()}catch(e){return null}}(e);if(!n)return;t.deliveryMetricsExportedToBigQueryEnabled&&await stageLog(t,n);const r=await getClientList();if(hasVisibleClients(r))return function sendMessagePayloadInternalToWindows(e,t){t.isFirebaseMessaging=!0,t.messageType=P.PUSH_RECEIVED;for(const n of e)n.postMessage(t)}(r,n);if(n.notification&&await function showNotification(e){const{actions:t}=e,{maxActions:n}=Notification;t&&n&&t.length>n&&console.warn(`This browser only supports ${n} actions. The remaining actions will not be displayed.`);return self.registration.showNotification(e.title??"",e)}(function wrapInternalPayload(e){const t={...e.notification};return t.data={[M]:e},t}(n)),t&&t.onBackgroundMessageHandler){const e=function externalizePayload(e){const t={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return function propagateNotificationPayload(e,t){if(!t.notification)return;e.notification={};const n=t.notification.title;n&&(e.notification.title=n);const r=t.notification.body;r&&(e.notification.body=r);const i=t.notification.image;i&&(e.notification.image=i);const o=t.notification.icon;o&&(e.notification.icon=o)}(t,e),function propagateDataPayload(e,t){t.data&&(e.data=t.data)}(t,e),function propagateFcmOptions(e,t){if(!t.fcmOptions&&!t.notification?.click_action)return;e.fcmOptions={};const n=t.fcmOptions?.link??t.notification?.click_action;n&&(e.fcmOptions.link=n);const r=t.fcmOptions?.analytics_label;r&&(e.fcmOptions.analyticsLabel=r)}(t,e),t}(n);"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(e):t.onBackgroundMessageHandler.next(e)}}async function onNotificationClick(e){const t=e.notification?.data?.[M];if(!t)return;if(e.action)return;e.stopImmediatePropagation(),e.notification.close();const n=function getLink(e){const t=e.fcmOptions?.link??e.notification?.click_action;if(t)return t;return function isConsoleMessage(e){return"object"==typeof e&&!!e&&"google.c.a.c_id"in e}(e.data)?self.location.origin:null}(t);if(!n)return;const r=new URL(n,self.location.href),i=new URL(self.location.origin);if(r.host!==i.host)return;let o=await async function getWindowClient(e){const t=await getClientList();for(const n of t){const t=new URL(n.url,self.location.href);if(e.host===t.host)return n}return null}(r);return o?o=await o.focus():(o=await self.clients.openWindow(n),await function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}(3e3)),o?(t.messageType=P.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,o.postMessage(t)):void 0}function hasVisibleClients(e){return e.some((e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))}function getClientList(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function getMissingValueError(e){return x.create("missing-app-config-values",{valueName:e})}class MessagingService{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.onRegisteredHandler=null,this.onUnregisteredHandler=null,this._registerNotifyChain=Promise.resolve(),this._fidChangeUnsubscribe=null,this.logEvents=[],this.logQueue={state:"stopped"};const r=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration Object");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId","messagingSenderId"],{options:n}=e;for(const e of t)if(!n[e])throw getMissingValueError(e);return{appName:e.name,projectId:n.projectId,apiKey:n.apiKey,appId:n.appId,senderId:n.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return this._fidChangeUnsubscribe&&(this._fidChangeUnsubscribe(),this._fidChangeUnsubscribe=null),"scheduled"===this.logQueue.state&&clearTimeout(this.logQueue.timerId),this.logQueue={state:"stopped"},Promise.resolve()}}const SwMessagingFactory=e=>{const t=new MessagingService(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",(e=>{e.waitUntil(onPush(e,t))})),self.addEventListener("pushsubscriptionchange",(e=>{e.waitUntil(onSubChange(e,t))})),self.addEventListener("notificationclick",(e=>{e.waitUntil(onNotificationClick(e))})),t};async function isSwSupported(){return function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}()&&await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{t(i.error?.message||"")}}catch(e){t(e)}}))}()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}function _setDeliveryMetricsExportedToBigQueryEnabled(e,t){const n=e;n.deliveryMetricsExportedToBigQueryEnabled=t,t?startLoggingService(n):function stopLoggingServiceAndClearQueue(e){"scheduled"===e.logQueue.state&&clearTimeout(e.logQueue.timerId),e.logQueue={state:"stopped"},e.logEvents=[]}(n)}function getMessagingInSw(e=n()){return isSwSupported().then((e=>{if(!e)throw x.create("unsupported-browser")}),(e=>{throw x.create("indexed-db-unsupported")})),_getProvider(getModularInstance(e),"messaging-sw").getImmediate()}function onBackgroundMessage(e,t){return function onBackgroundMessage$1(e,t){if(void 0!==self.document)throw x.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=getModularInstance(e),t)}function onRegistered(e,t){return function onRegistered$1(e,t){return e.onRegisteredHandler=t,()=>{e.onRegisteredHandler===t&&(e.onRegisteredHandler=null)}}(e=getModularInstance(e),t)}function onUnregistered(e,t){return function onUnregistered$1(e,t){return e.onUnregisteredHandler=t,()=>{e.onUnregisteredHandler===t&&(e.onUnregisteredHandler=null)}}(e=getModularInstance(e),t)}function experimentalSetDeliveryMetricsExportedToBigQueryEnabled(e,t){return _setDeliveryMetricsExportedToBigQueryEnabled(e=getModularInstance(e),t)}!function registerMessagingInSw(){t(new Component("messaging-sw",SwMessagingFactory,"PUBLIC"))}();export{experimentalSetDeliveryMetricsExportedToBigQueryEnabled,getMessagingInSw as getMessaging,isSwSupported as isSupported,onBackgroundMessage,onRegistered,onUnregistered};
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},i=`${this.service}/${e}`,a=this.errors[e],o=a?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(a,n):"Error",s=`${this.serviceName}: ${o} (${i}).`;return new FirebaseError(i,s,n)}}const r=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let i,a;const o=new WeakMap,s=new WeakMap,c=new WeakMap,d=new WeakMap,u=new WeakMap;let g={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return s.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return a||(a=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(o.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return c.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(s.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));s.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,g):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&o.set(t,e)})).catch((()=>{})),u.set(t,e),t}(e);if(d.has(e))return d.get(e);const t=transformCachableValue(e);return t!==e&&(d.set(e,t),u.set(t,e)),t}const unwrap=e=>u.get(e);function openDB(e,t,{blocked:n,upgrade:r,blocking:i,terminated:a}={}){const o=indexedDB.open(e,t),s=wrap(o);return r&&o.addEventListener("upgradeneeded",(e=>{r(wrap(o.result),e.oldVersion,e.newVersion,wrap(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{a&&e.addEventListener("close",(()=>a())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}function deleteDB(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),wrap(n).then((()=>{}))}const l=["get","getKey","getAll","getAllKeys","count"],p=["put","add","delete","clear"],f=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(f.get(t))return f.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=p.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!l.includes(n))return;const method=async function(e,...t){const a=this.transaction(e,i?"readwrite":"readonly");let o=a.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&a.done]))[0]};return f.set(t,method),method}!function replaceTraps(e){g=e(g)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const h="@firebase/installations",w="0.6.22",y=1e4,b=`w:${w}`,m="FIS_v2",v=36e5,I=new ErrorFactory("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const n=(await t.json()).error;return I.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function getHeaders$1({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const n=getHeaders$1(e);return n.append("Authorization",function getAuthorizationHeader(e){return`${m} ${e}`}(t)),n}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const k=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return k.test(t)?t:""}catch{return""}}function getKey$1(e){return`${e.appName}!${e.appId}`}const T=new Map;function fidChanged(e,t){const n=getKey$1(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=getBroadcastChannel();n&&n.postMessage({key:e,fid:t});closeBroadcastChannel()}(n,t)}function callFidChangeCallbacks(e,t){const n=T.get(e);if(n)for(const e of n)e(t)}let S=null;function getBroadcastChannel(){return!S&&"BroadcastChannel"in self&&(S=new BroadcastChannel("[Firebase] FID Change"),S.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)}),S}function closeBroadcastChannel(){0===T.size&&S&&(S.close(),S=null)}const D="firebase-installations-store";let C=null;function getDbPromise$1(){return C||(C=openDB("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(D)}})),C}async function set(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(D,"readwrite"),i=r.objectStore(D),a=await i.get(n);return await i.put(t,n),await r.done,a&&a.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey$1(e),n=(await getDbPromise$1()).transaction(D,"readwrite");await n.objectStore(D).delete(t),await n.done}async function update(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(D,"readwrite"),i=r.objectStore(D),a=await i.get(n),o=t(a);return void 0===o?await i.delete(n):await i.put(o,n),await r.done,!o||a&&a.fid===o.fid||fidChanged(e,o.fid),o}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(n),i=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(I.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),i=getHeaders$1(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&i.append("x-firebase-client",e)}const o={fid:n,authVersion:m,appId:e.appId,sdkVersion:b},s={method:"POST",headers:i,body:JSON.stringify(o)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=i.registrationPromise,i.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw I.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+y<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),i=getHeadersWithAuth(e,n),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&i.append("x-firebase-client",e)}const o={installation:{sdkVersion:b,appId:e.appId}},s={method:"POST",headers:i,body:JSON.stringify(o)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw I.create("not-registered");const i=r.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+v}(e)}(i))return r;if(1===i.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw I.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r={...t,authToken:n};return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n={...t,authToken:{requestStatus:0}};await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw I.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+y<Date.now()}(e.authToken)?{...e,authToken:{requestStatus:0}}:e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken$2(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function onIdChange(e,t){const{appConfig:n}=e;return function addCallback(e,t){getBroadcastChannel();const n=getKey$1(e);let r=T.get(n);r||(r=new Set,T.set(n,r)),r.add(t)}(n,t),()=>{!function removeCallback(e,t){const n=getKey$1(e),r=T.get(n);r&&(r.delete(t),0===r.size&&T.delete(n),closeBroadcastChannel())}(n,t)}}function getMissingValueError$1(e){return I.create("missing-app-config-values",{valueName:e})}const R="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=function extractAppConfig$1(e){if(!e||!e.options)throw getMissingValueError$1("App Configuration");if(!e.name)throw getMissingValueError$1("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw getMissingValueError$1(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,R).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken$2(n,e)}};!function registerInstallations(){t(new Component(R,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(h,w),e(h,w,"esm2020");const E="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",F="google.c.a.c_id",M=1e4;var P,A;function arrayToBase64(e){const t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function base64ToArray(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;++e)r[e]=n.charCodeAt(e);return r}!function(e){e[e.DATA_MESSAGE=1]="DATA_MESSAGE",e[e.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION"}(P||(P={})),function(e){e.PUSH_RECEIVED="push-received",e.NOTIFICATION_CLICKED="notification-clicked",e.FID_REGISTERED="fid-registered"}(A||(A={}));const B="fcm_token_details_db",O="fcm_token_object_Store";const $=new ErrorFactory("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","fid-registration-failed":"A problem occurred while creating an FCM registration via FID: {$errorInfo}","fid-unregister-failed":"A problem occurred while unregistering the FCM registration via FID: {$errorInfo}","fid-registration-idb-schema-unavailable":"Unable to read or persist FID registration metadata because the messaging IndexedDB schema is unavailable (for example, the database could not be upgraded to the latest version).","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used.","invalid-on-registered-handler":"No onRegistered callback handler was provided or registered. Implement onRegistered() before register()."}),K="firebase-messaging-database",j="firebase-messaging-store",x="firebase-messaging-fid-registration-store";let N={openDB:openDB,deleteDB:deleteDB},_=null;function createOpenDbOptions(e){return{upgrade:(t,n)=>{!function migrateMessagingDb(e,t,n){switch(t){case 0:if(e.createObjectStore(j),1===n)break;case 1:2===n&&e.createObjectStore(x)}}(t,n,e)},blocked:()=>{},blocking:(e,t,n)=>{_=null,n.target?.close()},terminated:()=>{_=null}}}function getDbPromise(){if(!_){const e=N.openDB(K,2,createOpenDbOptions(2));_=e.catch((()=>N.openDB(K,1,createOpenDbOptions(1))))}return _}function hasObjectStore(e,t){return e.objectStoreNames.contains(t)}function assertFidRegistrationObjectStore(e){if(!hasObjectStore(e,x))throw $.create("fid-registration-idb-schema-unavailable")}async function dbGet(e){const t=getKey(e),n=await getDbPromise(),r=await n.transaction(j).objectStore(j).get(t);if(r)return r;{const t=await async function migrateOldDatabase(e){if("databases"in indexedDB){const e=(await indexedDB.databases()).map((e=>e.name));if(!e.includes(B))return null}let t=null;return(await openDB(B,5,{upgrade:async(n,r,i,a)=>{if(r<2)return;if(!n.objectStoreNames.contains(O))return;const o=a.objectStore(O),s=await o.index("fcmSenderId").get(e);if(await o.clear(),s)if(2===r){const e=s;if(!e.auth||!e.p256dh||!e.endpoint)return;t={token:e.fcmToken,createTime:e.createTime??Date.now(),subscriptionOptions:{auth:e.auth,p256dh:e.p256dh,endpoint:e.endpoint,swScope:e.swScope,vapidKey:"string"==typeof e.vapidKey?e.vapidKey:arrayToBase64(e.vapidKey)}}}else if(3===r){const e=s;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}else if(4===r){const e=s;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}}})).close(),await deleteDB(B),await deleteDB("fcm_vapid_details_db"),await deleteDB("undefined"),function checkTokenDetails(e){if(!e||!e.subscriptionOptions)return!1;const{subscriptionOptions:t}=e;return"number"==typeof e.createTime&&e.createTime>0&&"string"==typeof e.token&&e.token.length>0&&"string"==typeof t.auth&&t.auth.length>0&&"string"==typeof t.p256dh&&t.p256dh.length>0&&"string"==typeof t.endpoint&&t.endpoint.length>0&&"string"==typeof t.swScope&&t.swScope.length>0&&"string"==typeof t.vapidKey&&t.vapidKey.length>0}(t)?t:null}(e.appConfig.senderId);if(t)return await dbSet(e,t),t}}async function dbSet(e,t){const n=getKey(e),r=await getDbPromise(),i=[j],a=hasObjectStore(r,x);a&&i.push(x);const o=r.transaction(i,"readwrite");return await o.objectStore(j).put(t,n),a&&await o.objectStore(x).delete(n),await o.done,t}async function dbRemove(e){const t=getKey(e),n=(await getDbPromise()).transaction(j,"readwrite");await n.objectStore(j).delete(t),await n.done}async function dbGetFidRegistration(e){const t=getKey(e),n=await getDbPromise();return assertFidRegistrationObjectStore(n),await n.transaction(x).objectStore(x).get(t)}async function dbRemoveFidRegistration(e){const t=getKey(e),n=await getDbPromise();assertFidRegistrationObjectStore(n);const r=n.transaction(x,"readwrite");await r.objectStore(x).delete(t),await r.done}function getKey({appConfig:e}){return e.appId}const q="@firebase/messaging",H="0.13.0";async function requestCreateRegistration(e,t){const n=await getHeaders(e),r=getBody(t,e.appConfig.appName,!0),i={method:"POST",headers:n,body:JSON.stringify(r)};let a,o;try{a=await async function fetchWithExponentialRetry(e,t,n){let r;for(let i=0;i<t;i++)try{return await e()}catch(e){if(r=e,i<t-1){const e=n*Math.pow(2,i);await new Promise((t=>setTimeout(t,e)))}}throw r}((()=>fetch(getEndpoint(e.appConfig),i)),3,1e3)}catch(e){throw $.create("fid-registration-failed",{errorInfo:e?.toString()})}if(a.ok){const e=await async function parseCreateRegistrationSuccessFid(e){const t=await e.text();if(!t.trim())throw $.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is empty"});let n;try{n=JSON.parse(t)}catch{throw $.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response body is not valid JSON"})}const r=n.name;if("string"!=typeof r||0===r.length)throw $.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response did not include a non-empty name"});return function parseFidFromRegistrationResourceName(e){const t=e.indexOf(V);if(-1!==t){const n=e.slice(t+V.length);if(n.length>0)return n}throw $.create("fid-registration-failed",{errorInfo:"CreateRegistration succeeded but response name is not a valid registration resource name"})}(r)}(a);return{responseFid:e}}try{o=await a.json()}catch(e){throw $.create("fid-registration-failed",{errorInfo:a.statusText})}const s=o.error?.message??a.statusText;throw $.create("fid-registration-failed",{errorInfo:s})}async function requestDeleteRegistration(e,t){const n={method:"DELETE",headers:await getHeaders(e)};let r;try{r=await fetch(`${getEndpoint(e.appConfig)}/${t}`,n)}catch(e){throw $.create("fid-unregister-failed",{errorInfo:e?.toString()})}if(!r.ok)try{const e=await r.json();throw e.error?.message??r.statusText}catch(e){throw $.create("fid-unregister-failed",{errorInfo:"string"==typeof e&&e||r.statusText||e?.toString()})}}const V="/registrations/";async function requestDeleteToken(e,t){const n={method:"DELETE",headers:await getHeaders(e)};try{const r=await fetch(`${getEndpoint(e.appConfig)}/${t}`,n),i=await r.json();if(i.error){const e=i.error.message;throw $.create("token-unsubscribe-failed",{errorInfo:e})}}catch(e){throw $.create("token-unsubscribe-failed",{errorInfo:e?.toString()})}}function getEndpoint({projectId:e}){return`https://fcmregistrations.googleapis.com/v1/projects/${e}/registrations`}async function getHeaders({appConfig:e,installations:t}){const n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function getRegistrationOrigin(e,t){try{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e))return new URL(e).host}catch{}try{if("undefined"!=typeof self&&self.location?.href)return new URL(e,self.location.origin).host}catch{}return"undefined"!=typeof self&&self.location?.host?self.location.host:t}function getBody({p256dh:e,auth:t,endpoint:n,vapidKey:r,swScope:i},a,o){const s={web:{origin:getRegistrationOrigin(i,a),endpoint:n,auth:t,p256dh:e}};return o&&(s.fcm_sdk_version=H),r!==E&&(s.web.applicationPubKey=r),s}async function getTokenInternal(e){const t=await async function getPushSubscription$1(e,t){const n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:base64ToArray(t)})}(e.swRegistration,e.vapidKey),n={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:arrayToBase64(t.getKey("auth")),p256dh:arrayToBase64(t.getKey("p256dh"))},r=await dbGet(e.firebaseDependencies);if(r){if(function isTokenValid(e,t){const n=t.vapidKey===e.vapidKey,r=t.endpoint===e.endpoint,i=t.auth===e.auth,a=t.p256dh===e.p256dh;return n&&r&&i&&a}(r.subscriptionOptions,n))return Date.now()>=r.createTime+6048e5?async function updateToken(e,t){try{const n=await async function requestUpdateToken(e,t){const n=await getHeaders(e),r=getBody(t.subscriptionOptions,e.appConfig.appName,!1),i={method:"PATCH",headers:n,body:JSON.stringify(r)};let a;try{const n=await fetch(`${getEndpoint(e.appConfig)}/${t.token}`,i);a=await n.json()}catch(e){throw $.create("token-update-failed",{errorInfo:e?.toString()})}if(a.error){const e=a.error.message;throw $.create("token-update-failed",{errorInfo:e})}if(!a.token)throw $.create("token-update-no-token");return a.token}(e.firebaseDependencies,t),r={...t,token:n,createTime:Date.now()};return await dbSet(e.firebaseDependencies,r),n}catch(e){throw e}}(e,{token:r.token,createTime:Date.now(),subscriptionOptions:n}):r.token;try{await requestDeleteToken(e.firebaseDependencies,r.token)}catch(e){console.warn(e)}return getNewToken(e.firebaseDependencies,n)}return getNewToken(e.firebaseDependencies,n)}async function revokeRegistrationInternal(e){const t=await dbGet(e.firebaseDependencies);t?await async function revokeLegacyFcmTokenAndClearCaches(e,t){await requestDeleteToken(e.firebaseDependencies,t.token),await dbRemove(e.firebaseDependencies),await removeFidRegistrationBestEffort(e.firebaseDependencies)}(e,t):await async function revokeFidRegistrationIfStored(e){const t=await dbGetFidRegistration(e.firebaseDependencies).catch((()=>{})),n=t?.fid;n&&await requestDeleteRegistration(e.firebaseDependencies,n),await removeFidRegistrationBestEffort(e.firebaseDependencies),n&&function notifyOnUnregistered(e,t){const n=e.onUnregisteredHandler;n&&("function"==typeof n?n(t):n.next(t))}(e,n)}(e);const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function getNewToken(e,t){const n=await async function requestGetToken(e,t){const n=await getHeaders(e),r=getBody(t,e.appConfig.appName,!1),i={method:"POST",headers:n,body:JSON.stringify(r)};let a;try{const t=await fetch(getEndpoint(e.appConfig),i);a=await t.json()}catch(e){throw $.create("token-subscribe-failed",{errorInfo:e?.toString()})}if(a.error){const e=a.error.message;throw $.create("token-subscribe-failed",{errorInfo:e})}if(!a.token)throw $.create("token-subscribe-no-token");return a.token}(e,t),r={token:n,createTime:Date.now(),subscriptionOptions:t};return await dbSet(e,r),r.token}async function removeFidRegistrationBestEffort(e){try{await dbRemoveFidRegistration(e)}catch{}}async function registerDefaultSw(e){try{e.swRegistration=await navigator.serviceWorker.register("/firebase-messaging-sw.js",{scope:"/firebase-cloud-messaging-push-scope"}),e.swRegistration.update().catch((()=>{})),await async function waitForRegistrationActive(e){return new Promise(((t,n)=>{const r=setTimeout((()=>n(new Error("Service worker not registered after 10000 ms"))),M),i=e.installing||e.waiting;e.active?(clearTimeout(r),t()):i?i.onstatechange=e=>{"activated"===e.target?.state&&(i.onstatechange=null,clearTimeout(r),t())}:(clearTimeout(r),n(new Error("No incoming service worker found.")))}))}(e.swRegistration)}catch(e){throw $.create("failed-service-worker-registration",{browserErrorMessage:e?.message})}}async function updateSwReg(e,t){if(t||e.swRegistration||await registerDefaultSw(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw $.create("invalid-sw-registration");e.swRegistration=t}}async function updateVapidKey(e,t){t?e.vapidKey=t:e.vapidKey||(e.vapidKey=E)}async function registerFcmRegistrationWithFid(e,t){const n=await async function getPushSubscription(e,t){const n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:base64ToArray(t)})}(e.swRegistration,e.vapidKey),r={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:n.endpoint,auth:arrayToBase64(n.getKey("auth")),p256dh:arrayToBase64(n.getKey("p256dh"))},i=e.firebaseDependencies.installations;for(let n=0;n<3;n++){const{responseFid:a}=await requestCreateRegistration(e.firebaseDependencies,r);if(a===t)return;n<2&&await i.getToken(!0)}throw $.create("fid-registration-failed",{errorInfo:"CreateRegistration response FID does not match Firebase Installation ID"})}async function register$1(e,t){if(!navigator)throw $.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw $.create("permission-blocked");if(!e.onRegisteredHandler)throw $.create("invalid-on-registered-handler");await updateVapidKey(e,t?.vapidKey),await updateSwReg(e,t?.serviceWorkerRegistration);const n=e._registerNotifyChain.catch((()=>{}));return e._registerNotifyChain=n.then((async()=>{const t=await e.firebaseDependencies.installations.getId(),n=await dbGetFidRegistration(e.firebaseDependencies),r=Date.now();(!n||n.fid!==t||r>=n.lastRegisterTime+6048e5)&&(await registerFcmRegistrationWithFid(e,t),await async function dbSetFidRegistration(e,t){const n=getKey(e),r=await getDbPromise();assertFidRegistrationObjectStore(r);const i=r.transaction([j,x],"readwrite");return await i.objectStore(x).put(t,n),await i.objectStore(j).delete(n),await i.done,t}(e.firebaseDependencies,{fid:t,lastRegisterTime:r,vapidKey:e.vapidKey}));if(!e.onRegisteredHandler)throw $.create("invalid-on-registered-handler");!function notifyOnRegistered(e,t){const n=e.onRegisteredHandler;n&&("function"==typeof n?n(t):n.next(t))}(e,t)})),e._registerNotifyChain}function externalizePayload(e){const t={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return function propagateNotificationPayload(e,t){if(!t.notification)return;e.notification={};const n=t.notification.title;n&&(e.notification.title=n);const r=t.notification.body;r&&(e.notification.body=r);const i=t.notification.image;i&&(e.notification.image=i);const a=t.notification.icon;a&&(e.notification.icon=a)}(t,e),function propagateDataPayload(e,t){if(!t.data)return;e.data=t.data}(t,e),function propagateFcmOptions(e,t){if(!t.fcmOptions&&!t.notification?.click_action)return;e.fcmOptions={};const n=t.fcmOptions?.link??t.notification?.click_action;n&&(e.fcmOptions.link=n);const r=t.fcmOptions?.analytics_label;r&&(e.fcmOptions.analyticsLabel=r)}(t,e),t}function getMissingValueError(e){return $.create("missing-app-config-values",{valueName:e})}!function _mergeStrings(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class MessagingService{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.onRegisteredHandler=null,this.onUnregisteredHandler=null,this._registerNotifyChain=Promise.resolve(),this._fidChangeUnsubscribe=null,this.logEvents=[],this.logQueue={state:"stopped"};const r=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration Object");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId","messagingSenderId"],{options:n}=e;for(const e of t)if(!n[e])throw getMissingValueError(e);return{appName:e.name,projectId:n.projectId,apiKey:n.apiKey,appId:n.appId,senderId:n.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return this._fidChangeUnsubscribe&&(this._fidChangeUnsubscribe(),this._fidChangeUnsubscribe=null),"scheduled"===this.logQueue.state&&clearTimeout(this.logQueue.timerId),this.logQueue={state:"stopped"},Promise.resolve()}}async function getToken$1(e,t){if(!navigator)throw $.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw $.create("permission-blocked");return await updateVapidKey(e,t?.vapidKey),await updateSwReg(e,t?.serviceWorkerRegistration),getTokenInternal(e)}async function logToScion(e,t,n){const r=function getEventType(e){switch(e){case A.NOTIFICATION_CLICKED:return"notification_open";case A.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);(await e.firebaseDependencies.analyticsProvider.get()).logEvent(r,{message_id:n[F],message_name:n["google.c.a.c_l"],message_time:n["google.c.a.ts"],message_device_time:Math.floor(Date.now()/1e3)})}async function messageEventListener(e,t){const n=t.data;if(!n.isFirebaseMessaging)return;if(e.onMessageHandler&&n.messageType===A.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(externalizePayload(n)):e.onMessageHandler.next(externalizePayload(n))),e.onRegisteredHandler&&n.messageType===A.FID_REGISTERED){const t=n.fid;"function"==typeof e.onRegisteredHandler?e.onRegisteredHandler(t):e.onRegisteredHandler.next(t)}const r=n.data;(function isConsoleMessage(e){return"object"==typeof e&&!!e&&F in e})(r)&&"1"===r["google.c.a.e"]&&await logToScion(e,n.messageType,r)}const WindowMessagingFactory=e=>{const t=new MessagingService(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",(e=>messageEventListener(t,e))),t._fidChangeUnsubscribe=function subscribeFidChangeRegistration(e,t){return onIdChange(t,(()=>{(async()=>{e.onRegisteredHandler&&await dbGetFidRegistration(e.firebaseDependencies)&&await register$1(e).catch((()=>{}))})()}))}(t,e.getProvider("installations").getImmediate()),t},WindowMessagingInternalFactory=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>getToken$1(t,e),register:e=>register$1(t,e)}};async function isWindowSupported(){try{await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{t(i.error?.message||"")}}catch(e){t(e)}}))}()}catch(e){return!1}return"undefined"!=typeof window&&function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}()&&function areCookiesEnabled(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}function getMessagingInWindow(e=n()){return isWindowSupported().then((e=>{if(!e)throw $.create("unsupported-browser")}),(e=>{throw $.create("indexed-db-unsupported")})),_getProvider(getModularInstance(e),"messaging").getImmediate()}async function getToken(e,t){return getToken$1(e=getModularInstance(e),t)}function deleteToken(e){return async function deleteToken$1(e){if(!navigator)throw $.create("only-available-in-window");return e.swRegistration||await registerDefaultSw(e),revokeRegistrationInternal(e)}(e=getModularInstance(e))}function onMessage(e,t){return function onMessage$1(e,t){if(!navigator)throw $.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=getModularInstance(e),t)}async function register(e,t){return register$1(e=getModularInstance(e),t)}async function unregister(e){return async function unregister$1(e){if(!navigator)throw $.create("only-available-in-window");const t=await dbGetFidRegistration(e.firebaseDependencies).catch((()=>{})),n=t?.fid??await e.firebaseDependencies.installations.getId();await requestDeleteRegistration(e.firebaseDependencies,n);try{await dbRemoveFidRegistration(e.firebaseDependencies)}catch{}try{await dbRemove(e.firebaseDependencies)}catch{}const r=e.onUnregisteredHandler;r&&("function"==typeof r?r(n):r.next(n))}(e=getModularInstance(e))}function onRegistered(e,t){return function onRegistered$1(e,t){return e.onRegisteredHandler=t,()=>{e.onRegisteredHandler===t&&(e.onRegisteredHandler=null)}}(e=getModularInstance(e),t)}function onUnregistered(e,t){return function onUnregistered$1(e,t){return e.onUnregisteredHandler=t,()=>{e.onUnregisteredHandler===t&&(e.onUnregisteredHandler=null)}}(e=getModularInstance(e),t)}!function registerMessagingInWindow(){t(new Component("messaging",WindowMessagingFactory,"PUBLIC")),t(new Component("messaging-internal",WindowMessagingInternalFactory,"PRIVATE")),e(q,H),e(q,H,"esm2020")}();export{deleteToken,getMessagingInWindow as getMessaging,getToken,isWindowSupported as isSupported,onMessage,onRegistered,onUnregistered,register,unregister};
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(at,it){try{!(function(){function N(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function a(e,t){if(!e)throw e=t,new Error("Firebase Database ("+O.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)}let B=N(at),O={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};function d(){try{return"object"==typeof indexedDB}catch(e){}}class n extends Error{constructor(e,t,a){super(t),this.code=e,this.customData=a,this.name="FirebaseError",Object.setPrototypeOf(this,n.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,i.prototype.create)}}class i{constructor(e,t,a){this.service=e,this.serviceName=t,this.errors=a}create(e,...t){var i,a=t[0]||{},s=this.service+"/"+e,r=this.errors[e],r=r?(i=a,r.replace(H,(e,t)=>{var a=i[t];return null!=a?String(a):`<${t}?>`})):"Error",r=this.serviceName+`: ${r} (${s}).`;return new n(s,r,a)}}let H=/\{\$([^}]+)}/g;function o(e,t=1e3,a=2){var i=t*Math.pow(a,e),s=Math.round(.5*i*(Math.random()-.5)*2);return Math.min(144e5,i+s)}function r(e){return e&&e._delegate?e._delegate:e}class e{constructor(e,t,a){this.name=e,this.instanceFactory=t,this.type=a,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var f,s;(w=f=f||{})[w.DEBUG=0]="DEBUG",w[w.VERBOSE=1]="VERBOSE",w[w.INFO=2]="INFO",w[w.WARN=3]="WARN",w[w.ERROR=4]="ERROR",w[w.SILENT=5]="SILENT";let j={debug:f.DEBUG,verbose:f.VERBOSE,info:f.INFO,warn:f.WARN,error:f.ERROR,silent:f.SILENT},V=f.INFO,$={[f.DEBUG]:"log",[f.VERBOSE]:"log",[f.INFO]:"info",[f.WARN]:"warn",[f.ERROR]:"error"},U=(e,t,...a)=>{if(!(t<e.logLevel)){var i=(new Date).toISOString(),s=$[t];if(!s)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[s](`[${i}] ${e.name}:`,...a)}};class K{constructor(e){this.name=e,this._logLevel=V,this._logHandler=U,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in f))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?j[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,f.DEBUG,...e),this._logHandler(this,f.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,f.VERBOSE,...e),this._logHandler(this,f.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,f.INFO,...e),this._logHandler(this,f.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,f.WARN,...e),this._logHandler(this,f.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,f.ERROR,...e),this._logHandler(this,f.ERROR,...e)}}let q=(t,e)=>e.some(e=>t instanceof e),c,W;let z=new WeakMap,l=new WeakMap,G=new WeakMap,g=new WeakMap,h=new WeakMap;let u={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return l.get(e);if("objectStoreNames"===t)return e.objectStoreNames||G.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return p(e[t])},set(e,t,a){return e[t]=a,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function J(i){return i!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(W=W||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(i)?function(...e){return i.apply(m(this),e),p(z.get(this))}:function(...e){return p(i.apply(m(this),e))}:function(e,...t){var a=i.call(m(this),e,...t);return G.set(a,e.sort?e.sort():[e]),p(a)}}function X(e){var r,t;return"function"==typeof e?J(e):(e instanceof IDBTransaction&&(r=e,l.has(r)||(t=new Promise((e,t)=>{let a=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",s),r.removeEventListener("abort",s)},i=()=>{e(),a()},s=()=>{t(r.error||new DOMException("AbortError","AbortError")),a()};r.addEventListener("complete",i),r.addEventListener("error",s),r.addEventListener("abort",s)}),l.set(r,t))),q(e,c=c||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,u):e)}function p(e){var r,t;return e instanceof IDBRequest?(r=e,(t=new Promise((e,t)=>{let a=()=>{r.removeEventListener("success",i),r.removeEventListener("error",s)},i=()=>{e(p(r.result)),a()},s=()=>{t(r.error),a()};r.addEventListener("success",i),r.addEventListener("error",s)})).then(e=>{e instanceof IDBCursor&&z.set(e,r)}).catch(()=>{}),h.set(t,r),t):g.has(e)?g.get(e):((t=X(e))!==e&&(g.set(e,t),h.set(t,e)),t)}let m=e=>h.get(e);let Y=["get","getKey","getAll","getAllKeys","count"],Z=["put","add","delete","clear"],v=new Map;function Q(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(v.get(t))return v.get(t);let s=t.replace(/FromIndex$/,""),r=t!==s,n=Z.includes(s);var a;return s in(r?IDBIndex:IDBObjectStore).prototype&&(n||Y.includes(s))?(a=async function(e,...t){var a=this.transaction(e,n?"readwrite":"readonly");let i=a.store;return r&&(i=i.index(t.shift())),(await Promise.all([i[s](...t),n&&a.done]))[0]},v.set(t,a),a):void 0}}u={...s=u,get:(e,t,a)=>Q(e,t)||s.get(e,t,a),has:(e,t)=>!!Q(e,t)||s.has(e,t)};var ee="@firebase/installations",t="0.6.22";let te=1e4,ae="w:"+t,ie="FIS_v2",se="https://firebaseinstallations.googleapis.com/v1",re=36e5;var w;let y=new i("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function ne(e){return e instanceof n&&e.code.includes("request-failed")}function oe({projectId:e}){return se+`/projects/${e}/installations`}function ce(e){return{token:e.token,requestStatus:2,expiresIn:Number(e.expiresIn.replace("s","000")),creationTime:Date.now()}}async function le(e,t){var a=(await t.json()).error;return y.create("request-failed",{requestName:e,serverCode:a.code,serverMessage:a.message,serverStatus:a.status})}function ge({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function he(e,{refreshToken:t}){var a=ge(e);return a.append("Authorization",(e=t,ie+" "+e)),a}async function ue(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function de(t){return new Promise(e=>{setTimeout(e,t)})}let fe=/^[cdef][\w-]{21}$/,b="";function pe(){try{var e=new Uint8Array(17),t=((self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16,(e=>btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_"))(e).substr(0,22));return fe.test(t)?t:b}catch{return b}}function E(e){return e.appName+"!"+e.appId}let me=new Map;function ve(e,t){var a=E(e),e=(we(a,t),a),a=(()=>(!C&&"BroadcastChannel"in self&&((C=new BroadcastChannel("[Firebase] FID Change")).onmessage=e=>{we(e.data.key,e.data.fid)}),C))();a&&a.postMessage({key:e,fid:t}),0===me.size&&C&&(C.close(),C=null)}function we(e,t){var a=me.get(e);if(a)for(var i of a)i(t)}let C=null;let ye="firebase-installations-database",be=1,_="firebase-installations-store",Ee=null;function S(){return Ee=Ee||((e,t,{blocked:a,upgrade:i,blocking:s,terminated:r})=>{let n=indexedDB.open(e,t);var o=p(n);return i&&n.addEventListener("upgradeneeded",e=>{i(p(n.result),e.oldVersion,e.newVersion,p(n.transaction),e)}),a&&n.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),o.then(e=>{r&&e.addEventListener("close",()=>r()),s&&e.addEventListener("versionchange",e=>s(e.oldVersion,e.newVersion,e))}).catch(()=>{}),o})(ye,be,{upgrade:(e,t)=>{0===t&&e.createObjectStore(_)}})}async function I(e,t){var a=E(e),i=(await S()).transaction(_,"readwrite"),s=i.objectStore(_),r=await s.get(a);return await s.put(t,a),await i.done,r&&r.fid===t.fid||ve(e,t.fid),t}async function Ce(e){var t=E(e),a=(await S()).transaction(_,"readwrite");await a.objectStore(_).delete(t),await a.done}async function T(e,t){var a=E(e),i=(await S()).transaction(_,"readwrite"),s=i.objectStore(_),r=await s.get(a),n=t(r);return void 0===n?await s.delete(a):await s.put(n,a),await i.done,!n||r&&r.fid===n.fid||ve(e,n.fid),n}async function k(a){let i;var e=await T(a.appConfig,e=>{var t=Se(e||{fid:pe(),registrationStatus:0}),t=((e,t)=>{var a,i;return 0===t.registrationStatus?navigator.onLine?(a={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},i=(async(t,a)=>{try{var e=await(async({appConfig:e,heartbeatServiceProvider:t},{fid:a})=>{let i=oe(e);var s=ge(e),r=((r=t.getImmediate({optional:!0}))&&(r=await r.getHeartbeatsHeader())&&s.append("x-firebase-client",r),{fid:a,authVersion:ie,appId:e.appId,sdkVersion:ae});let n={method:"POST",headers:s,body:JSON.stringify(r)};if((s=await ue(()=>fetch(i,n))).ok)return{fid:(r=await s.json()).fid||a,registrationStatus:2,refreshToken:r.refreshToken,authToken:ce(r.authToken)};throw await le("Create Installation",s)})(t,a);return I(t.appConfig,e)}catch(e){throw ne(e)&&409===e.customData.serverCode?await Ce(t.appConfig):await I(t.appConfig,{fid:a.fid,registrationStatus:0}),e}})(e,a),{installationEntry:a,registrationPromise:i}):(a=Promise.reject(y.create("app-offline")),{installationEntry:t,registrationPromise:a}):1===t.registrationStatus?{installationEntry:t,registrationPromise:(async e=>{let t=await _e(e.appConfig);for(;1===t.registrationStatus;)await de(100),t=await _e(e.appConfig);var a,i;return 0!==t.registrationStatus?t:({installationEntry:a,registrationPromise:i}=await k(e),i||a)})(e)}:{installationEntry:t}})(a,t);return i=t.registrationPromise,t.installationEntry});return e.fid===b?{installationEntry:await i}:{installationEntry:e,registrationPromise:i}}function _e(e){return T(e,e=>{if(e)return Se(e);throw y.create("installation-not-found")})}function Se(e){var t;return 1===(t=e).registrationStatus&&t.registrationTime+te<Date.now()?{fid:e.fid,registrationStatus:0}:e}async function Ie({appConfig:e,heartbeatServiceProvider:t},a){[s,r]=[e,a.fid];let i=oe(s)+`/${r}/authTokens:generate`;var s,r,n=he(e,a),o=t.getImmediate({optional:!0}),o=(o&&(o=await o.getHeartbeatsHeader())&&n.append("x-firebase-client",o),{installation:{sdkVersion:ae,appId:e.appId}});let c={method:"POST",headers:n,body:JSON.stringify(o)};n=await ue(()=>fetch(i,c));if(n.ok)return ce(await n.json());throw await le("Generate Auth Token",n)}async function R(i,s=!1){let r;var e=await T(i.appConfig,e=>{if(!ke(e))throw y.create("not-registered");var t,a=e.authToken;if(s||2!==(t=a).requestStatus||(e=>{var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+re})(t)){if(1===a.requestStatus)return r=(async(e,t)=>{let a=await Te(e.appConfig);for(;1===a.authToken.requestStatus;)await de(100),a=await Te(e.appConfig);var i=a.authToken;return 0===i.requestStatus?R(e,t):i})(i,s),e;if(navigator.onLine)return t=e,a={requestStatus:1,requestTime:Date.now()},a={...t,authToken:a},r=(async(t,a)=>{try{var e=await Ie(t,a),i={...a,authToken:e};return await I(t.appConfig,i),e}catch(e){var s;throw!ne(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(s={...a,authToken:{requestStatus:0}},await I(t.appConfig,s)):await Ce(t.appConfig),e}})(i,a),a;throw y.create("app-offline")}return e});return r?await r:e.authToken}function Te(e){return T(e,e=>{var t,a;if(ke(e))return t=e.authToken,1===(a=t).requestStatus&&a.requestTime+te<Date.now()?{...e,authToken:{requestStatus:0}}:e;throw y.create("not-registered")})}function ke(e){return void 0!==e&&2===e.registrationStatus}async function Re(e,t=!1){var a=e,i=(await(!(i=(await k(a)).registrationPromise)||!await i),await R(a,t));return i.token}function M(e){return y.create("missing-app-config-values",{valueName:e})}let Me="installations",Le=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:(e=>{if(!e||!e.options)throw M("App Configuration");if(!e.name)throw M("App Name");var t;for(t of["projectId","apiKey","appId"])if(!e.options[t])throw M(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}})(t),heartbeatServiceProvider:it._getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},Ae=e=>{var t=e.getProvider("app").getImmediate();let a=it._getProvider(t,Me).getImmediate();return{getId:()=>(async e=>{var t=e,{installationEntry:a,registrationPromise:i}=await k(t);return(i||R(t)).catch(console.error),a.fid})(a),getToken:e=>Re(a,e)}};it._registerComponent(new e(Me,Le,"PUBLIC")),it._registerComponent(new e("installations-internal",Ae,"PRIVATE")),it.registerVersion(ee,t),it.registerVersion(ee,t,"esm2020");let L="@firebase/remote-config";class Fe{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}let A=new i("remoteconfig","Remote Config",{"already-initialized":"Remote Config already initialized","registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported.","stream-error":"The stream was not able to connect to the backend: {$originalErrorMessage}.","realtime-unavailable":"The Realtime service is unavailable: {$originalErrorMessage}","update-message-invalid":"The stream invalidation message was unparsable: {$originalErrorMessage}","update-not-fetched":"Unable to fetch the latest config: {$originalErrorMessage}","analytics-unavailable":"Connection to Firebase Analytics failed: {$originalErrorMessage}"});let De=["1","true","t","yes","y","on"];class F{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=De.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return e=isNaN(e)?0:e}getSource(){return this._source}}class Pe{constructor(e){this.storage=e._storage,this.logger=e._logger,this.analyticsProvider=e._analyticsProvider}async updateActiveExperiments(e){var t=await this.storage.getActiveExperiments()||new Set,a=this.createExperimentInfoMap(e);return this.addActiveExperiments(a),this.removeInactiveExperiments(t,a),this.storage.setActiveExperiments(new Set(a.keys()))}createExperimentInfoMap(e){var t,a=new Map;for(t of e)a.set(t.experimentId,t);return a}addActiveExperiments(e){var t,a,i={};for([t,a]of e.entries())i["firebase"+t]=a.variantId;this.addExperimentToAnalytics(i)}removeInactiveExperiments(e,t){var a,i={};for(a of e)t.has(a)||(i["firebase"+a]=null);this.addExperimentToAnalytics(i)}addExperimentToAnalytics(e){if(0!==Object.keys(e).length)try{var t=this.analyticsProvider.getImmediate({optional:!0});t?(t.setUserProperties(e),t.logEvent("set_firebase_experiment_state")):this.logger.warn("Analytics import failed. Verify if you have imported Firebase Analytics in your app code.")}catch(e){throw A.create("analytics-unavailable",{originalErrorMessage:e?.message})}}}async function xe(e){var t=r(e),[a,i]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(a&&a.config&&a.eTag&&a.templateVersion&&a.eTag!==i)&&(i=new Pe(t).updateActiveExperiments(a.experiments||[]),await Promise.all([t._storageCache.setActiveConfig(a.config),t._storage.setActiveConfigEtag(a.eTag),t._storage.setActiveConfigTemplateVersion(a.templateVersion),i]),!0)}function Ne(e){let t=r(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function Be(t){var a=r(t);let e=new Fe;setTimeout(async()=>{e.abort()},a.settings.fetchTimeoutMillis);var i,s=a._storageCache.getCustomSignals();s&&a._logger.debug("Fetching config with custom signals: "+JSON.stringify(s));try{await a._client.fetch({cacheMaxAgeMillis:a.settings.minimumFetchIntervalMillis,signal:e,customSignals:s}),await a._storageCache.setLastFetchStatus("success")}catch(e){t="fetch-throttle";s=(i=e)instanceof n&&-1!==i.code.indexOf(t)?"throttle":"failure";throw await a._storageCache.setLastFetchStatus(s),e}}function Oe(a){var e,t,i=r(a);return[e={},t={}]=[i._storageCache.getActiveConfig(),i.defaultConfig],Object.keys({...e,...t}).reduce((e,t)=>(e[t]=D(a,t),e),{})}function D(e,t){var a=r(e),i=(a._isInitializationComplete||a._logger.debug(`A value was requested for key "${t}" before SDK initialization completed.`+" Await on ensureInitialized if the intent was to get a previously activated value."),a._storageCache.getActiveConfig());return i&&void 0!==i[t]?new F("remote",i[t]):a.defaultConfig&&void 0!==a.defaultConfig[t]?new F("default",String(a.defaultConfig[t])):(a._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new F("static"))}class He{constructor(e,t,a,i){this.client=e,this.storage=t,this.storageCache=a,this.logger=i}isCachedDataFresh(e,t){var a;return t?(a=Date.now()-t,this.logger.debug("Config fetch cache check."+` Cache age millis: ${a}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${a=a<=e}.`),a):(this.logger.debug("Config fetch cache check. Cache unpopulated."),!1)}async fetch(e){var[t,a]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(a&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return a;e.eTag=a&&a.eTag;t=await this.client.fetch(e),a=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===t.status&&a.push(this.storage.setLastSuccessfulFetchResponse(t)),await Promise.all(a),t}}class je{constructor(e,t,a,i,s,r){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=a,this.projectId=i,this.apiKey=s,this.appId=r}async fetch(a){var e,[t,i]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),s=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=`+this.apiKey,r={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":a.eTag||"*"},t={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:i,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language,custom_signals:a.customSignals},i={method:"POST",headers:r,body:JSON.stringify(t)},r=fetch(s,i),t=new Promise((e,t)=>{a.signal.addEventListener(()=>{var e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let n;try{await Promise.race([r,t]),n=await r}catch(e){let t="fetch-client-network";throw"AbortError"===e?.name&&(t="fetch-timeout"),A.create(t,{originalErrorMessage:e?.message})}let o=n.status;s=n.headers.get("ETag")||void 0;let c,l,g,h;if(200===n.status){let e;try{e=await n.json()}catch(e){throw A.create("fetch-client-parse",{originalErrorMessage:e?.message})}c=e.entries,l=e.state,g=e.templateVersion,h=e.experimentDescriptions}if("INSTANCE_STATE_UNSPECIFIED"===l?o=500:"NO_CHANGE"===l?o=304:"NO_TEMPLATE"!==l&&"EMPTY_CONFIG"!==l||(c={},h=[]),304!==o&&200!==o)throw A.create("fetch-status",{httpStatus:o});return{status:o,eTag:s,config:c,templateVersion:g,experiments:h}}}class Ve{constructor(e,t){this.client=e,this.storage=t}async fetch(e){var t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(t,{throttleEndTimeMillis:e,backoffCount:a}){var s,r;s=t.signal,r=e,await new Promise((e,t)=>{var a=Math.max(r-Date.now(),0);let i=setTimeout(e,a);s.addEventListener(()=>{clearTimeout(i),t(A.create("fetch-throttle",{throttleEndTimeMillis:r}))})});try{var i=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),i}catch(e){if((e=>{var t;return e instanceof n&&e.customData&&(429===(t=Number(e.customData.httpStatus))||500===t||503===t||504===t)})(e))return i={throttleEndTimeMillis:Date.now()+o(a),backoffCount:a+1},await this.storage.setThrottleMetadata(i),this.attemptFetch(t,i);throw e}}}class $e{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,a,i,s,r,n){this.app=e,this._client=t,this._storageCache=a,this._storage=i,this._logger=s,this._realtimeHandler=r,this._analyticsProvider=n,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function P(e,t){var a=e.target.error||void 0;return A.create(t,{originalErrorMessage:a&&a?.message})}let x="app_namespace_store";class Ue{getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getActiveExperiments(){return this.get("active_experiments")}setActiveExperiments(e){return this.set("active_experiments",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}getCustomSignals(){return this.get("custom_signals")}getRealtimeBackoffMetadata(){return this.get("realtime_backoff_metadata")}setRealtimeBackoffMetadata(e){return this.set("realtime_backoff_metadata",e)}getActiveConfigTemplateVersion(){return this.get("last_known_template_version")}setActiveConfigTemplateVersion(e){return this.set("last_known_template_version",e)}}class Ke extends Ue{constructor(e,t,a,i=(()=>new Promise((t,a)=>{try{var e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{a(P(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{var t=e.target.result;0===e.oldVersion&&t.createObjectStore(x,{keyPath:"compositeKey"})}}catch(e){a(A.create("storage-open",{originalErrorMessage:e?.message}))}}))()){super(),this.appId=e,this.appName=t,this.namespace=a,this.openDbPromise=i}async setCustomSignals(e){var t=(await this.openDbPromise).transaction([x],"readwrite"),a=We(e,await this.getWithTransaction("custom_signals",t)||{});return await this.setWithTransaction("custom_signals",a,t),a}async getWithTransaction(r,n){return new Promise((a,t)=>{var e=n.objectStore(x),i=this.createCompositeKey(r);try{var s=e.get(i);s.onerror=e=>{t(P(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;a(t?t.value:void 0)}}catch(e){t(A.create("storage-get",{originalErrorMessage:e?.message}))}})}async setWithTransaction(r,n,o){return new Promise((e,t)=>{var a=o.objectStore(x),i=this.createCompositeKey(r);try{var s=a.put({compositeKey:i,value:n});s.onerror=e=>{t(P(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(A.create("storage-set",{originalErrorMessage:e?.message}))}})}async get(e){var t=(await this.openDbPromise).transaction([x],"readonly");return this.getWithTransaction(e,t)}async set(e,t){var a=(await this.openDbPromise).transaction([x],"readwrite");return this.setWithTransaction(e,t,a)}async delete(r){let n=await this.openDbPromise;return new Promise((e,t)=>{var a=n.transaction([x],"readwrite").objectStore(x),i=this.createCompositeKey(r);try{var s=a.delete(i);s.onerror=e=>{t(P(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(A.create("storage-delete",{originalErrorMessage:e?.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class qe extends Ue{constructor(){super(...arguments),this.storage={}}async get(e){return Promise.resolve(this.storage[e])}async set(e,t){return this.storage[e]=t,Promise.resolve(void 0)}async delete(e){return this.storage[e]=void 0,Promise.resolve()}async setCustomSignals(e){var t=this.storage.custom_signals||{};return this.storage.custom_signals=We(e,t),Promise.resolve(this.storage.custom_signals)}}function We(e,t){var a={...t,...e},a=Object.fromEntries(Object.entries(a).filter(([,e])=>null!==e).map(([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t]));if(100<Object.keys(a).length)throw A.create("custom-signal-max-allowed-signals",{maxSignals:100});return a}class ze{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),a=this.storage.getActiveConfig(),i=this.storage.getCustomSignals(),e=await e,e=(e&&(this.lastFetchStatus=e),await t),t=(e&&(this.lastSuccessfulFetchTimestampMillis=e),await a),e=(t&&(this.activeConfig=t),await i);e&&(this.customSignals=e)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}class Ge extends class{constructor(e){this.allowedEvents_=e,this.listeners_={},a(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...a){if(Array.isArray(this.listeners_[t])){var i=[...this.listeners_[t]];for(let e=0;e<i.length;e++)i[e].callback.apply(i[e].context,a)}}on(e,t,a){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:a});var i=this.getInitialEvent(e);i&&t.apply(a,i)}off(e,t,a){this.validateEventType_(e);var i=this.listeners_[e]||[];for(let s=0;s<i.length;s++)if(i[s].callback===t&&(!a||a===i[s].context))return void i.splice(s,1)}validateEventType_(t){a(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}{static getInstance(){return new Ge}constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}getInitialEvent(e){return a("visible"===e,"Unknown event type: "+e),[this.visible_]}}let Je="featureDisabled",Xe="retryIntervalSeconds",Ye="latestTemplateVersionNumber";class Ze{constructor(e,t,a,i,s,r,n,o,c,l){this.firebaseInstallations=e,this.storage=t,this.sdkVersion=a,this.namespace=i,this.projectId=s,this.apiKey=r,this.appId=n,this.logger=o,this.storageCache=c,this.cachingClient=l,this.observers=new Set,this.isConnectionActive=!1,this.isRealtimeDisabled=!1,this.httpRetriesRemaining=8,this.isInBackground=!1,this.decoder=new TextDecoder("utf-8"),this.isClosingConnection=!1,this.propagateError=t=>this.observers.forEach(e=>e.error?.(t)),this.isStatusCodeRetryable=e=>!e||[408,429,502,503,504].includes(e),this.setRetriesRemaining(),Ge.getInstance().on("visible",this.onVisibilityChange,this)}async setRetriesRemaining(){var e=(await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams||0;this.httpRetriesRemaining=Math.max(8-e,1)}async updateBackoffMetadataWithLastFailedStreamConnectionTime(e){var t=((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams||0)+1,a=o(t,6e4,2);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(e.getTime()+a),numFailedStreams:t})}async updateBackoffMetadataWithRetryInterval(e){var t=Date.now(),t=new Date(t+1e3*e);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:t,numFailedStreams:0}),await this.retryHttpConnectionWhenBackoffEnds()}async closeRealtimeHttpConnection(){if(!this.isClosingConnection){this.isClosingConnection=!0;try{this.reader&&await this.reader.cancel()}catch(e){this.logger.debug("Failed to cancel the reader, connection was lost.")}finally{this.reader=void 0}this.controller&&(await this.controller.abort(),this.controller=void 0),this.isClosingConnection=!1}}async resetRealtimeBackoff(){await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(-1),numFailedStreams:0})}resetRetryCount(){this.httpRetriesRemaining=8}async establishRealtimeConnection(e,t,a,i){var s=await this.storage.getActiveConfigEtag(),r=await this.storage.getActiveConfigTemplateVersion(),s={"X-Goog-Api-Key":this.apiKey,"X-Goog-Firebase-Installations-Auth":a,"Content-Type":"application/json",Accept:"application/json","If-None-Match":s||"*","Content-Encoding":"gzip"},r={project:this.projectId,namespace:this.namespace,lastKnownVersionNumber:r,appId:this.appId,sdkVersion:this.sdkVersion,appInstanceId:t};return await fetch(e,{method:"POST",headers:s,body:JSON.stringify(r),signal:i})}getRealtimeUrl(){var e=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfigrealtime.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=`+this.apiKey;return new URL(e)}async createRealtimeConnection(){var[e,t]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken(!1)]),a=(this.controller=new AbortController,this.getRealtimeUrl());return await this.establishRealtimeConnection(a,e,t,this.controller.signal)}async retryHttpConnectionWhenBackoffEnds(){let e=await this.storage.getRealtimeBackoffMetadata();e=e||{backoffEndTimeMillis:new Date(-1),numFailedStreams:0};var t=new Date(e.backoffEndTimeMillis).getTime(),a=Date.now(),t=Math.max(0,t-a);await this.makeRealtimeHttpConnection(t)}setIsHttpConnectionRunning(e){this.isConnectionActive=e}checkAndSetHttpConnectionFlagIfNotRunning(){var e=this.canEstablishStreamConnection();return e&&this.setIsHttpConnectionRunning(!0),e}fetchResponseIsUpToDate(e,t){return null!=e.config&&e.templateVersion?e.templateVersion>=t:"success"===this.storageCache.getLastFetchStatus()}parseAndValidateConfigUpdateMessage(e){var t=e.indexOf("{"),a=e.indexOf("}",t);return t<0||a<0||a<=t?"":e.substring(t,a+1)}isEventListenersEmpty(){return 0===this.observers.size}getRandomInt(e){return Math.floor(Math.random()*e)}executeAllListenerCallbacks(t){this.observers.forEach(e=>e.next(t))}getChangedParams(e,t,a,i){var s,r,n,o,c=new Set,l=new Set(Object.keys(e||{})),g=new Set(Object.keys(t||{})),h=a.experiments||[],u=i?.experiments||[],d=this.createExperimentsMap(h),f=this.createExperimentsMap(u);for(s of l)g.has(s)&&e[s]===t[s]||c.add(s),d.has(s)!==f.has(s)?c.add(s):(r=d.get(s),n=f.get(s),r&&n&&!this.areExperimentsEqual(r,n)&&c.add(s));for(o of g)l.has(o)||c.add(o);return c}areExperimentsEqual(e,t){return e.experimentId===t.experimentId&&e.variantId===t.variantId&&e.timeToLiveMillis===t.timeToLiveMillis&&e.triggerTimeoutMillis===t.triggerTimeoutMillis}createExperimentsMap(e){var t,a=new Map;for(t of e)if(t.affectedParameterKeys&&!t.experimentId.startsWith("_exp_rollout"))for(var i of t.affectedParameterKeys)a.set(i,t);return a}async fetchLatestConfig(e,a){var i=e-1,s=3-i,r=this.storageCache.getCustomSignals(),n=(r&&this.logger.debug("Fetching config with custom signals: "+JSON.stringify(r)),new Fe);try{var o,c={cacheMaxAgeMillis:0,signal:n,customSignals:r,fetchType:"REALTIME",fetchAttempt:s},l=await this.storage.getLastSuccessfulFetchResponse(),g=await this.cachingClient.fetch(c);let t=await this.storage.getActiveConfig();if(this.fetchResponseIsUpToDate(g,a))if(null==g.config)this.logger.debug("The fetch succeeded, but the backend had no updates.");else{null==t&&(t={});let e=this.getChangedParams(g.config,t,g,l);0===e.size?this.logger.debug("Config was fetched, but no params changed."):(o={getUpdatedKeys(){return new Set(e)}},this.executeAllListenerCallbacks(o))}else this.logger.debug("Fetched template version is the same as SDK's current version. Retrying fetch."),await this.autoFetch(i,a)}catch(e){n=e instanceof Error?e.message:String(e),r=A.create("update-not-fetched",{originalErrorMessage:"Failed to auto-fetch config update: "+n});this.propagateError(r)}}async autoFetch(e,a){var t;if(0===e)t=A.create("update-not-fetched",{originalErrorMessage:"Unable to fetch the latest version of the template."}),this.propagateError(t);else{let t=1e3*this.getRandomInt(4);await new Promise(e=>setTimeout(e,t)),await this.fetchLatestConfig(e,a)}}async handleNotifications(e){let t="";for(;;){var{done:a,value:i}=await e.read();if(a)break;if(a=this.decoder.decode(i,{stream:!0}),t+=a,a.includes("}")&&0!==(t=this.parseAndValidateConfigUpdateMessage(t)).length){try{var s,r,n,o=JSON.parse(t);if(this.isEventListenersEmpty())break;if(Je in o&&!0===o[Je]){var c=A.create("realtime-unavailable",{originalErrorMessage:"The server is temporarily unavailable. Try again in a few minutes."});this.propagateError(c);break}Ye in o&&(s=await this.storage.getActiveConfigTemplateVersion(),r=Number(o[Ye]),s)&&s<r&&await this.autoFetch(3,r),Xe in o&&(n=Number(o[Xe]),await this.updateBackoffMetadataWithRetryInterval(n))}catch(e){this.logger.debug("Unable to parse latest config update message.",e);i=e instanceof Error?e.message:String(e);this.propagateError(A.create("update-message-invalid",{originalErrorMessage:i}))}t=""}}}async listenForNotifications(e){try{await this.handleNotifications(e)}catch(e){this.isInBackground||this.logger.debug("Real-time connection was closed due to an exception.")}}async prepareAndBeginRealtimeHttpStream(){if(this.checkAndSetHttpConnectionFlagIfNotRunning()){let e=await this.storage.getRealtimeBackoffMetadata();var a=(e=e||{backoffEndTimeMillis:new Date(-1),numFailedStreams:0}).backoffEndTimeMillis.getTime();if(Date.now()<a)await this.retryHttpConnectionWhenBackoffEnds();else{let e,t;try{e=await this.createRealtimeConnection(),t=e.status,e.ok&&e.body&&(this.resetRetryCount(),await this.resetRealtimeBackoff(),i=e.body.getReader(),this.reader=i,await this.listenForNotifications(i))}catch(e){this.isInBackground?this.resetRetryCount():this.logger.debug("Exception connecting to real-time RC backend. Retrying the connection...:",e)}finally{await this.closeRealtimeHttpConnection(),this.setIsHttpConnectionRunning(!1);var i,a=!this.isInBackground&&(void 0===t||this.isStatusCodeRetryable(t));a&&await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date),a||e?.ok?await this.retryHttpConnectionWhenBackoffEnds():(i="Unable to connect to the server. HTTP status code: "+t,a=A.create("stream-error",{originalErrorMessage:i}),this.propagateError(a))}}}}canEstablishStreamConnection(){var e=0<this.observers.size,t=!this.isRealtimeDisabled,a=!this.isConnectionActive,i=!this.isInBackground;return e&&t&&a&&i}async makeRealtimeHttpConnection(t){var e;this.canEstablishStreamConnection()&&(0<this.httpRetriesRemaining?(this.httpRetriesRemaining--,await new Promise(e=>setTimeout(e,t)),this.prepareAndBeginRealtimeHttpStream()):this.isInBackground||(e=A.create("stream-error",{originalErrorMessage:"Unable to connect to the server. Check your connection and try again."}),this.propagateError(e)))}async beginRealtime(){0<this.observers.size&&await this.makeRealtimeHttpConnection(0)}addObserver(e){this.observers.add(e),this.beginRealtime()}removeObserver(e){this.observers.has(e)&&this.observers.delete(e)}async onVisibilityChange(e){this.isInBackground=!e,e?await this.beginRealtime():await this.closeRealtimeHttpConnection()}}async function Qe(){if(!d())return!1;try{return await new Promise((i,s)=>{try{let e=!0,t="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(t);a.onsuccess=()=>{a.result.close(),e||self.indexedDB.deleteDatabase(t),i(!0)},a.onupgradeneeded=()=>{e=!1},a.onerror=()=>{s(a.error?.message||"")}}catch(e){s(e)}})}catch(e){return!1}}it._registerComponent(new e("remote-config",function(e,{options:t}){var a=e.getProvider("app").getImmediate(),i=e.getProvider("installations-internal").getImmediate(),s=e.getProvider("analytics-internal"),{projectId:r,apiKey:n,appId:o}=a.options;if(!r)throw A.create("registration-project-id");if(!n)throw A.create("registration-api-key");if(!o)throw A.create("registration-app-id");var c=t?.templateId||"firebase",l=d()?new Ke(o,a.name,c):new qe,g=new ze(l),h=new K(L),u=(h.logLevel=f.ERROR,new je(i,it.SDK_VERSION,c,r,n,o)),u=new Ve(u,l),u=new He(u,l,g,h),i=new Ze(i,l,it.SDK_VERSION,c,r,n,o,h,g,u),c=new $e(a,u,g,l,h,i,s);return Ne(c),c},"PUBLIC").setMultipleInstances(!0)),it.registerVersion(L,"0.8.5"),it.registerVersion(L,"0.8.5","esm2020");class et{constructor(e,t){this.app=e,this._delegate=t}get defaultConfig(){return this._delegate.defaultConfig}set defaultConfig(e){this._delegate.defaultConfig=e}get fetchTimeMillis(){return this._delegate.fetchTimeMillis}get lastFetchStatus(){return this._delegate.lastFetchStatus}get settings(){return this._delegate.settings}set settings(e){this._delegate.settings=e}activate(){return xe(this._delegate)}ensureInitialized(){return Ne(this._delegate)}fetch(){return Be(this._delegate)}fetchAndActivate(){return(async e=>(await Be(e=r(e)),xe(e)))(this._delegate)}getAll(){return Oe(this._delegate)}getBoolean(e){return D(r(this._delegate),e).asBoolean()}getNumber(e){return D(r(this._delegate),e).asNumber()}getString(e){return D(r(this._delegate),e).asString()}getValue(e){return D(this._delegate,e)}setLogLevel(e){var t=this._delegate,a=r(t);switch(e){case"debug":a._logger.logLevel=f.DEBUG;break;case"silent":a._logger.logLevel=f.SILENT;break;default:a._logger.logLevel=f.ERROR}}}function tt(e,{instanceIdentifier:t}){var a=e.getProvider("app-compat").getImmediate(),i=e.getProvider("remote-config").getImmediate({identifier:t});return new et(a,i)}(w=B.default).INTERNAL.registerComponent(new e("remoteConfig-compat",tt,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:Qe})),w.registerVersion("@firebase/remote-config-compat","0.2.26")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-remote-config-compat.js - be sure to load firebase-app.js first.")}});
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(at,it){try{!(function(){function N(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function a(e,t){if(!e)throw e=t,new Error("Firebase Database ("+O.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)}let B=N(at),O={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};function d(){try{return"object"==typeof indexedDB}catch(e){}}class n extends Error{constructor(e,t,a){super(t),this.code=e,this.customData=a,this.name="FirebaseError",Object.setPrototypeOf(this,n.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,i.prototype.create)}}class i{constructor(e,t,a){this.service=e,this.serviceName=t,this.errors=a}create(e,...t){var i,a=t[0]||{},s=this.service+"/"+e,r=this.errors[e],r=r?(i=a,r.replace(H,(e,t)=>{var a=i[t];return null!=a?String(a):`<${t}?>`})):"Error",r=this.serviceName+`: ${r} (${s}).`;return new n(s,r,a)}}let H=/\{\$([^}]+)}/g;function o(e,t=1e3,a=2){var i=t*Math.pow(a,e),s=Math.round(.5*i*(Math.random()-.5)*2);return Math.min(144e5,i+s)}function r(e){return e&&e._delegate?e._delegate:e}class e{constructor(e,t,a){this.name=e,this.instanceFactory=t,this.type=a,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var f,s;(w=f=f||{})[w.DEBUG=0]="DEBUG",w[w.VERBOSE=1]="VERBOSE",w[w.INFO=2]="INFO",w[w.WARN=3]="WARN",w[w.ERROR=4]="ERROR",w[w.SILENT=5]="SILENT";let j={debug:f.DEBUG,verbose:f.VERBOSE,info:f.INFO,warn:f.WARN,error:f.ERROR,silent:f.SILENT},V=f.INFO,$={[f.DEBUG]:"log",[f.VERBOSE]:"log",[f.INFO]:"info",[f.WARN]:"warn",[f.ERROR]:"error"},U=(e,t,...a)=>{if(!(t<e.logLevel)){var i=(new Date).toISOString(),s=$[t];if(!s)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[s](`[${i}] ${e.name}:`,...a)}};class K{constructor(e){this.name=e,this._logLevel=V,this._logHandler=U,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in f))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?j[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,f.DEBUG,...e),this._logHandler(this,f.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,f.VERBOSE,...e),this._logHandler(this,f.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,f.INFO,...e),this._logHandler(this,f.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,f.WARN,...e),this._logHandler(this,f.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,f.ERROR,...e),this._logHandler(this,f.ERROR,...e)}}let q=(t,e)=>e.some(e=>t instanceof e),c,W;let z=new WeakMap,l=new WeakMap,G=new WeakMap,g=new WeakMap,h=new WeakMap;let u={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return l.get(e);if("objectStoreNames"===t)return e.objectStoreNames||G.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return p(e[t])},set(e,t,a){return e[t]=a,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function J(i){return i!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(W=W||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(i)?function(...e){return i.apply(m(this),e),p(z.get(this))}:function(...e){return p(i.apply(m(this),e))}:function(e,...t){var a=i.call(m(this),e,...t);return G.set(a,e.sort?e.sort():[e]),p(a)}}function X(e){var r,t;return"function"==typeof e?J(e):(e instanceof IDBTransaction&&(r=e,l.has(r)||(t=new Promise((e,t)=>{let a=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",s),r.removeEventListener("abort",s)},i=()=>{e(),a()},s=()=>{t(r.error||new DOMException("AbortError","AbortError")),a()};r.addEventListener("complete",i),r.addEventListener("error",s),r.addEventListener("abort",s)}),l.set(r,t))),q(e,c=c||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,u):e)}function p(e){var r,t;return e instanceof IDBRequest?(r=e,(t=new Promise((e,t)=>{let a=()=>{r.removeEventListener("success",i),r.removeEventListener("error",s)},i=()=>{e(p(r.result)),a()},s=()=>{t(r.error),a()};r.addEventListener("success",i),r.addEventListener("error",s)})).then(e=>{e instanceof IDBCursor&&z.set(e,r)}).catch(()=>{}),h.set(t,r),t):g.has(e)?g.get(e):((t=X(e))!==e&&(g.set(e,t),h.set(t,e)),t)}let m=e=>h.get(e);let Y=["get","getKey","getAll","getAllKeys","count"],Z=["put","add","delete","clear"],v=new Map;function Q(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(v.get(t))return v.get(t);let s=t.replace(/FromIndex$/,""),r=t!==s,n=Z.includes(s);var a;return s in(r?IDBIndex:IDBObjectStore).prototype&&(n||Y.includes(s))?(a=async function(e,...t){var a=this.transaction(e,n?"readwrite":"readonly");let i=a.store;return r&&(i=i.index(t.shift())),(await Promise.all([i[s](...t),n&&a.done]))[0]},v.set(t,a),a):void 0}}u={...s=u,get:(e,t,a)=>Q(e,t)||s.get(e,t,a),has:(e,t)=>!!Q(e,t)||s.has(e,t)};var ee="@firebase/installations",t="0.6.22";let te=1e4,ae="w:"+t,ie="FIS_v2",se="https://firebaseinstallations.googleapis.com/v1",re=36e5;var w;let y=new i("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function ne(e){return e instanceof n&&e.code.includes("request-failed")}function oe({projectId:e}){return se+`/projects/${e}/installations`}function ce(e){return{token:e.token,requestStatus:2,expiresIn:Number(e.expiresIn.replace("s","000")),creationTime:Date.now()}}async function le(e,t){var a=(await t.json()).error;return y.create("request-failed",{requestName:e,serverCode:a.code,serverMessage:a.message,serverStatus:a.status})}function ge({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function he(e,{refreshToken:t}){var a=ge(e);return a.append("Authorization",(e=t,ie+" "+e)),a}async function ue(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function de(t){return new Promise(e=>{setTimeout(e,t)})}let fe=/^[cdef][\w-]{21}$/,b="";function pe(){try{var e=new Uint8Array(17),t=((self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16,(e=>btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_"))(e).substr(0,22));return fe.test(t)?t:b}catch{return b}}function E(e){return e.appName+"!"+e.appId}let me=new Map;function ve(e,t){var a=E(e),e=(we(a,t),a),a=(()=>(!C&&"BroadcastChannel"in self&&((C=new BroadcastChannel("[Firebase] FID Change")).onmessage=e=>{we(e.data.key,e.data.fid)}),C))();a&&a.postMessage({key:e,fid:t}),0===me.size&&C&&(C.close(),C=null)}function we(e,t){var a=me.get(e);if(a)for(var i of a)i(t)}let C=null;let ye="firebase-installations-database",be=1,_="firebase-installations-store",Ee=null;function S(){return Ee=Ee||((e,t,{blocked:a,upgrade:i,blocking:s,terminated:r})=>{let n=indexedDB.open(e,t);var o=p(n);return i&&n.addEventListener("upgradeneeded",e=>{i(p(n.result),e.oldVersion,e.newVersion,p(n.transaction),e)}),a&&n.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),o.then(e=>{r&&e.addEventListener("close",()=>r()),s&&e.addEventListener("versionchange",e=>s(e.oldVersion,e.newVersion,e))}).catch(()=>{}),o})(ye,be,{upgrade:(e,t)=>{0===t&&e.createObjectStore(_)}})}async function I(e,t){var a=E(e),i=(await S()).transaction(_,"readwrite"),s=i.objectStore(_),r=await s.get(a);return await s.put(t,a),await i.done,r&&r.fid===t.fid||ve(e,t.fid),t}async function Ce(e){var t=E(e),a=(await S()).transaction(_,"readwrite");await a.objectStore(_).delete(t),await a.done}async function T(e,t){var a=E(e),i=(await S()).transaction(_,"readwrite"),s=i.objectStore(_),r=await s.get(a),n=t(r);return void 0===n?await s.delete(a):await s.put(n,a),await i.done,!n||r&&r.fid===n.fid||ve(e,n.fid),n}async function k(a){let i;var e=await T(a.appConfig,e=>{var t=Se(e||{fid:pe(),registrationStatus:0}),t=((e,t)=>{var a,i;return 0===t.registrationStatus?navigator.onLine?(a={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},i=(async(t,a)=>{try{var e=await(async({appConfig:e,heartbeatServiceProvider:t},{fid:a})=>{let i=oe(e);var s=ge(e),r=((r=t.getImmediate({optional:!0}))&&(r=await r.getHeartbeatsHeader())&&s.append("x-firebase-client",r),{fid:a,authVersion:ie,appId:e.appId,sdkVersion:ae});let n={method:"POST",headers:s,body:JSON.stringify(r)};if((s=await ue(()=>fetch(i,n))).ok)return{fid:(r=await s.json()).fid||a,registrationStatus:2,refreshToken:r.refreshToken,authToken:ce(r.authToken)};throw await le("Create Installation",s)})(t,a);return I(t.appConfig,e)}catch(e){throw ne(e)&&409===e.customData.serverCode?await Ce(t.appConfig):await I(t.appConfig,{fid:a.fid,registrationStatus:0}),e}})(e,a),{installationEntry:a,registrationPromise:i}):(a=Promise.reject(y.create("app-offline")),{installationEntry:t,registrationPromise:a}):1===t.registrationStatus?{installationEntry:t,registrationPromise:(async e=>{let t=await _e(e.appConfig);for(;1===t.registrationStatus;)await de(100),t=await _e(e.appConfig);var a,i;return 0!==t.registrationStatus?t:({installationEntry:a,registrationPromise:i}=await k(e),i||a)})(e)}:{installationEntry:t}})(a,t);return i=t.registrationPromise,t.installationEntry});return e.fid===b?{installationEntry:await i}:{installationEntry:e,registrationPromise:i}}function _e(e){return T(e,e=>{if(e)return Se(e);throw y.create("installation-not-found")})}function Se(e){var t;return 1===(t=e).registrationStatus&&t.registrationTime+te<Date.now()?{fid:e.fid,registrationStatus:0}:e}async function Ie({appConfig:e,heartbeatServiceProvider:t},a){[s,r]=[e,a.fid];let i=oe(s)+`/${r}/authTokens:generate`;var s,r,n=he(e,a),o=t.getImmediate({optional:!0}),o=(o&&(o=await o.getHeartbeatsHeader())&&n.append("x-firebase-client",o),{installation:{sdkVersion:ae,appId:e.appId}});let c={method:"POST",headers:n,body:JSON.stringify(o)};n=await ue(()=>fetch(i,c));if(n.ok)return ce(await n.json());throw await le("Generate Auth Token",n)}async function R(i,s=!1){let r;var e=await T(i.appConfig,e=>{if(!ke(e))throw y.create("not-registered");var t,a=e.authToken;if(s||2!==(t=a).requestStatus||(e=>{var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+re})(t)){if(1===a.requestStatus)return r=(async(e,t)=>{let a=await Te(e.appConfig);for(;1===a.authToken.requestStatus;)await de(100),a=await Te(e.appConfig);var i=a.authToken;return 0===i.requestStatus?R(e,t):i})(i,s),e;if(navigator.onLine)return t=e,a={requestStatus:1,requestTime:Date.now()},a={...t,authToken:a},r=(async(t,a)=>{try{var e=await Ie(t,a),i={...a,authToken:e};return await I(t.appConfig,i),e}catch(e){var s;throw!ne(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(s={...a,authToken:{requestStatus:0}},await I(t.appConfig,s)):await Ce(t.appConfig),e}})(i,a),a;throw y.create("app-offline")}return e});return r?await r:e.authToken}function Te(e){return T(e,e=>{var t,a;if(ke(e))return t=e.authToken,1===(a=t).requestStatus&&a.requestTime+te<Date.now()?{...e,authToken:{requestStatus:0}}:e;throw y.create("not-registered")})}function ke(e){return void 0!==e&&2===e.registrationStatus}async function Re(e,t=!1){var a=e,i=(await(!(i=(await k(a)).registrationPromise)||!await i),await R(a,t));return i.token}function M(e){return y.create("missing-app-config-values",{valueName:e})}let Me="installations",Le=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:(e=>{if(!e||!e.options)throw M("App Configuration");if(!e.name)throw M("App Name");var t;for(t of["projectId","apiKey","appId"])if(!e.options[t])throw M(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}})(t),heartbeatServiceProvider:it._getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},Ae=e=>{var t=e.getProvider("app").getImmediate();let a=it._getProvider(t,Me).getImmediate();return{getId:()=>(async e=>{var t=e,{installationEntry:a,registrationPromise:i}=await k(t);return(i||R(t)).catch(console.error),a.fid})(a),getToken:e=>Re(a,e)}};it._registerComponent(new e(Me,Le,"PUBLIC")),it._registerComponent(new e("installations-internal",Ae,"PRIVATE")),it.registerVersion(ee,t),it.registerVersion(ee,t,"esm2020");let L="@firebase/remote-config";class Fe{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}let A=new i("remoteconfig","Remote Config",{"already-initialized":"Remote Config already initialized","registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported.","stream-error":"The stream was not able to connect to the backend: {$originalErrorMessage}.","realtime-unavailable":"The Realtime service is unavailable: {$originalErrorMessage}","update-message-invalid":"The stream invalidation message was unparsable: {$originalErrorMessage}","update-not-fetched":"Unable to fetch the latest config: {$originalErrorMessage}","analytics-unavailable":"Connection to Firebase Analytics failed: {$originalErrorMessage}"});let De=["1","true","t","yes","y","on"];class F{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=De.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return e=isNaN(e)?0:e}getSource(){return this._source}}class Pe{constructor(e){this.storage=e._storage,this.logger=e._logger,this.analyticsProvider=e._analyticsProvider}async updateActiveExperiments(e){var t=await this.storage.getActiveExperiments()||new Set,a=this.createExperimentInfoMap(e);return this.addActiveExperiments(a),this.removeInactiveExperiments(t,a),this.storage.setActiveExperiments(new Set(a.keys()))}createExperimentInfoMap(e){var t,a=new Map;for(t of e)a.set(t.experimentId,t);return a}addActiveExperiments(e){var t,a,i={};for([t,a]of e.entries())i["firebase"+t]=a.variantId;this.addExperimentToAnalytics(i)}removeInactiveExperiments(e,t){var a,i={};for(a of e)t.has(a)||(i["firebase"+a]=null);this.addExperimentToAnalytics(i)}addExperimentToAnalytics(e){if(0!==Object.keys(e).length)try{var t=this.analyticsProvider.getImmediate({optional:!0});t?(t.setUserProperties(e),t.logEvent("set_firebase_experiment_state")):this.logger.warn("Analytics import failed. Verify if you have imported Firebase Analytics in your app code.")}catch(e){throw A.create("analytics-unavailable",{originalErrorMessage:e?.message})}}}async function xe(e){var t=r(e),[a,i]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(a&&a.config&&a.eTag&&a.templateVersion&&a.eTag!==i)&&(i=new Pe(t).updateActiveExperiments(a.experiments||[]),await Promise.all([t._storageCache.setActiveConfig(a.config),t._storage.setActiveConfigEtag(a.eTag),t._storage.setActiveConfigTemplateVersion(a.templateVersion),i]),!0)}function Ne(e){let t=r(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function Be(t){var a=r(t);let e=new Fe;setTimeout(async()=>{e.abort()},a.settings.fetchTimeoutMillis);var i,s=a._storageCache.getCustomSignals();s&&a._logger.debug("Fetching config with custom signals: "+JSON.stringify(s));try{await a._client.fetch({cacheMaxAgeMillis:a.settings.minimumFetchIntervalMillis,signal:e,customSignals:s}),await a._storageCache.setLastFetchStatus("success")}catch(e){t="fetch-throttle";s=(i=e)instanceof n&&-1!==i.code.indexOf(t)?"throttle":"failure";throw await a._storageCache.setLastFetchStatus(s),e}}function Oe(a){var e,t,i=r(a);return[e={},t={}]=[i._storageCache.getActiveConfig(),i.defaultConfig],Object.keys({...e,...t}).reduce((e,t)=>(e[t]=D(a,t),e),{})}function D(e,t){var a=r(e),i=(a._isInitializationComplete||a._logger.debug(`A value was requested for key "${t}" before SDK initialization completed.`+" Await on ensureInitialized if the intent was to get a previously activated value."),a._storageCache.getActiveConfig());return i&&void 0!==i[t]?new F("remote",i[t]):a.defaultConfig&&void 0!==a.defaultConfig[t]?new F("default",String(a.defaultConfig[t])):(a._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new F("static"))}class He{constructor(e,t,a,i){this.client=e,this.storage=t,this.storageCache=a,this.logger=i}isCachedDataFresh(e,t){var a;return t?(a=Date.now()-t,this.logger.debug("Config fetch cache check."+` Cache age millis: ${a}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${a=a<=e}.`),a):(this.logger.debug("Config fetch cache check. Cache unpopulated."),!1)}async fetch(e){var[t,a]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(a&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return a;e.eTag=a&&a.eTag;t=await this.client.fetch(e),a=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===t.status&&a.push(this.storage.setLastSuccessfulFetchResponse(t)),await Promise.all(a),t}}class je{constructor(e,t,a,i,s,r){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=a,this.projectId=i,this.apiKey=s,this.appId=r}async fetch(a){var e,[t,i]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),s=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=`+this.apiKey,r={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":a.eTag||"*"},t={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:i,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language,custom_signals:a.customSignals},i={method:"POST",headers:r,body:JSON.stringify(t)},r=fetch(s,i),t=new Promise((e,t)=>{a.signal.addEventListener(()=>{var e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let n;try{await Promise.race([r,t]),n=await r}catch(e){let t="fetch-client-network";throw"AbortError"===e?.name&&(t="fetch-timeout"),A.create(t,{originalErrorMessage:e?.message})}let o=n.status;s=n.headers.get("ETag")||void 0;let c,l,g,h;if(200===n.status){let e;try{e=await n.json()}catch(e){throw A.create("fetch-client-parse",{originalErrorMessage:e?.message})}c=e.entries,l=e.state,g=e.templateVersion,h=e.experimentDescriptions}if("INSTANCE_STATE_UNSPECIFIED"===l?o=500:"NO_CHANGE"===l?o=304:"NO_TEMPLATE"!==l&&"EMPTY_CONFIG"!==l||(c={},h=[]),304!==o&&200!==o)throw A.create("fetch-status",{httpStatus:o});return{status:o,eTag:s,config:c,templateVersion:g,experiments:h}}}class Ve{constructor(e,t){this.client=e,this.storage=t}async fetch(e){var t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(t,{throttleEndTimeMillis:e,backoffCount:a}){var s,r;s=t.signal,r=e,await new Promise((e,t)=>{var a=Math.max(r-Date.now(),0);let i=setTimeout(e,a);s.addEventListener(()=>{clearTimeout(i),t(A.create("fetch-throttle",{throttleEndTimeMillis:r}))})});try{var i=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),i}catch(e){if((e=>{var t;return e instanceof n&&e.customData&&(429===(t=Number(e.customData.httpStatus))||500===t||503===t||504===t)})(e))return i={throttleEndTimeMillis:Date.now()+o(a),backoffCount:a+1},await this.storage.setThrottleMetadata(i),this.attemptFetch(t,i);throw e}}}class $e{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,a,i,s,r,n){this.app=e,this._client=t,this._storageCache=a,this._storage=i,this._logger=s,this._realtimeHandler=r,this._analyticsProvider=n,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function P(e,t){var a=e.target.error||void 0;return A.create(t,{originalErrorMessage:a&&a?.message})}let x="app_namespace_store";class Ue{getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getActiveExperiments(){return this.get("active_experiments")}setActiveExperiments(e){return this.set("active_experiments",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}getCustomSignals(){return this.get("custom_signals")}getRealtimeBackoffMetadata(){return this.get("realtime_backoff_metadata")}setRealtimeBackoffMetadata(e){return this.set("realtime_backoff_metadata",e)}getActiveConfigTemplateVersion(){return this.get("last_known_template_version")}setActiveConfigTemplateVersion(e){return this.set("last_known_template_version",e)}}class Ke extends Ue{constructor(e,t,a,i=(()=>new Promise((t,a)=>{try{var e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{a(P(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{var t=e.target.result;0===e.oldVersion&&t.createObjectStore(x,{keyPath:"compositeKey"})}}catch(e){a(A.create("storage-open",{originalErrorMessage:e?.message}))}}))()){super(),this.appId=e,this.appName=t,this.namespace=a,this.openDbPromise=i}async setCustomSignals(e){var t=(await this.openDbPromise).transaction([x],"readwrite"),a=We(e,await this.getWithTransaction("custom_signals",t)||{});return await this.setWithTransaction("custom_signals",a,t),a}async getWithTransaction(r,n){return new Promise((a,t)=>{var e=n.objectStore(x),i=this.createCompositeKey(r);try{var s=e.get(i);s.onerror=e=>{t(P(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;a(t?t.value:void 0)}}catch(e){t(A.create("storage-get",{originalErrorMessage:e?.message}))}})}async setWithTransaction(r,n,o){return new Promise((e,t)=>{var a=o.objectStore(x),i=this.createCompositeKey(r);try{var s=a.put({compositeKey:i,value:n});s.onerror=e=>{t(P(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(A.create("storage-set",{originalErrorMessage:e?.message}))}})}async get(e){var t=(await this.openDbPromise).transaction([x],"readonly");return this.getWithTransaction(e,t)}async set(e,t){var a=(await this.openDbPromise).transaction([x],"readwrite");return this.setWithTransaction(e,t,a)}async delete(r){let n=await this.openDbPromise;return new Promise((e,t)=>{var a=n.transaction([x],"readwrite").objectStore(x),i=this.createCompositeKey(r);try{var s=a.delete(i);s.onerror=e=>{t(P(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(A.create("storage-delete",{originalErrorMessage:e?.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class qe extends Ue{constructor(){super(...arguments),this.storage={}}async get(e){return Promise.resolve(this.storage[e])}async set(e,t){return this.storage[e]=t,Promise.resolve(void 0)}async delete(e){return this.storage[e]=void 0,Promise.resolve()}async setCustomSignals(e){var t=this.storage.custom_signals||{};return this.storage.custom_signals=We(e,t),Promise.resolve(this.storage.custom_signals)}}function We(e,t){var a={...t,...e},a=Object.fromEntries(Object.entries(a).filter(([,e])=>null!==e).map(([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t]));if(100<Object.keys(a).length)throw A.create("custom-signal-max-allowed-signals",{maxSignals:100});return a}class ze{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),a=this.storage.getActiveConfig(),i=this.storage.getCustomSignals(),e=await e,e=(e&&(this.lastFetchStatus=e),await t),t=(e&&(this.lastSuccessfulFetchTimestampMillis=e),await a),e=(t&&(this.activeConfig=t),await i);e&&(this.customSignals=e)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}class Ge extends class{constructor(e){this.allowedEvents_=e,this.listeners_={},a(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...a){if(Array.isArray(this.listeners_[t])){var i=[...this.listeners_[t]];for(let e=0;e<i.length;e++)i[e].callback.apply(i[e].context,a)}}on(e,t,a){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:a});var i=this.getInitialEvent(e);i&&t.apply(a,i)}off(e,t,a){this.validateEventType_(e);var i=this.listeners_[e]||[];for(let s=0;s<i.length;s++)if(i[s].callback===t&&(!a||a===i[s].context))return void i.splice(s,1)}validateEventType_(t){a(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}{static getInstance(){return new Ge}constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}getInitialEvent(e){return a("visible"===e,"Unknown event type: "+e),[this.visible_]}}let Je="featureDisabled",Xe="retryIntervalSeconds",Ye="latestTemplateVersionNumber";class Ze{constructor(e,t,a,i,s,r,n,o,c,l){this.firebaseInstallations=e,this.storage=t,this.sdkVersion=a,this.namespace=i,this.projectId=s,this.apiKey=r,this.appId=n,this.logger=o,this.storageCache=c,this.cachingClient=l,this.observers=new Set,this.isConnectionActive=!1,this.isRealtimeDisabled=!1,this.httpRetriesRemaining=8,this.isInBackground=!1,this.decoder=new TextDecoder("utf-8"),this.isClosingConnection=!1,this.propagateError=t=>this.observers.forEach(e=>e.error?.(t)),this.isStatusCodeRetryable=e=>!e||[408,429,502,503,504].includes(e),this.setRetriesRemaining(),Ge.getInstance().on("visible",this.onVisibilityChange,this)}async setRetriesRemaining(){var e=(await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams||0;this.httpRetriesRemaining=Math.max(8-e,1)}async updateBackoffMetadataWithLastFailedStreamConnectionTime(e){var t=((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams||0)+1,a=o(t,6e4,2);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(e.getTime()+a),numFailedStreams:t})}async updateBackoffMetadataWithRetryInterval(e){var t=Date.now(),t=new Date(t+1e3*e);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:t,numFailedStreams:0}),await this.retryHttpConnectionWhenBackoffEnds()}async closeRealtimeHttpConnection(){if(!this.isClosingConnection){this.isClosingConnection=!0;try{this.reader&&await this.reader.cancel()}catch(e){this.logger.debug("Failed to cancel the reader, connection was lost.")}finally{this.reader=void 0}this.controller&&(await this.controller.abort(),this.controller=void 0),this.isClosingConnection=!1}}async resetRealtimeBackoff(){await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(-1),numFailedStreams:0})}resetRetryCount(){this.httpRetriesRemaining=8}async establishRealtimeConnection(e,t,a,i){var s=await this.storage.getActiveConfigEtag(),r=await this.storage.getActiveConfigTemplateVersion(),s={"X-Goog-Api-Key":this.apiKey,"X-Goog-Firebase-Installations-Auth":a,"Content-Type":"application/json",Accept:"application/json","If-None-Match":s||"*","Content-Encoding":"gzip"},r={project:this.projectId,namespace:this.namespace,lastKnownVersionNumber:r,appId:this.appId,sdkVersion:this.sdkVersion,appInstanceId:t};return await fetch(e,{method:"POST",headers:s,body:JSON.stringify(r),signal:i})}getRealtimeUrl(){var e=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfigrealtime.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=`+this.apiKey;return new URL(e)}async createRealtimeConnection(){var[e,t]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken(!1)]),a=(this.controller=new AbortController,this.getRealtimeUrl());return await this.establishRealtimeConnection(a,e,t,this.controller.signal)}async retryHttpConnectionWhenBackoffEnds(){let e=await this.storage.getRealtimeBackoffMetadata();e=e||{backoffEndTimeMillis:new Date(-1),numFailedStreams:0};var t=new Date(e.backoffEndTimeMillis).getTime(),a=Date.now(),t=Math.max(0,t-a);await this.makeRealtimeHttpConnection(t)}setIsHttpConnectionRunning(e){this.isConnectionActive=e}checkAndSetHttpConnectionFlagIfNotRunning(){var e=this.canEstablishStreamConnection();return e&&this.setIsHttpConnectionRunning(!0),e}fetchResponseIsUpToDate(e,t){return null!=e.config&&e.templateVersion?e.templateVersion>=t:"success"===this.storageCache.getLastFetchStatus()}parseAndValidateConfigUpdateMessage(e){var t=e.indexOf("{"),a=e.indexOf("}",t);return t<0||a<0||a<=t?"":e.substring(t,a+1)}isEventListenersEmpty(){return 0===this.observers.size}getRandomInt(e){return Math.floor(Math.random()*e)}executeAllListenerCallbacks(t){this.observers.forEach(e=>e.next(t))}getChangedParams(e,t,a,i){var s,r,n,o,c=new Set,l=new Set(Object.keys(e||{})),g=new Set(Object.keys(t||{})),h=a.experiments||[],u=i?.experiments||[],d=this.createExperimentsMap(h),f=this.createExperimentsMap(u);for(s of l)g.has(s)&&e[s]===t[s]||c.add(s),d.has(s)!==f.has(s)?c.add(s):(r=d.get(s),n=f.get(s),r&&n&&!this.areExperimentsEqual(r,n)&&c.add(s));for(o of g)l.has(o)||c.add(o);return c}areExperimentsEqual(e,t){return e.experimentId===t.experimentId&&e.variantId===t.variantId&&e.timeToLiveMillis===t.timeToLiveMillis&&e.triggerTimeoutMillis===t.triggerTimeoutMillis}createExperimentsMap(e){var t,a=new Map;for(t of e)if(t.affectedParameterKeys&&!t.experimentId.startsWith("_exp_rollout"))for(var i of t.affectedParameterKeys)a.set(i,t);return a}async fetchLatestConfig(e,a){var i=e-1,s=3-i,r=this.storageCache.getCustomSignals(),n=(r&&this.logger.debug("Fetching config with custom signals: "+JSON.stringify(r)),new Fe);try{var o,c={cacheMaxAgeMillis:0,signal:n,customSignals:r,fetchType:"REALTIME",fetchAttempt:s},l=await this.storage.getLastSuccessfulFetchResponse(),g=await this.cachingClient.fetch(c);let t=await this.storage.getActiveConfig();if(this.fetchResponseIsUpToDate(g,a))if(null==g.config)this.logger.debug("The fetch succeeded, but the backend had no updates.");else{null==t&&(t={});let e=this.getChangedParams(g.config,t,g,l);0===e.size?this.logger.debug("Config was fetched, but no params changed."):(o={getUpdatedKeys(){return new Set(e)}},this.executeAllListenerCallbacks(o))}else this.logger.debug("Fetched template version is the same as SDK's current version. Retrying fetch."),await this.autoFetch(i,a)}catch(e){n=e instanceof Error?e.message:String(e),r=A.create("update-not-fetched",{originalErrorMessage:"Failed to auto-fetch config update: "+n});this.propagateError(r)}}async autoFetch(e,a){var t;if(0===e)t=A.create("update-not-fetched",{originalErrorMessage:"Unable to fetch the latest version of the template."}),this.propagateError(t);else{let t=1e3*this.getRandomInt(4);await new Promise(e=>setTimeout(e,t)),await this.fetchLatestConfig(e,a)}}async handleNotifications(e){let t="";for(;;){var{done:a,value:i}=await e.read();if(a)break;if(a=this.decoder.decode(i,{stream:!0}),t+=a,a.includes("}")&&0!==(t=this.parseAndValidateConfigUpdateMessage(t)).length){try{var s,r,n,o=JSON.parse(t);if(this.isEventListenersEmpty())break;if(Je in o&&!0===o[Je]){var c=A.create("realtime-unavailable",{originalErrorMessage:"The server is temporarily unavailable. Try again in a few minutes."});this.propagateError(c);break}Ye in o&&(s=await this.storage.getActiveConfigTemplateVersion(),r=Number(o[Ye]),s)&&s<r&&await this.autoFetch(3,r),Xe in o&&(n=Number(o[Xe]),await this.updateBackoffMetadataWithRetryInterval(n))}catch(e){this.logger.debug("Unable to parse latest config update message.",e);i=e instanceof Error?e.message:String(e);this.propagateError(A.create("update-message-invalid",{originalErrorMessage:i}))}t=""}}}async listenForNotifications(e){try{await this.handleNotifications(e)}catch(e){this.isInBackground||this.logger.debug("Real-time connection was closed due to an exception.")}}async prepareAndBeginRealtimeHttpStream(){if(this.checkAndSetHttpConnectionFlagIfNotRunning()){let e=await this.storage.getRealtimeBackoffMetadata();var a=(e=e||{backoffEndTimeMillis:new Date(-1),numFailedStreams:0}).backoffEndTimeMillis.getTime();if(Date.now()<a)await this.retryHttpConnectionWhenBackoffEnds();else{let e,t;try{e=await this.createRealtimeConnection(),t=e.status,e.ok&&e.body&&(this.resetRetryCount(),await this.resetRealtimeBackoff(),i=e.body.getReader(),this.reader=i,await this.listenForNotifications(i))}catch(e){this.isInBackground?this.resetRetryCount():this.logger.debug("Exception connecting to real-time RC backend. Retrying the connection...:",e)}finally{await this.closeRealtimeHttpConnection(),this.setIsHttpConnectionRunning(!1);var i,a=!this.isInBackground&&(void 0===t||this.isStatusCodeRetryable(t));a&&await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date),a||e?.ok?await this.retryHttpConnectionWhenBackoffEnds():(i="Unable to connect to the server. HTTP status code: "+t,a=A.create("stream-error",{originalErrorMessage:i}),this.propagateError(a))}}}}canEstablishStreamConnection(){var e=0<this.observers.size,t=!this.isRealtimeDisabled,a=!this.isConnectionActive,i=!this.isInBackground;return e&&t&&a&&i}async makeRealtimeHttpConnection(t){var e;this.canEstablishStreamConnection()&&(0<this.httpRetriesRemaining?(this.httpRetriesRemaining--,await new Promise(e=>setTimeout(e,t)),this.prepareAndBeginRealtimeHttpStream()):this.isInBackground||(e=A.create("stream-error",{originalErrorMessage:"Unable to connect to the server. Check your connection and try again."}),this.propagateError(e)))}async beginRealtime(){0<this.observers.size&&await this.makeRealtimeHttpConnection(0)}addObserver(e){this.observers.add(e),this.beginRealtime()}removeObserver(e){this.observers.has(e)&&this.observers.delete(e)}async onVisibilityChange(e){this.isInBackground=!e,e?await this.beginRealtime():await this.closeRealtimeHttpConnection()}}async function Qe(){if(!d())return!1;try{return await new Promise((i,s)=>{try{let e=!0,t="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(t);a.onsuccess=()=>{a.result.close(),e||self.indexedDB.deleteDatabase(t),i(!0)},a.onupgradeneeded=()=>{e=!1},a.onerror=()=>{s(a.error?.message||"")}}catch(e){s(e)}})}catch(e){return!1}}it._registerComponent(new e("remote-config",function(e,{options:t}){var a=e.getProvider("app").getImmediate(),i=e.getProvider("installations-internal").getImmediate(),s=e.getProvider("analytics-internal"),{projectId:r,apiKey:n,appId:o}=a.options;if(!r)throw A.create("registration-project-id");if(!n)throw A.create("registration-api-key");if(!o)throw A.create("registration-app-id");var c=t?.templateId||"firebase",l=d()?new Ke(o,a.name,c):new qe,g=new ze(l),h=new K(L),u=(h.logLevel=f.ERROR,new je(i,it.SDK_VERSION,c,r,n,o)),u=new Ve(u,l),u=new He(u,l,g,h),i=new Ze(i,l,it.SDK_VERSION,c,r,n,o,h,g,u),c=new $e(a,u,g,l,h,i,s);return Ne(c),c},"PUBLIC").setMultipleInstances(!0)),it.registerVersion(L,"0.8.5"),it.registerVersion(L,"0.8.5","esm2020");class et{constructor(e,t){this.app=e,this._delegate=t}get defaultConfig(){return this._delegate.defaultConfig}set defaultConfig(e){this._delegate.defaultConfig=e}get fetchTimeMillis(){return this._delegate.fetchTimeMillis}get lastFetchStatus(){return this._delegate.lastFetchStatus}get settings(){return this._delegate.settings}set settings(e){this._delegate.settings=e}activate(){return xe(this._delegate)}ensureInitialized(){return Ne(this._delegate)}fetch(){return Be(this._delegate)}fetchAndActivate(){return(async e=>(await Be(e=r(e)),xe(e)))(this._delegate)}getAll(){return Oe(this._delegate)}getBoolean(e){return D(r(this._delegate),e).asBoolean()}getNumber(e){return D(r(this._delegate),e).asNumber()}getString(e){return D(r(this._delegate),e).asString()}getValue(e){return D(this._delegate,e)}setLogLevel(e){var t=this._delegate,a=r(t);switch(e){case"debug":a._logger.logLevel=f.DEBUG;break;case"silent":a._logger.logLevel=f.SILENT;break;default:a._logger.logLevel=f.ERROR}}}function tt(e,{instanceIdentifier:t}){var a=e.getProvider("app-compat").getImmediate(),i=e.getProvider("remote-config").getImmediate({identifier:t});return new et(a,i)}(w=B.default).INTERNAL.registerComponent(new e("remoteConfig-compat",tt,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:Qe})),w.registerVersion("@firebase/remote-config-compat","0.2.26")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-remote-config-compat.js - be sure to load firebase-app.js first.")}});
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as i,SDK_VERSION as s}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";const n="${JSCORE_VERSION}",assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+n+") INTERNAL ASSERT FAILED: "+e)};function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,i){super(t),this.code=e,this.customData=i,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,i){this.service=e,this.serviceName=t,this.errors=i}create(e,...t){const i=t[0]||{},s=`${this.service}/${e}`,n=this.errors[e],r=n?function replaceTemplate(e,t){return e.replace(a,((e,i)=>{const s=t[i];return null!=s?String(s):`<${i}?>`}))}(n,i):"Error",o=`${this.serviceName}: ${r} (${s}).`;return new FirebaseError(s,o,i)}}const a=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const i=Object.keys(e),s=Object.keys(t);for(const n of i){if(!s.includes(n))return!1;const i=e[n],a=t[n];if(isObject(i)&&isObject(a)){if(!deepEqual(i,a))return!1}else if(i!==a)return!1}for(const e of s)if(!i.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,i=2){const s=t*Math.pow(i,e),n=Math.round(.5*s*(Math.random()-.5)*2);return Math.min(144e5,s+n)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,i){this.name=e,this.instanceFactory=t,this.type=i,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var r;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(r||(r={}));const o={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},c=r.INFO,l={[r.DEBUG]:"log",[r.VERBOSE]:"log",[r.INFO]:"info",[r.WARN]:"warn",[r.ERROR]:"error"},defaultLogHandler=(e,t,...i)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),n=l[t];if(!n)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[n](`[${s}] ${e.name}:`,...i)};class Logger{constructor(e){this.name=e,this._logLevel=c,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in r))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?o[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,r.DEBUG,...e),this._logHandler(this,r.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,r.VERBOSE,...e),this._logHandler(this,r.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,r.INFO,...e),this._logHandler(this,r.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,r.WARN,...e),this._logHandler(this,r.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,r.ERROR,...e),this._logHandler(this,r.ERROR,...e)}}let g,u;const h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,m=new WeakMap;let w={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return d.get(e);if("objectStoreNames"===t)return e.objectStoreNames||f.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return wrap(e[t])},set:(e,t,i)=>(e[t]=i,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return u||(u=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(h.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...i){const s=e.call(unwrap(this),t,...i);return f.set(s,t.sort?t.sort():[t]),wrap(s)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(d.has(e))return;const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{i(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));d.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return g||(g=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,w):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{i(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&h.set(t,e)})).catch((()=>{})),m.set(t,e),t}(e);if(p.has(e))return p.get(e);const t=transformCachableValue(e);return t!==e&&(p.set(e,t),m.set(t,e)),t}const unwrap=e=>m.get(e);const v=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],b=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(b.get(t))return b.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,n=y.includes(i);if(!(i in(s?IDBIndex:IDBObjectStore).prototype)||!n&&!v.includes(i))return;const method=async function(e,...t){const a=this.transaction(e,n?"readwrite":"readonly");let r=a.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),n&&a.done]))[0]};return b.set(t,method),method}!function replaceTraps(e){w=e(w)}((e=>({...e,get:(t,i,s)=>getMethod(t,i)||e.get(t,i,s),has:(t,i)=>!!getMethod(t,i)||e.has(t,i)})));const E="@firebase/installations",C="0.6.22",I=1e4,S=`w:${C}`,T="FIS_v2",_=36e5,R=new ErrorFactory("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const i=(await t.json()).error;return R.create("request-failed",{requestName:e,serverCode:i.code,serverMessage:i.message,serverStatus:i.status})}function getHeaders({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const i=getHeaders(e);return i.append("Authorization",function getAuthorizationHeader(e){return`${T} ${e}`}(t)),i}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const k=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return k.test(t)?t:""}catch{return""}}function getKey(e){return`${e.appName}!${e.appId}`}const M=new Map;function fidChanged(e,t){const i=getKey(e);callFidChangeCallbacks(i,t),function broadcastFidChange(e,t){const i=function getBroadcastChannel(){!F&&"BroadcastChannel"in self&&(F=new BroadcastChannel("[Firebase] FID Change"),F.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return F}();i&&i.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===M.size&&F&&(F.close(),F=null)}()}(i,t)}function callFidChangeCallbacks(e,t){const i=M.get(e);if(i)for(const e of i)e(t)}let F=null;const A="firebase-installations-store";let L=null;function getDbPromise(){return L||(L=function openDB(e,t,{blocked:i,upgrade:s,blocking:n,terminated:a}={}){const r=indexedDB.open(e,t),o=wrap(r);return s&&r.addEventListener("upgradeneeded",(e=>{s(wrap(r.result),e.oldVersion,e.newVersion,wrap(r.transaction),e)})),i&&r.addEventListener("blocked",(e=>i(e.oldVersion,e.newVersion,e))),o.then((e=>{a&&e.addEventListener("close",(()=>a())),n&&e.addEventListener("versionchange",(e=>n(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(A)}})),L}async function set(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(A,"readwrite"),n=s.objectStore(A),a=await n.get(i);return await n.put(t,i),await s.done,a&&a.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),i=(await getDbPromise()).transaction(A,"readwrite");await i.objectStore(A).delete(t),await i.done}async function update(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(A,"readwrite"),n=s.objectStore(A),a=await n.get(i),r=t(a);return void 0===r?await n.delete(i):await n.put(r,i),await s.done,!r||a&&a.fid===r.fid||fidChanged(e,r.fid),r}async function getInstallationEntry(e){let t;const i=await update(e.appConfig,(i=>{const s=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(i),n=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(R.create("app-offline"))}}const i={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},s=async function registerInstallation(e,t){try{const i=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:i}){const s=getInstallationsEndpoint(e),n=getHeaders(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={fid:i,authVersion:T,appId:e.appId,sdkVersion:S},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){const e=await c.json();return{fid:e.fid||i,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,i)}catch(i){throw isServerError(i)&&409===i.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),i}}(e,i);return{installationEntry:i,registrationPromise:s}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,s);return t=n.registrationPromise,n.installationEntry}));return""===i.fid?{installationEntry:await t}:{installationEntry:i,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:i}=await getInstallationEntry(e);return i||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw R.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+I<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},i){const s=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,i),n=getHeadersWithAuth(e,i),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={installation:{sdkVersion:S,appId:e.appId}},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let i;const s=await update(e.appConfig,(s=>{if(!isEntryRegistered(s))throw R.create("not-registered");const n=s.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+_}(e)}(n))return s;if(1===n.requestStatus)return i=async function waitUntilAuthTokenRequest(e,t){let i=await updateAuthTokenRequest(e.appConfig);for(;1===i.authToken.requestStatus;)await sleep(100),i=await updateAuthTokenRequest(e.appConfig);const s=i.authToken;return 0===s.requestStatus?refreshAuthToken(e,t):s}(e,t),s;{if(!navigator.onLine)throw R.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(s);return i=async function fetchAuthTokenFromServer(e,t){try{const i=await generateAuthTokenRequest(e,t),s={...t,authToken:i};return await set(e.appConfig,s),i}catch(i){if(!isServerError(i)||401!==i.customData.serverCode&&404!==i.customData.serverCode){const i={...t,authToken:{requestStatus:0}};await set(e.appConfig,i)}else await remove(e.appConfig);throw i}}(e,t),t}}));return i?await i:s.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw R.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+I<Date.now()}(e.authToken)?{...e,authToken:{requestStatus:0}}:e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const i=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(i);return(await refreshAuthToken(i,t)).token}function getMissingValueError(e){return R.create("missing-app-config-values",{valueName:e})}const D="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),i=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId"];for(const i of t)if(!e.options[i])throw getMissingValueError(i);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:i,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),i=_getProvider(t,D).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:i,registrationPromise:s}=await getInstallationEntry(t);return s?s.catch(console.error):refreshAuthToken(t).catch(console.error),i.fid}(i),getToken:e=>getToken(i,e)}};!function registerInstallations(){t(new Component(D,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(E,C),e(E,C,"esm2020");const x="@firebase/remote-config",P="0.8.5";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const B="remote-config",O=new ErrorFactory("remoteconfig","Remote Config",{"already-initialized":"Remote Config already initialized","registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported.","stream-error":"The stream was not able to connect to the backend: {$originalErrorMessage}.","realtime-unavailable":"The Realtime service is unavailable: {$originalErrorMessage}","update-message-invalid":"The stream invalidation message was unparsable: {$originalErrorMessage}","update-not-fetched":"Unable to fetch the latest config: {$originalErrorMessage}","analytics-unavailable":"Connection to Firebase Analytics failed: {$originalErrorMessage}"});const N=["1","true","t","yes","y","on"];class Value{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&N.indexOf(this._value.toLowerCase())>=0}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}class Experiment{constructor(e){this.storage=e._storage,this.logger=e._logger,this.analyticsProvider=e._analyticsProvider}async updateActiveExperiments(e){const t=await this.storage.getActiveExperiments()||new Set,i=this.createExperimentInfoMap(e);return this.addActiveExperiments(i),this.removeInactiveExperiments(t,i),this.storage.setActiveExperiments(new Set(i.keys()))}createExperimentInfoMap(e){const t=new Map;for(const i of e)t.set(i.experimentId,i);return t}addActiveExperiments(e){const t={};for(const[i,s]of e.entries())t[`firebase${i}`]=s.variantId;this.addExperimentToAnalytics(t)}removeInactiveExperiments(e,t){const i={};for(const s of e)t.has(s)||(i[`firebase${s}`]=null);this.addExperimentToAnalytics(i)}addExperimentToAnalytics(e){if(0!==Object.keys(e).length)try{const t=this.analyticsProvider.getImmediate({optional:!0});t?(t.setUserProperties(e),t.logEvent("set_firebase_experiment_state")):this.logger.warn("Analytics import failed. Verify if you have imported Firebase Analytics in your app code.")}catch(e){throw O.create("analytics-unavailable",{originalErrorMessage:e?.message})}}}function getRemoteConfig(e=i(),t={}){e=getModularInstance(e);const s=_getProvider(e,B);if(s.isInitialized()){if(deepEqual(s.getOptions(),t))return s.getImmediate();throw O.create("already-initialized")}s.initialize({options:t});const n=s.getImmediate();return t.initialFetchResponse&&(n._initializePromise=Promise.all([n._storage.setLastSuccessfulFetchResponse(t.initialFetchResponse),n._storage.setActiveConfigEtag(t.initialFetchResponse?.eTag||""),n._storage.setActiveConfigTemplateVersion(t.initialFetchResponse.templateVersion||0),n._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),n._storageCache.setLastFetchStatus("success"),n._storageCache.setActiveConfig(t.initialFetchResponse?.config||{})]).then(),n._isInitializationComplete=!0),n}async function activate(e){const t=getModularInstance(e),[i,s]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);if(!(i&&i.config&&i.eTag&&i.templateVersion&&i.eTag!==s))return!1;const n=new Experiment(t).updateActiveExperiments(i.experiments||[]);return await Promise.all([t._storageCache.setActiveConfig(i.config),t._storage.setActiveConfigEtag(i.eTag),t._storage.setActiveConfigTemplateVersion(i.templateVersion),n]),!0}function ensureInitialized(e){const t=getModularInstance(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then((()=>{t._isInitializationComplete=!0}))),t._initializePromise}async function fetchConfig(e){const t=getModularInstance(e),i=new RemoteConfigAbortSignal;setTimeout((async()=>{i.abort()}),t.settings.fetchTimeoutMillis);const s=t._storageCache.getCustomSignals();s&&t._logger.debug(`Fetching config with custom signals: ${JSON.stringify(s)}`);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:i,customSignals:s}),await t._storageCache.setLastFetchStatus("success")}catch(e){const i=function hasErrorCode(e,t){return e instanceof FirebaseError&&-1!==e.code.indexOf(t)}(e,"fetch-throttle")?"throttle":"failure";throw await t._storageCache.setLastFetchStatus(i),e}}function getAll(e){const t=getModularInstance(e);return function getAllKeys(e={},t={}){return Object.keys({...e,...t})}(t._storageCache.getActiveConfig(),t.defaultConfig).reduce(((t,i)=>(t[i]=getValue(e,i),t)),{})}function getBoolean(e,t){return getValue(getModularInstance(e),t).asBoolean()}function getNumber(e,t){return getValue(getModularInstance(e),t).asNumber()}function getString(e,t){return getValue(getModularInstance(e),t).asString()}function getValue(e,t){const i=getModularInstance(e);i._isInitializationComplete||i._logger.debug(`A value was requested for key "${t}" before SDK initialization completed. Await on ensureInitialized if the intent was to get a previously activated value.`);const s=i._storageCache.getActiveConfig();return s&&void 0!==s[t]?new Value("remote",s[t]):i.defaultConfig&&void 0!==i.defaultConfig[t]?new Value("default",String(i.defaultConfig[t])):(i._logger.debug(`Returning static value for key "${t}". Define a default or remote value if this is unintentional.`),new Value("static"))}function setLogLevel(e,t){const i=getModularInstance(e);switch(t){case"debug":i._logger.logLevel=r.DEBUG;break;case"silent":i._logger.logLevel=r.SILENT;break;default:i._logger.logLevel=r.ERROR}}async function setCustomSignals(e,t){const i=getModularInstance(e);if(0!==Object.keys(t).length){for(const e in t){if(e.length>250)return void i._logger.error(`Custom signal key ${e} is too long, max allowed length is 250.`);const s=t[e];if("string"==typeof s&&s.length>500)return void i._logger.error(`Value supplied for custom signal ${e} is too long, max allowed length is 500.`)}try{await i._storageCache.setCustomSignals(t)}catch(e){i._logger.error(`Error encountered while setting custom signals: ${e}`)}}}function onConfigUpdate(e,t){const i=getModularInstance(e);return i._realtimeHandler.addObserver(t),()=>{i._realtimeHandler.removeObserver(t)}}class CachingClient{constructor(e,t,i,s){this.client=e,this.storage=t,this.storageCache=i,this.logger=s}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const i=Date.now()-t,s=i<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${i}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${s}.`),s}async fetch(e){const[t,i]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(i&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return i;e.eTag=i&&i.eTag;const s=await this.client.fetch(e),n=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===s.status&&n.push(this.storage.setLastSuccessfulFetchResponse(s)),await Promise.all(n),s}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,i,s,n,a){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=i,this.projectId=s,this.apiKey=n,this.appId=a}async fetch(e){const[t,i]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),s=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,n={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":e.eTag||"*"},a={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:i,app_id:this.appId,language_code:getUserLanguage(),custom_signals:e.customSignals},r={method:"POST",headers:n,body:JSON.stringify(a)},o=fetch(s,r),c=new Promise(((t,i)=>{e.signal.addEventListener((()=>{const e=new Error("The operation was aborted.");e.name="AbortError",i(e)}))}));let l;try{await Promise.race([o,c]),l=await o}catch(e){let t="fetch-client-network";throw"AbortError"===e?.name&&(t="fetch-timeout"),O.create(t,{originalErrorMessage:e?.message})}let g=l.status;const u=l.headers.get("ETag")||void 0;let h,d,f,p;if(200===l.status){let e;try{e=await l.json()}catch(e){throw O.create("fetch-client-parse",{originalErrorMessage:e?.message})}h=e.entries,d=e.state,f=e.templateVersion,p=e.experimentDescriptions}if("INSTANCE_STATE_UNSPECIFIED"===d?g=500:"NO_CHANGE"===d?g=304:"NO_TEMPLATE"!==d&&"EMPTY_CONFIG"!==d||(h={},p=[]),304!==g&&200!==g)throw O.create("fetch-status",{httpStatus:g});return{status:g,eTag:u,config:h,templateVersion:f,experiments:p}}}class RetryingClient{constructor(e,t){this.client=e,this.storage=t}async fetch(e){const t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(e,{throttleEndTimeMillis:t,backoffCount:i}){await function setAbortableTimeout(e,t){return new Promise(((i,s)=>{const n=Math.max(t-Date.now(),0),a=setTimeout(i,n);e.addEventListener((()=>{clearTimeout(a),s(O.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(e.signal,t);try{const t=await this.client.fetch(e);return await this.storage.deleteThrottleMetadata(),t}catch(t){if(!function isRetriableError(e){if(!(e instanceof FirebaseError&&e.customData))return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(t))throw t;const s={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(i),backoffCount:i+1};return await this.storage.setThrottleMetadata(s),this.attemptFetch(e,s)}}}class RemoteConfig{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,i,s,n,a,r){this.app=e,this._client=t,this._storageCache=i,this._storage=s,this._logger=n,this._realtimeHandler=a,this._analyticsProvider=r,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function toFirebaseError(e,t){const i=e.target.error||void 0;return O.create(t,{originalErrorMessage:i&&i?.message})}const H="app_namespace_store";class Storage{getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getActiveExperiments(){return this.get("active_experiments")}setActiveExperiments(e){return this.set("active_experiments",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}getCustomSignals(){return this.get("custom_signals")}getRealtimeBackoffMetadata(){return this.get("realtime_backoff_metadata")}setRealtimeBackoffMetadata(e){return this.set("realtime_backoff_metadata",e)}getActiveConfigTemplateVersion(){return this.get("last_known_template_version")}setActiveConfigTemplateVersion(e){return this.set("last_known_template_version",e)}}class IndexedDbStorage extends Storage{constructor(e,t,i,s=function openDatabase(){return new Promise(((e,t)=>{try{const i=indexedDB.open("firebase_remote_config",1);i.onerror=e=>{t(toFirebaseError(e,"storage-open"))},i.onsuccess=t=>{e(t.target.result)},i.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(H,{keyPath:"compositeKey"})}}catch(e){t(O.create("storage-open",{originalErrorMessage:e?.message}))}}))}()){super(),this.appId=e,this.appName=t,this.namespace=i,this.openDbPromise=s}async setCustomSignals(e){const t=(await this.openDbPromise).transaction([H],"readwrite"),i=mergeCustomSignals(e,await this.getWithTransaction("custom_signals",t)||{});return await this.setWithTransaction("custom_signals",i,t),i}async getWithTransaction(e,t){return new Promise(((i,s)=>{const n=t.objectStore(H),a=this.createCompositeKey(e);try{const e=n.get(a);e.onerror=e=>{s(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;i(t?t.value:void 0)}}catch(e){s(O.create("storage-get",{originalErrorMessage:e?.message}))}}))}async setWithTransaction(e,t,i){return new Promise(((s,n)=>{const a=i.objectStore(H),r=this.createCompositeKey(e);try{const e=a.put({compositeKey:r,value:t});e.onerror=e=>{n(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{s()}}catch(e){n(O.create("storage-set",{originalErrorMessage:e?.message}))}}))}async get(e){const t=(await this.openDbPromise).transaction([H],"readonly");return this.getWithTransaction(e,t)}async set(e,t){const i=(await this.openDbPromise).transaction([H],"readwrite");return this.setWithTransaction(e,t,i)}async delete(e){const t=await this.openDbPromise;return new Promise(((i,s)=>{const n=t.transaction([H],"readwrite").objectStore(H),a=this.createCompositeKey(e);try{const e=n.delete(a);e.onerror=e=>{s(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{i()}}catch(e){s(O.create("storage-delete",{originalErrorMessage:e?.message}))}}))}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class InMemoryStorage extends Storage{constructor(){super(...arguments),this.storage={}}async get(e){return Promise.resolve(this.storage[e])}async set(e,t){return this.storage[e]=t,Promise.resolve(void 0)}async delete(e){return this.storage[e]=void 0,Promise.resolve()}async setCustomSignals(e){const t=this.storage.custom_signals||{};return this.storage.custom_signals=mergeCustomSignals(e,t),Promise.resolve(this.storage.custom_signals)}}function mergeCustomSignals(e,t){const i={...t,...e},s=Object.fromEntries(Object.entries(i).filter((([e,t])=>null!==t)).map((([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t])));if(Object.keys(s).length>100)throw O.create("custom-signal-max-allowed-signals",{maxSignals:100});return s}class StorageCache{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){const e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),i=this.storage.getActiveConfig(),s=this.storage.getCustomSignals(),n=await e;n&&(this.lastFetchStatus=n);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const r=await i;r&&(this.activeConfig=r);const o=await s;o&&(this.customSignals=o)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}class EventEmitter{constructor(e){this.allowedEvents_=e,this.listeners_={},assert(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const i=[...this.listeners_[e]];for(let e=0;e<i.length;e++)i[e].callback.apply(i[e].context,t)}}on(e,t,i){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:i});const s=this.getInitialEvent(e);s&&t.apply(i,s)}off(e,t,i){this.validateEventType_(e);const s=this.listeners_[e]||[];for(let e=0;e<s.length;e++)if(s[e].callback===t&&(!i||i===s[e].context))return void s.splice(e,1)}validateEventType_(e){assert(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}class VisibilityMonitor extends EventEmitter{static getInstance(){return new VisibilityMonitor}constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}getInitialEvent(e){return assert("visible"===e,"Unknown event type: "+e),[this.visible_]}}const V="X-Goog-Api-Key",$="X-Goog-Firebase-Installations-Auth",j="featureDisabled",q="retryIntervalSeconds",U="latestTemplateVersionNumber";class RealtimeHandler{constructor(e,t,i,s,n,a,r,o,c,l){this.firebaseInstallations=e,this.storage=t,this.sdkVersion=i,this.namespace=s,this.projectId=n,this.apiKey=a,this.appId=r,this.logger=o,this.storageCache=c,this.cachingClient=l,this.observers=new Set,this.isConnectionActive=!1,this.isRealtimeDisabled=!1,this.httpRetriesRemaining=8,this.isInBackground=!1,this.decoder=new TextDecoder("utf-8"),this.isClosingConnection=!1,this.propagateError=e=>this.observers.forEach((t=>t.error?.(e))),this.isStatusCodeRetryable=e=>!e||[408,429,502,503,504].includes(e),this.setRetriesRemaining(),VisibilityMonitor.getInstance().on("visible",this.onVisibilityChange,this)}async setRetriesRemaining(){const e=await this.storage.getRealtimeBackoffMetadata(),t=e?.numFailedStreams||0;this.httpRetriesRemaining=Math.max(8-t,1)}async updateBackoffMetadataWithLastFailedStreamConnectionTime(e){const t=((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams||0)+1,i=calculateBackoffMillis(t,6e4,2);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(e.getTime()+i),numFailedStreams:t})}async updateBackoffMetadataWithRetryInterval(e){const t=Date.now(),i=new Date(t+1e3*e);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:i,numFailedStreams:0}),await this.retryHttpConnectionWhenBackoffEnds()}async closeRealtimeHttpConnection(){if(!this.isClosingConnection){this.isClosingConnection=!0;try{this.reader&&await this.reader.cancel()}catch(e){this.logger.debug("Failed to cancel the reader, connection was lost.")}finally{this.reader=void 0}this.controller&&(await this.controller.abort(),this.controller=void 0),this.isClosingConnection=!1}}async resetRealtimeBackoff(){await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(-1),numFailedStreams:0})}resetRetryCount(){this.httpRetriesRemaining=8}async establishRealtimeConnection(e,t,i,s){const n=await this.storage.getActiveConfigEtag(),a=await this.storage.getActiveConfigTemplateVersion(),r={[V]:this.apiKey,[$]:i,"Content-Type":"application/json",Accept:"application/json","If-None-Match":n||"*","Content-Encoding":"gzip"},o={project:this.projectId,namespace:this.namespace,lastKnownVersionNumber:a,appId:this.appId,sdkVersion:this.sdkVersion,appInstanceId:t};return await fetch(e,{method:"POST",headers:r,body:JSON.stringify(o),signal:s})}getRealtimeUrl(){const e=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfigrealtime.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=${this.apiKey}`;return new URL(e)}async createRealtimeConnection(){const[e,t]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken(!1)]);this.controller=new AbortController;const i=this.getRealtimeUrl();return await this.establishRealtimeConnection(i,e,t,this.controller.signal)}async retryHttpConnectionWhenBackoffEnds(){let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=new Date(e.backoffEndTimeMillis).getTime(),i=Date.now(),s=Math.max(0,t-i);await this.makeRealtimeHttpConnection(s)}setIsHttpConnectionRunning(e){this.isConnectionActive=e}checkAndSetHttpConnectionFlagIfNotRunning(){const e=this.canEstablishStreamConnection();return e&&this.setIsHttpConnectionRunning(!0),e}fetchResponseIsUpToDate(e,t){return null!=e.config&&e.templateVersion?e.templateVersion>=t:"success"===this.storageCache.getLastFetchStatus()}parseAndValidateConfigUpdateMessage(e){const t=e.indexOf("{"),i=e.indexOf("}",t);return t<0||i<0||t>=i?"":e.substring(t,i+1)}isEventListenersEmpty(){return 0===this.observers.size}getRandomInt(e){return Math.floor(Math.random()*e)}executeAllListenerCallbacks(e){this.observers.forEach((t=>t.next(e)))}getChangedParams(e,t,i,s){const n=new Set,a=new Set(Object.keys(e||{})),r=new Set(Object.keys(t||{})),o=i.experiments||[],c=s?.experiments||[],l=this.createExperimentsMap(o),g=this.createExperimentsMap(c);for(const i of a){if(r.has(i)&&e[i]===t[i]||n.add(i),l.has(i)!==g.has(i)){n.add(i);continue}const s=l.get(i),a=g.get(i);s&&a&&!this.areExperimentsEqual(s,a)&&n.add(i)}for(const e of r)a.has(e)||n.add(e);return n}areExperimentsEqual(e,t){return e.experimentId===t.experimentId&&e.variantId===t.variantId&&e.timeToLiveMillis===t.timeToLiveMillis&&e.triggerTimeoutMillis===t.triggerTimeoutMillis}createExperimentsMap(e){const t=new Map;for(const i of e)if(i.affectedParameterKeys&&!i.experimentId.startsWith("_exp_rollout"))for(const e of i.affectedParameterKeys)t.set(e,i);return t}async fetchLatestConfig(e,t){const i=e-1,s=3-i,n=this.storageCache.getCustomSignals();n&&this.logger.debug(`Fetching config with custom signals: ${JSON.stringify(n)}`);const a=new RemoteConfigAbortSignal;try{const e={cacheMaxAgeMillis:0,signal:a,customSignals:n,fetchType:"REALTIME",fetchAttempt:s},r=await this.storage.getLastSuccessfulFetchResponse(),o=await this.cachingClient.fetch(e);let c=await this.storage.getActiveConfig();if(!this.fetchResponseIsUpToDate(o,t))return this.logger.debug("Fetched template version is the same as SDK's current version. Retrying fetch."),void await this.autoFetch(i,t);if(null==o.config)return void this.logger.debug("The fetch succeeded, but the backend had no updates.");null==c&&(c={});const l=this.getChangedParams(o.config,c,o,r);if(0===l.size)return void this.logger.debug("Config was fetched, but no params changed.");const g={getUpdatedKeys:()=>new Set(l)};this.executeAllListenerCallbacks(g)}catch(e){const t=e instanceof Error?e.message:String(e),i=O.create("update-not-fetched",{originalErrorMessage:`Failed to auto-fetch config update: ${t}`});this.propagateError(i)}}async autoFetch(e,t){if(0===e){const e=O.create("update-not-fetched",{originalErrorMessage:"Unable to fetch the latest version of the template."});return void this.propagateError(e)}const i=1e3*this.getRandomInt(4);await new Promise((e=>setTimeout(e,i))),await this.fetchLatestConfig(e,t)}async handleNotifications(e){let t,i="";for(;;){const{done:s,value:n}=await e.read();if(s)break;if(t=this.decoder.decode(n,{stream:!0}),i+=t,t.includes("}")){if(i=this.parseAndValidateConfigUpdateMessage(i),0===i.length)continue;try{const e=JSON.parse(i);if(this.isEventListenersEmpty())break;if(j in e&&!0===e[j]){const e=O.create("realtime-unavailable",{originalErrorMessage:"The server is temporarily unavailable. Try again in a few minutes."});this.propagateError(e);break}if(U in e){const t=await this.storage.getActiveConfigTemplateVersion(),i=Number(e[U]);t&&i>t&&await this.autoFetch(3,i)}if(q in e){const t=Number(e[q]);await this.updateBackoffMetadataWithRetryInterval(t)}}catch(e){this.logger.debug("Unable to parse latest config update message.",e);const t=e instanceof Error?e.message:String(e);this.propagateError(O.create("update-message-invalid",{originalErrorMessage:t}))}i=""}}}async listenForNotifications(e){try{await this.handleNotifications(e)}catch(e){this.isInBackground||this.logger.debug("Real-time connection was closed due to an exception.")}}async prepareAndBeginRealtimeHttpStream(){if(!this.checkAndSetHttpConnectionFlagIfNotRunning())return;let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=e.backoffEndTimeMillis.getTime();if(Date.now()<t)return void await this.retryHttpConnectionWhenBackoffEnds();let i,s;try{if(i=await this.createRealtimeConnection(),s=i.status,i.ok&&i.body){this.resetRetryCount(),await this.resetRealtimeBackoff();const e=i.body.getReader();this.reader=e,await this.listenForNotifications(e)}}catch(e){this.isInBackground?this.resetRetryCount():this.logger.debug("Exception connecting to real-time RC backend. Retrying the connection...:",e)}finally{await this.closeRealtimeHttpConnection(),this.setIsHttpConnectionRunning(!1);const e=!this.isInBackground&&(void 0===s||this.isStatusCodeRetryable(s));if(e&&await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date),e||i?.ok)await this.retryHttpConnectionWhenBackoffEnds();else{const e=`Unable to connect to the server. HTTP status code: ${s}`,t=O.create("stream-error",{originalErrorMessage:e});this.propagateError(t)}}}canEstablishStreamConnection(){const e=this.observers.size>0,t=!this.isRealtimeDisabled,i=!this.isConnectionActive,s=!this.isInBackground;return e&&t&&i&&s}async makeRealtimeHttpConnection(e){if(this.canEstablishStreamConnection())if(this.httpRetriesRemaining>0)this.httpRetriesRemaining--,await new Promise((t=>setTimeout(t,e))),this.prepareAndBeginRealtimeHttpStream();else if(!this.isInBackground){const e=O.create("stream-error",{originalErrorMessage:"Unable to connect to the server. Check your connection and try again."});this.propagateError(e)}}async beginRealtime(){this.observers.size>0&&await this.makeRealtimeHttpConnection(0)}addObserver(e){this.observers.add(e),this.beginRealtime()}removeObserver(e){this.observers.has(e)&&this.observers.delete(e)}async onVisibilityChange(e){this.isInBackground=!e,e?e&&await this.beginRealtime():await this.closeRealtimeHttpConnection()}}async function fetchAndActivate(e){return e=getModularInstance(e),await fetchConfig(e),activate(e)}async function isSupported(){if(!isIndexedDBAvailable())return!1;try{return await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let i=!0;const s="validate-browser-context-for-indexeddb-analytics-module",n=self.indexedDB.open(s);n.onsuccess=()=>{n.result.close(),i||self.indexedDB.deleteDatabase(s),e(!0)},n.onupgradeneeded=()=>{i=!1},n.onerror=()=>{t(n.error?.message||"")}}catch(e){t(e)}}))}()}catch(e){return!1}}!function registerRemoteConfig(){t(new Component(B,(function remoteConfigFactory(e,{options:t}){const i=e.getProvider("app").getImmediate(),n=e.getProvider("installations-internal").getImmediate(),a=e.getProvider("analytics-internal"),{projectId:o,apiKey:c,appId:l}=i.options;if(!o)throw O.create("registration-project-id");if(!c)throw O.create("registration-api-key");if(!l)throw O.create("registration-app-id");const g=t?.templateId||"firebase",u=isIndexedDBAvailable()?new IndexedDbStorage(l,i.name,g):new InMemoryStorage,h=new StorageCache(u),d=new Logger(x);d.logLevel=r.ERROR;const f=new RestClient(n,s,g,o,c,l),p=new RetryingClient(f,u),m=new CachingClient(p,u,h,d),w=new RealtimeHandler(n,u,s,g,o,c,l,d,h,m),v=new RemoteConfig(i,m,h,u,d,w,a);return ensureInitialized(v),v}),"PUBLIC").setMultipleInstances(!0)),e(x,P),e(x,P,"esm2020")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,onConfigUpdate,setCustomSignals,setLogLevel};
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
expand_more 13 low-confidence finding(s)
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()})(this,function(){let F=()=>{},r=function(t){var r=[];let n=0;for(let a=0;a<t.length;a++){let e=t.charCodeAt(a);e<128?r[n++]=e:(e<2048?r[n++]=e>>6|192:(55296==(64512&e)&&a+1<t.length&&56320==(64512&t.charCodeAt(a+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++a)),r[n++]=e>>18|240,r[n++]=e>>12&63|128):r[n++]=e>>12|224,r[n++]=e>>6&63|128),r[n++]=63&e|128)}return r},M={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,a=[];for(let h=0;h<r.length;h+=3){var i=r[h],s=h+1<r.length,o=s?r[h+1]:0,c=h+2<r.length,l=c?r[h+2]:0;let e=(15&o)<<2|l>>6,t=63&l;c||(t=64,s)||(e=64),a.push(n[i>>2],n[(3&i)<<4|o>>4],n[e],n[t])}return a.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(r(e),t)},decodeString(r,n){if(this.HAS_NATIVE_SUPPORT&&!n)return atob(r);{var a=this.decodeStringToByteArray(r,n);var i=[];let e=0,t=0;for(;e<a.length;){var s,o,c,l=a[e++];l<128?i[t++]=String.fromCharCode(l):191<l&&l<224?(s=a[e++],i[t++]=String.fromCharCode((31&l)<<6|63&s)):239<l&&l<365?(s=((7&l)<<18|(63&a[e++])<<12|(63&a[e++])<<6|63&a[e++])-65536,i[t++]=String.fromCharCode(55296+(s>>10)),i[t++]=String.fromCharCode(56320+(1023&s))):(o=a[e++],c=a[e++],i[t++]=String.fromCharCode((15&l)<<12|(63&o)<<6|63&c))}return i.join("");return}},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let c=0;c<e.length;){var a=r[e.charAt(c++)],i=c<e.length?r[e.charAt(c)]:0,s=++c<e.length?r[e.charAt(c)]:64,o=++c<e.length?r[e.charAt(c)]:64;if(++c,null==a||null==i||null==s||null==o)throw new z;n.push(a<<2|i>>4),64!==s&&(n.push(i<<4&240|s>>2),64!==o)&&n.push(s<<6&192|o)}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class z extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}function x(e){var t=r(e);return M.encodeByteArray(t,!0)}let H=function(e){return x(e).replace(/\./g,"")},j=function(e){try{return M.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function c(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(var r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=c(e[r],t[r]));return e}function V(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}let $=()=>V().__FIREBASE_DEFAULTS__,W=()=>{var e;return"undefined"!=typeof process&&void 0!==process.env&&(e=process.env.__FIREBASE_DEFAULTS__)?JSON.parse(e):void 0},U=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&j(e[1]);return t&&JSON.parse(t)}},J=()=>{try{return F()||$()||W()||U()}catch(e){console.info("Unable to get __FIREBASE_DEFAULTS__ due to: "+e)}},l=()=>J()?.config;class G{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(r){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof r&&(this.promise.catch(()=>{}),1===r.length?r(e):r(e,t))}}}function K(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}class s extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,s.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,n.prototype.create)}}class n{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var n,r=t[0]||{},a=this.service+"/"+e,i=this.errors[e],i=i?(n=r,i.replace(Y,(e,t)=>{var r=n[t];return null!=r?String(r):`<${t}?>`})):"Error",i=this.serviceName+`: ${i} (${a}).`;return new s(a,i,r)}}let Y=/\{\$([^}]+)}/g;function X(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function h(e,t){if(e!==t){var r,n,a=Object.keys(e),i=Object.keys(t);for(r of a){if(!i.includes(r))return;var s=e[r],o=t[r];if(q(s)&&q(o)){if(!h(s,o))return}else if(s!==o)return}for(n of i)if(!a.includes(n))return}return 1}function q(e){return null!==e&&"object"==typeof e}function Z(e,t){var r=new Q(e,t);return r.subscribe.bind(r)}class Q{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(()=>{e(this)}).catch(e=>{this.error(e)})}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(void 0===e&&void 0===t&&void 0===r)throw new Error("Missing Observer.");void 0===(n=((e,t)=>{if("object"==typeof e&&null!==e)for(var r of t)if(r in e&&"function"==typeof e[r])return 1})(e,["next","error","complete"])?e:{next:e,error:t,complete:r}).next&&(n.next=i),void 0===n.error&&(n.error=i),void 0===n.complete&&(n.complete=i);var a=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?n.error(this.finalError):n.complete()}catch(e){}}),this.observers.push(n),a}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount)&&void 0!==this.onNoObservers&&this.onNoObservers(this)}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function i(){}class o{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let a="[DEFAULT]";class ee{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){var r=new G;if(this.instancesDeferred.set(t,r),this.isInitialized(t)||this.shouldAutoInitialize())try{var n=this.getOrInitializeService({instanceIdentifier:t});n&&r.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(e?.identifier),r=e?.optional??!1;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:a})}catch(e){}for(var[t,r]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var n=this.getOrInitializeService({instanceIdentifier:t});r.resolve(n)}catch(e){}}}}clearInstance(e=a){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){var e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=a){return this.instances.has(e)}getOptions(e=a){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,r=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(r))throw Error(this.name+`(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var n,a,i=this.getOrInitializeService({instanceIdentifier:r,options:t});for([n,a]of this.instancesDeferred.entries())r===this.normalizeInstanceIdentifier(n)&&a.resolve(i);return i}onInit(e,t){var r=this.normalizeInstanceIdentifier(t);let n=this.onInitCallbacks.get(r)??new Set;n.add(e),this.onInitCallbacks.set(r,n);var a=this.instances.get(r);return a&&e(a,r),()=>{n.delete(e)}}invokeOnInitCallbacks(e,t){var r=this.onInitCallbacks.get(t);if(r)for(var n of r)try{n(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:(n=e)===a?void 0:n,options:t}),this.instances.set(e,r),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r)}catch{}var n;return r||null}normalizeInstanceIdentifier(e=a){return!this.component||this.component.multipleInstances?e:a}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class te{constructor(e){this.name=e,this.providers=new Map}addComponent(e){var t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with `+this.name);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){var t;return this.providers.has(e)?this.providers.get(e):(t=new ee(e,this),this.providers.set(e,t),t)}getProviders(){return Array.from(this.providers.values())}}let d=[];var p,u;(e=p=p||{})[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT";let re={debug:p.DEBUG,verbose:p.VERBOSE,info:p.INFO,warn:p.WARN,error:p.ERROR,silent:p.SILENT},ne=p.INFO,ae={[p.DEBUG]:"log",[p.VERBOSE]:"log",[p.INFO]:"info",[p.WARN]:"warn",[p.ERROR]:"error"},ie=(e,t,...r)=>{if(!(t<e.logLevel)){var n=(new Date).toISOString(),a=ae[t];if(!a)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[a](`[${n}] ${e.name}:`,...r)}};class se{constructor(e){this.name=e,this._logLevel=ne,this._logHandler=ie,this._userLogHandler=null,d.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in p))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?re[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,p.DEBUG,...e),this._logHandler(this,p.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,p.VERBOSE,...e),this._logHandler(this,p.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,p.INFO,...e),this._logHandler(this,p.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,p.WARN,...e),this._logHandler(this,p.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,p.ERROR,...e),this._logHandler(this,p.ERROR,...e)}}let oe=(t,e)=>e.some(e=>t instanceof e),ce,le;let he=new WeakMap,f=new WeakMap,de=new WeakMap,g=new WeakMap,b=new WeakMap;let m={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return f.get(e);if("objectStoreNames"===t)return e.objectStoreNames||de.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return v(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function pe(n){return n!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(le=le||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(n)?function(...e){return n.apply(_(this),e),v(he.get(this))}:function(...e){return v(n.apply(_(this),e))}:function(e,...t){var r=n.call(_(this),e,...t);return de.set(r,e.sort?e.sort():[e]),v(r)}}function ue(e){var i,t;return"function"==typeof e?pe(e):(e instanceof IDBTransaction&&(i=e,f.has(i)||(t=new Promise((e,t)=>{let r=()=>{i.removeEventListener("complete",n),i.removeEventListener("error",a),i.removeEventListener("abort",a)},n=()=>{e(),r()},a=()=>{t(i.error||new DOMException("AbortError","AbortError")),r()};i.addEventListener("complete",n),i.addEventListener("error",a),i.addEventListener("abort",a)}),f.set(i,t))),oe(e,ce=ce||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,m):e)}function v(e){var i,t;return e instanceof IDBRequest?(i=e,(t=new Promise((e,t)=>{let r=()=>{i.removeEventListener("success",n),i.removeEventListener("error",a)},n=()=>{e(v(i.result)),r()},a=()=>{t(i.error),r()};i.addEventListener("success",n),i.addEventListener("error",a)})).then(e=>{e instanceof IDBCursor&&he.set(e,i)}).catch(()=>{}),b.set(t,i),t):g.has(e)?g.get(e):((t=ue(e))!==e&&(g.set(e,t),b.set(t,e)),t)}let _=e=>b.get(e);let fe=["get","getKey","getAll","getAllKeys","count"],ge=["put","add","delete","clear"],y=new Map;function be(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(y.get(t))return y.get(t);let a=t.replace(/FromIndex$/,""),i=t!==a,s=ge.includes(a);var r;return a in(i?IDBIndex:IDBObjectStore).prototype&&(s||fe.includes(a))?(r=async function(e,...t){var r=this.transaction(e,s?"readwrite":"readonly");let n=r.store;return i&&(n=n.index(t.shift())),(await Promise.all([n[a](...t),s&&r.done]))[0]},y.set(t,r),r):void 0}}m={...u=m,get:(e,t,r)=>be(e,t)||u.get(e,t,r),has:(e,t)=>!!be(e,t)||u.has(e,t)};class me{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{var t;return"VERSION"===e.getComponent()?.type?(t=e.getImmediate()).library+"/"+t.version:null}).filter(e=>e).join(" ")}}let E="@firebase/app",C="0.15.0",w=new se("@firebase/app");var e;let I="[DEFAULT]",ve={"@firebase/app":"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/data-connect":"fire-data-connect","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","@firebase/ai":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},D=new Map,S=new Map,A=new Map;function O(t,r){try{t.container.addComponent(r)}catch(e){w.debug(`Component ${r.name} failed to register with FirebaseApp `+t.name,e)}}function _e(e,t){e.container.addOrOverwriteComponent(t)}function N(e){var t,r,n=e.name;if(A.has(n))return w.debug(`There were multiple attempts to register component ${n}.`),!1;A.set(n,e);for(t of D.values())O(t,e);for(r of S.values())O(r,e);return!0}function ye(e,t){var r=e.container.getProvider("heartbeat").getImmediate({optional:!0});return r&&r.triggerHeartbeat(),e.container.getProvider(t)}function L(e){return void 0!==e.options}function Ee(e){return!L(e)&&("authIdToken"in e||"appCheckToken"in e||"releaseOnDeref"in e||"automaticDataCollectionEnabled"in e)}let B=new n("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."});class Ce{constructor(e,t,r){this._isDeleted=!1,this._options={...e},this._config={...t},this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new o("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw B.create("app-deleted",{appName:this._name})}}function we(e,t){var r=j(e.split(".")[1]);null===r?console.error(`FirebaseServerApp ${t} is invalid: second part could not be parsed.`):void 0===JSON.parse(r).exp?console.error(`FirebaseServerApp ${t} is invalid: expiration claim could not be parsed`):1e3*JSON.parse(r).exp-(new Date).getTime()<=0&&console.error(`FirebaseServerApp ${t} is invalid: the token has expired.`)}class Ie extends Ce{constructor(e,t,r,n){var a=void 0===t.automaticDataCollectionEnabled||t.automaticDataCollectionEnabled,i={name:r,automaticDataCollectionEnabled:a};void 0!==e.apiKey?super(e,i,n):super(e.options,i,n),this._serverConfig={automaticDataCollectionEnabled:a,...t},this._serverConfig.authIdToken&&we(this._serverConfig.authIdToken,"authIdToken"),this._serverConfig.appCheckToken&&we(this._serverConfig.appCheckToken,"appCheckToken"),this._finalizationRegistry=null,"undefined"!=typeof FinalizationRegistry&&(this._finalizationRegistry=new FinalizationRegistry(()=>{this.automaticCleanup()})),this._refCount=0,this.incRefCount(this._serverConfig.releaseOnDeref),this._serverConfig.releaseOnDeref=void 0,t.releaseOnDeref=void 0,k(E,C,"serverapp")}toJSON(){}get refCount(){return this._refCount}incRefCount(e){this.isDeleted||(this._refCount++,void 0!==e&&null!==this._finalizationRegistry&&this._finalizationRegistry.register(e,this))}decRefCount(){return this.isDeleted?0:--this._refCount}automaticCleanup(){t(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw B.create("server-app-deleted")}}let De="12.15.0";function T(e,t={}){let r=e;if("object"!=typeof t){let e=t;t={name:e}}var n={name:I,automaticDataCollectionEnabled:!0,...t};let a=n.name;if("string"!=typeof a||!a)throw B.create("bad-app-name",{appName:String(a)});if(!(r=r||l()))throw B.create("no-options");var i=D.get(a);if(i){if(h(r,i.options)&&h(n,i.config))return i;throw B.create("duplicate-app",{appName:a})}var s,o=new te(a);for(s of A.values())o.addComponent(s);i=new Ce(r,n,o);return D.set(a,i),i}async function t(e){let t=!1;var r=e.name;D.has(r)?(t=!0,D.delete(r)):S.has(r)&&e.decRefCount()<=0&&(S.delete(r),t=!0),t&&(await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function k(e,t,r){let n=ve[e]??e;r&&(n+="-"+r);var a,i=n.match(/\s|\//),s=t.match(/\s|\//);i||s?(a=[`Unable to register library "${n}" with version "${t}":`],i&&a.push(`library name "${n}" contains illegal characters (whitespace or "/")`),i&&s&&a.push("and"),s&&a.push(`version name "${t}" contains illegal characters (whitespace or "/")`),w.warn(a.join(" "))):N(new o(n+"-version",()=>({library:n,version:t}),"VERSION"))}function Se(e,t){if(null!==e&&"function"!=typeof e)throw B.create("invalid-log-argument");var r,i=e,n=t;for(r of d){let a=null;n&&n.level&&(a=re[n.level]),r.userLogHandler=null===i?null:(e,t,...r)=>{var n=r.map(e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}}).filter(e=>e).join(" ");t>=(a??e.logLevel)&&i({level:p[t].toLowerCase(),message:n,args:r,type:e.name})}}}function Ae(e){var t;t=e,d.forEach(e=>{e.setLogLevel(t)})}let Oe="firebase-heartbeat-database",Ne=1,R="firebase-heartbeat-store",Le=null;function Be(){return Le=Le||((e,t,{blocked:r,upgrade:n,blocking:a,terminated:i})=>{let s=indexedDB.open(e,t);var o=v(s);return n&&s.addEventListener("upgradeneeded",e=>{n(v(s.result),e.oldVersion,e.newVersion,v(s.transaction),e)}),r&&s.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),o.then(e=>{i&&e.addEventListener("close",()=>i()),a&&e.addEventListener("versionchange",e=>a(e.oldVersion,e.newVersion,e))}).catch(()=>{}),o})(Oe,Ne,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(R)}catch(e){console.warn(e)}}}).catch(e=>{throw B.create("idb-open",{originalErrorMessage:e.message})})}async function Te(e,t){try{var r=(await Be()).transaction(R,"readwrite");await r.objectStore(R).put(t,ke(e)),await r.done}catch(e){e instanceof s?w.warn(e.message):(r=B.create("idb-set",{originalErrorMessage:e?.message}),w.warn(r.message))}}function ke(e){return e.name+"!"+e.options.appId}class Re{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new Fe(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){try{var e,r=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString();let t=Pe();if(null!=this._heartbeatsCache?.heartbeats||(this._heartbeatsCache=await this._heartbeatsCachePromise,null!=this._heartbeatsCache?.heartbeats))if(this._heartbeatsCache.lastSentHeartbeatDate!==t&&!this._heartbeatsCache.heartbeats.some(e=>e.date===t))return this._heartbeatsCache.heartbeats.push({date:t,agent:r}),30<this._heartbeatsCache.heartbeats.length&&(e=(e=>{if(0===e.length)return-1;let t=0,r=e[0].date;for(let n=1;n<e.length;n++)e[n].date<r&&(r=e[n].date,t=n);return t})(this._heartbeatsCache.heartbeats),this._heartbeatsCache.heartbeats.splice(e,1)),this._storage.overwrite(this._heartbeatsCache)}catch(e){w.warn(e)}}async getHeartbeatsHeader(){try{var e,t,r,n;return(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==this._heartbeatsCache?.heartbeats||0===this._heartbeatsCache.heartbeats.length)?"":(e=Pe(),{heartbeatsToSend:t,unsentEntries:r}=((e,t=1024)=>{let r=[],n=e.slice();for(let i of e){var a=r.find(e=>e.agent===i.agent);if(a){if(a.dates.push(i.date),Me(r)>t){a.dates.pop();break}}else if(r.push({agent:i.agent,dates:[i.date]}),Me(r)>t){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}})(this._heartbeatsCache.heartbeats),n=H(JSON.stringify({version:2,heartbeats:t})),this._heartbeatsCache.lastSentHeartbeatDate=e,0<r.length?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),n)}catch(e){return w.warn(e),""}}}function Pe(){return(new Date).toISOString().substring(0,10)}class Fe{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!(()=>{try{return"object"==typeof indexedDB}catch(e){}})()&&new Promise((n,a)=>{try{let e=!0,t="validate-browser-context-for-indexeddb-analytics-module",r=self.indexedDB.open(t);r.onsuccess=()=>{r.result.close(),e||self.indexedDB.deleteDatabase(t),n(!0)},r.onupgradeneeded=()=>{e=!1},r.onerror=()=>{a(r.error?.message||"")}}catch(e){a(e)}}).then(()=>!0).catch(()=>!1)}async read(){var e;return await this._canUseIndexedDBPromise&&(e=await(async e=>{try{var t=(await Be()).transaction(R),r=await t.objectStore(R).get(ke(e));return await t.done,r}catch(e){e instanceof s?w.warn(e.message):(t=B.create("idb-get",{originalErrorMessage:e?.message}),w.warn(t.message))}})(this.app))?.heartbeats?e:{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise)return t=await this.read(),Te(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??t.lastSentHeartbeatDate,heartbeats:e.heartbeats})}async add(e){var t;if(await this._canUseIndexedDBPromise)return t=await this.read(),Te(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??t.lastSentHeartbeatDate,heartbeats:[...t.heartbeats,...e.heartbeats]})}}function Me(e){return H(JSON.stringify({version:2,heartbeats:e})).length}e="",N(new o("platform-logger",e=>new me(e),"PRIVATE")),N(new o("heartbeat",e=>new Re(e),"PRIVATE")),k(E,C,e),k(E,C,"esm2020"),k("fire-js","");var ze=Object.freeze({__proto__:null,SDK_VERSION:De,_DEFAULT_ENTRY_NAME:I,_addComponent:O,_addOrOverwriteComponent:_e,_apps:D,_clearComponents:function(){A.clear()},_components:A,_getProvider:ye,_isFirebaseApp:L,_isFirebaseServerApp:function(e){return null!=e&&void 0!==e.settings},_isFirebaseServerAppSettings:Ee,_registerComponent:N,_removeServiceInstance:function(e,t,r=I){ye(e,t).clearInstance(r)},_serverApps:S,deleteApp:t,getApp:function(e=I){var t=D.get(e);if(!t&&e===I&&l())return T();if(t)return t;throw B.create("no-app",{appName:e})},getApps:function(){return Array.from(D.values())},initializeApp:T,initializeServerApp:function(e,t={}){if(("undefined"!=typeof window||K())&&!K())throw B.create("invalid-server-app-environment");let r,n=t||{};if(e&&(L(e)?r=e.options:Ee(e)?n=e:r=e),void 0===n.automaticDataCollectionEnabled&&(n.automaticDataCollectionEnabled=!0),!(r=r||l()))throw B.create("no-options");var a={...n,...r};if(void 0!==a.releaseOnDeref&&delete a.releaseOnDeref,void 0!==n.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw B.create("finalization-registry-not-supported",{});var a=""+[...JSON.stringify(a)].reduce((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0,0),i=S.get(a);if(i)i.incRefCount(n.releaseOnDeref);else{var s,o=new te(a);for(s of A.values())o.addComponent(s);i=new Ie(r,n,a,o),S.set(a,i)}return i},onLog:Se,registerVersion:k,setLogLevel:Ae,FirebaseError:s});class xe{constructor(e,t){this._delegate=e,this.firebase=t,O(e,new o("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),t(this._delegate)))}_getService(e,t=I){this._delegate.checkDestroyed();var r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==r.getComponent()?.instantiationMode||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=I){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){O(this._delegate,e)}_addOrOverwriteComponent(e){_e(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}let He=new n("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});function je(a){let i={},s={__esModule:!0,initializeApp:function(e,t={}){var r=T(e,t);if(X(i,r.name))return i[r.name];var n=new a(r,s);return i[r.name]=n},app:o,registerVersion:k,setLogLevel:Ae,onLog:Se,apps:null,SDK_VERSION:De,INTERNAL:{registerComponent:function(t){let r=t.name,n=r.replace("-compat","");{var e;N(t)&&"PUBLIC"===t.type&&(e=(e=o())=>{if("function"!=typeof e[n])throw He.create("invalid-app-argument",{appName:r});return e[n]()},void 0!==t.serviceProps&&c(e,t.serviceProps),s[n]=e,a.prototype[n]=function(...e){return this._getService.bind(this,r).apply(this,t.multipleInstances?e:[])})}return"PUBLIC"===t.type?s[n]:null},removeApp:function(e){delete i[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var r=t;return r},modularAPIs:ze}};function o(e){if(e=e||I,X(i,e))return i[e];throw He.create("no-app",{appName:e})}return s.default=s,Object.defineProperty(s,"apps",{get:function(){return Object.keys(i).map(e=>i[e])}}),o.App=a,s}var Ve=function e(){let t=je(xe);return t.INTERNAL={...t.INTERNAL,createFirebaseNamespace:e,extendNamespace:function(e){c(t,e)},createSubscribe:Z,ErrorFactory:n,deepExtend:c},t}(),$e=new se("@firebase/app-compat");try{var We,P=V();void 0!==P.firebase&&($e.warn(`
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(qn,Bn){try{!(function(){function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var V=t(qn);let r=()=>{},x={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var i=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let d=0;d<r.length;d+=3){var s=r[d],a=d+1<r.length,o=a?r[d+1]:0,c=d+2<r.length,l=c?r[d+2]:0;let e=(15&o)<<2|l>>6,t=63&l;c||(t=64,a)||(e=64),n.push(i[s>>2],i[(3&s)<<4|o>>4],i[e],i[t])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray((t=>{var r=[];let i=0;for(let n=0;n<t.length;n++){let e=t.charCodeAt(n);e<128?r[i++]=e:(e<2048?r[i++]=e>>6|192:(55296==(64512&e)&&n+1<t.length&&56320==(64512&t.charCodeAt(n+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++n)),r[i++]=e>>18|240,r[i++]=e>>12&63|128):r[i++]=e>>12|224,r[i++]=e>>6&63|128),r[i++]=63&e|128)}return r})(e),t)},decodeString(r,i){if(this.HAS_NATIVE_SUPPORT&&!i)return atob(r);{var n=this.decodeStringToByteArray(r,i);var s=[];let e=0,t=0;for(;e<n.length;){var a,o,c,l=n[e++];l<128?s[t++]=String.fromCharCode(l):191<l&&l<224?(a=n[e++],s[t++]=String.fromCharCode((31&l)<<6|63&a)):239<l&&l<365?(a=((7&l)<<18|(63&n[e++])<<12|(63&n[e++])<<6|63&n[e++])-65536,s[t++]=String.fromCharCode(55296+(a>>10)),s[t++]=String.fromCharCode(56320+(1023&a))):(o=n[e++],c=n[e++],s[t++]=String.fromCharCode((15&l)<<12|(63&o)<<6|63&c))}return s.join("");return}},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_,i=[];for(let c=0;c<e.length;){var n=r[e.charAt(c++)],s=c<e.length?r[e.charAt(c)]:0,a=++c<e.length?r[e.charAt(c)]:64,o=++c<e.length?r[e.charAt(c)]:64;if(++c,null==n||null==s||null==a||null==o)throw new W;i.push(n<<2|s>>4),64!==a&&(i.push(s<<4&240|a>>2),64!==o)&&i.push(a<<6&192|o)}return i},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class W extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}let H=function(e){try{return x.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};let j=()=>(()=>{if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")})().__FIREBASE_DEFAULTS__,q=()=>{var e;return"undefined"!=typeof process&&void 0!==process.env&&(e=process.env.__FIREBASE_DEFAULTS__)?JSON.parse(e):void 0},B=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&H(e[1]);return t&&JSON.parse(t)}},z=()=>{try{return r()||j()||q()||B()}catch(e){console.info("Unable to get __FIREBASE_DEFAULTS__ due to: "+e)}};var i;class G{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(r){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof r&&(this.promise.catch(()=>{}),1===r.length?r(e):r(e,t))}}}function l(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function K(){var e=z()?.forceEnvironment;if("node"===e)return!0;if("browser"===e)return!1;try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function J(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function Y(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function $(){var e=l();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function X(){try{return"object"==typeof indexedDB}catch(e){return!1}}class d extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,d.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Q.prototype.create)}}class Q{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var i,r=t[0]||{},n=this.service+"/"+e,s=this.errors[e],s=s?(i=r,s.replace(Z,(e,t)=>{var r=i[t];return null!=r?String(r):`<${t}?>`})):"Error",s=this.serviceName+`: ${s} (${n}).`;return new d(n,s,r)}}let Z=/\{\$([^}]+)}/g;function ee(e,t){if(e!==t){var r,i,n=Object.keys(e),s=Object.keys(t);for(r of n){if(!s.includes(r))return!1;var a=e[r],o=t[r];if(te(a)&&te(o)){if(!ee(a,o))return!1}else if(a!==o)return!1}for(i of s)if(!n.includes(i))return!1}return!0}function te(e){return null!==e&&"object"==typeof e}function re(e){let t=[];for(let[r,i]of Object.entries(e))Array.isArray(i)?i.forEach(e=>{t.push(encodeURIComponent(r)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(r)+"="+encodeURIComponent(i));return t.length?"&"+t.join("&"):""}function ie(e){let i={};return e.replace(/^\?/,"").split("&").forEach(e=>{var t,r;e&&([t,r]=e.split("="),i[decodeURIComponent(t)]=decodeURIComponent(r))}),i}function ne(e){var t,r=e.indexOf("?");return r?(t=e.indexOf("#",r),e.substring(r,0<t?t:void 0)):""}class se{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(()=>{e(this)}).catch(e=>{this.error(e)})}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let i;if(void 0===e&&void 0===t&&void 0===r)throw new Error("Missing Observer.");void 0===(i=((e,t)=>{if("object"==typeof e&&null!==e)for(var r of t)if(r in e&&"function"==typeof e[r])return 1})(e,["next","error","complete"])?e:{next:e,error:t,complete:r}).next&&(i.next=ae),void 0===i.error&&(i.error=ae),void 0===i.complete&&(i.complete=ae);var n=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch(e){}}),this.observers.push(i),n}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount)&&void 0!==this.onNoObservers&&this.onNoObservers(this)}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function ae(){}function a(e){return e&&e._delegate?e._delegate:e}function oe(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{}}(e=i=i||{})[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT";let ce={debug:i.DEBUG,verbose:i.VERBOSE,info:i.INFO,warn:i.WARN,error:i.ERROR,silent:i.SILENT},le=i.INFO,de={[i.DEBUG]:"log",[i.VERBOSE]:"log",[i.INFO]:"info",[i.WARN]:"warn",[i.ERROR]:"error"},he=(e,t,...r)=>{if(!(t<e.logLevel)){var i=(new Date).toISOString(),n=de[t];if(!n)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[n](`[${i}] ${e.name}:`,...r)}};class ue{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let pe={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},me={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function ge(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}function fe(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registered for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is incorrect, malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-password":"A non-empty password must be provided","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.","missing-recaptcha-token":"The reCAPTCHA token is missing when sending request to the backend.","invalid-recaptcha-token":"The reCAPTCHA token is invalid when sending request to the backend.","invalid-recaptcha-action":"The reCAPTCHA action is invalid when sending request to the backend.","recaptcha-not-enabled":"reCAPTCHA Enterprise integration is not enabled for this project.","missing-client-type":"The reCAPTCHA client type is missing when sending request to the backend.","missing-recaptcha-version":"The reCAPTCHA version is missing when sending request to the backend.","invalid-req-type":"Invalid request parameters.","invalid-recaptcha-version":"The reCAPTCHA version is invalid when sending request to the backend.","unsupported-password-policy-schema-version":"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.","password-does-not-meet-requirements":"The password does not meet the requirements.","invalid-hosting-link-domain":"The provided Hosting link domain is not configured in Firebase Hosting or is not owned by the current project. This cannot be a default Hosting domain (`web.app` or `firebaseapp.com`)."}}let ve=ge,_e=new Q("auth","Firebase",ge()),ye=new class{constructor(e){this.name=e,this._logLevel=le,this._logHandler=he,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in i))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?ce[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,i.DEBUG,...e),this._logHandler(this,i.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,i.VERBOSE,...e),this._logHandler(this,i.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,i.INFO,...e),this._logHandler(this,i.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,i.WARN,...e),this._logHandler(this,i.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,i.ERROR,...e),this._logHandler(this,i.ERROR,...e)}}("@firebase/auth");function Ie(e,...t){ye.logLevel<=i.ERROR&&ye.error(`Auth (${Bn.SDK_VERSION}): `+e,...t)}function h(e,...t){throw Ee(e,...t)}function u(e,...t){return Ee(e,...t)}function we(e,t,r){var i={...ve(),[t]:r};return new Q("auth","Firebase",i).create(t,{appName:e.name})}function c(e){return we(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Te(e,t,r){var i=r;if(!(t instanceof i))throw i.name!==t.constructor.name&&h(e,"argument-error"),we(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function Ee(e,...t){var r,i;return"string"!=typeof e?(r=t[0],(i=[...t.slice(1)])[0]&&(i[0].appName=e.name),e._errorFactory.create(r,...i)):_e.create(e,...t)}function g(e,t,...r){if(!e)throw Ee(t,...r)}function n(e){var t="INTERNAL ASSERTION FAILED: "+e;throw Ie(t),new Error(t)}function o(e,t){e||n(t)}function be(){return"undefined"!=typeof self&&self.location?.href||""}function ke(){return"http:"===Se()||"https:"===Se()}function Se(){return"undefined"!=typeof self&&self.location?.protocol||null}class Re{constructor(e,t){o((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile="undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(l())||Y()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(ke()||J()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function Ae(e,t){o(e.emulator,"Emulator should always be set here");var r=e.emulator.url;return t?""+r+(t.startsWith("/")?t.slice(1):t):r}class Pe{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){return this.fetchImpl||("undefined"!=typeof self&&"fetch"in self?self.fetch:"undefined"!=typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!=typeof fetch?fetch:void n("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static headers(){return this.headersImpl||("undefined"!=typeof self&&"Headers"in self?self.Headers:"undefined"!=typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!=typeof Headers?Headers:void n("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static response(){return this.responseImpl||("undefined"!=typeof self&&"Response"in self?self.Response:"undefined"!=typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!=typeof Response?Response:void n("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}let Ce={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},Ne=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],Oe=new Re(3e4,6e4);function p(e,t){return e.tenantId&&!t.tenantId?{...t,tenantId:e.tenantId}:t}async function m(n,s,a,o,e={}){return Le(n,e,async()=>{let e={},t={};o&&("GET"===s?t=o:e={body:JSON.stringify(o)});var r=re({...t,key:n.config.apiKey}).slice(1),i=await n._getAdditionalHeaders(),i=(i["Content-Type"]="application/json",n.languageCode&&(i["X-Firebase-Locale"]=n.languageCode),{method:s,headers:i,...e});return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||(i.referrerPolicy="strict-origin-when-cross-origin"),n.emulatorConfig&&oe(n.emulatorConfig.host)&&(i.credentials="include"),Pe.fetch()(await De(n,n.config.apiHost,a,r),i)})}async function Le(t,e,r){t._canInitEmulator=!1;var i={...Ce,...e};try{var n=new Me(t),s=await Promise.race([r(),n.promise]),a=(n.clearNetworkTimeout(),await s.json());if("needConfirmation"in a)throw Ue(t,"account-exists-with-different-credential",a);if(s.ok&&!("errorMessage"in a))return a;var[o,c]=(s.ok?a.errorMessage:a.error.message).split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===o)throw Ue(t,"credential-already-in-use",a);if("EMAIL_EXISTS"===o)throw Ue(t,"email-already-in-use",a);if("USER_DISABLED"===o)throw Ue(t,"user-disabled",a);var l=i[o]||o.toLowerCase().replace(/[_\s]+/g,"-");if(c)throw we(t,l,c);h(t,l)}catch(e){if(e instanceof d)throw e;h(t,"network-request-failed",{message:String(e)})}}async function s(e,t,r,i,n={}){var s=await m(e,t,r,i,n);return"mfaPendingCredential"in s&&h(e,"multi-factor-auth-required",{_serverResponse:s}),s}async function De(e,t,r,i){var n=""+t+r+"?"+i,s=e,n=s.config.emulator?Ae(e.config,n):e.config.apiScheme+"://"+n;if(Ne.includes(r)&&(await s._persistenceManagerAvailable,"COOKIE"===s._getPersistenceType()))return s._getPersistence()._getFinalTarget(n).toString();return n}class Me{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(u(this.auth,"network-request-failed")),Oe.get())})}}function Ue(e,t,r){var i={appName:e.name},i=(r.email&&(i.email=r.email),r.phoneNumber&&(i.phoneNumber=r.phoneNumber),u(e,t,i));return i.customData._tokenResponse=r,i}function Fe(e){return void 0!==e&&void 0!==e.getResponse}function Ve(e){return void 0!==e&&void 0!==e.enterprise}class xe{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(t){if(this.recaptchaEnforcementState&&0!==this.recaptchaEnforcementState.length)for(let e of this.recaptchaEnforcementState)if(e.provider&&e.provider===t){switch(e.enforcementState){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}return}return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function We(e,t){return m(e,"GET","/v2/recaptchaConfig",p(e,t))}async function He(e,t){return m(e,"POST","/v1/accounts:lookup",t)}function je(e){if(e)try{var t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function qe(e){return 1e3*Number(e)}function Be(e){var[t,r,i]=e.split(".");if(void 0===t||void 0===r||void 0===i)return Ie("JWT malformed, contained fewer than 3 sections"),null;try{var n=H(r);return n?JSON.parse(n):(Ie("Failed to decode base64 JWT payload"),null)}catch(e){return Ie("Caught error parsing JWT payload as JSON",e?.toString()),null}}function ze(e){var t=Be(e);return g(t,"internal-error"),g(void 0!==t.exp,"internal-error"),g(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function f(t,e,r=!1){if(r)return e;try{return await e}catch(e){throw e instanceof d&&(r=[e.code][0],"auth/user-disabled"===r||"auth/user-token-expired"===r)&&(t.auth.currentUser===t&&await t.auth.signOut()),e}}class Ge{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId)&&clearTimeout(this.timerId)}getInterval(e){var t;return e?(t=this.errorBackoff,this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t):(this.errorBackoff=3e4,t=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5,Math.max(0,t))}schedule(e=!1){var t;this.isRunning&&(t=this.getInterval(e),this.timerId=setTimeout(async()=>{await this.iteration()},t))}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===e?.code&&this.schedule(!0))}this.schedule()}}class Ke{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=je(this.lastLoginAt),this.creationTime=je(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Je(e){var t,r,i=e.auth,n=await e.getIdToken(),n=await f(e,He(i,{idToken:n})),i=(g(n?.users.length,i,"internal-error"),n.users[0]),n=(e._notifyReloadListener(i),i.providerUserInfo?.length?Ye(i.providerUserInfo):[]),n=(t=e.providerData,r=n,[...t.filter(t=>!r.some(e=>e.providerId===t.providerId)),...r]),s=!(e.email&&i.passwordHash||n.length),s=!!e.isAnonymous&&s,n={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:n,metadata:new Ke(i.createdAt,i.lastLoginAt),isAnonymous:s};Object.assign(e,n)}function Ye(e){return e.map(({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null}))}class $e{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){g(e.idToken,"internal-error"),g(void 0!==e.idToken,"internal-error"),g(void 0!==e.refreshToken,"internal-error");var t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):ze(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){g(0!==e.length,"internal-error");var t=ze(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(g(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null):this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){n=t;var i,n,{accessToken:r,refreshToken:s,expiresIn:a}=await{accessToken:(r=await Le(i=e,{},async()=>{var e=re({grant_type:"refresh_token",refresh_token:n}).slice(1),{tokenApiHost:t,apiKey:r}=i.config,t=await De(i,t,"/v1/token","key="+r),r=await i._getAdditionalHeaders(),r=(r["Content-Type"]="application/x-www-form-urlencoded",{method:"POST",headers:r,body:e});return i.emulatorConfig&&oe(i.emulatorConfig.host)&&(r.credentials="include"),Pe.fetch()(t,r)})).access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token};this.updateTokensAndExpiration(r,s,Number(a))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*r}static fromJSON(e,t){var{refreshToken:r,accessToken:i,expirationTime:n}=t,s=new $e;return r&&(g("string"==typeof r,"internal-error",{appName:e}),s.refreshToken=r),i&&(g("string"==typeof i,"internal-error",{appName:e}),s.accessToken=i),n&&(g("number"==typeof n,"internal-error",{appName:e}),s.expirationTime=n),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new $e,this.toJSON())}_performRefresh(){return n("not implemented")}}function v(e,t){g("string"==typeof e||void 0===e,"internal-error",{appName:t})}class _{constructor({uid:e,auth:t,stsTokenManager:r,...i}){this.providerId="firebase",this.proactiveRefresh=new Ge(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new Ke(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await f(this,this.stsTokenManager.getToken(this.auth,e));return g(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return(async(e,t=!1)=>{var r=a(e),i=await r.getIdToken(t),n=Be(i),s=(g(n&&n.exp&&n.auth_time&&n.iat,r.auth,"internal-error"),(r="object"==typeof n.firebase?n.firebase:void 0)?.sign_in_provider);return{claims:n,token:i,authTime:je(qe(n.auth_time)),issuedAtTime:je(qe(n.iat)),expirationTime:je(qe(n.exp)),signInProvider:s||null,signInSecondFactor:r?.sign_in_second_factor||null}})(this,e)}reload(){return(async e=>{var t=a(e);await Je(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)})(this)}_assign(e){this!==e&&(g(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(e=>({...e})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){var t=new _({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){g(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await Je(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e;return Bn._isFirebaseServerApp(this.auth.app)?Promise.reject(c(this.auth)):(e=await this.getIdToken(),await f(this,(async(e,t)=>m(e,"POST","/v1/accounts:delete",t))(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut())}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var r=t.displayName??void 0,i=t.email??void 0,n=t.phoneNumber??void 0,s=t.photoURL??void 0,a=t.tenantId??void 0,o=t._redirectEventId??void 0,c=t.createdAt??void 0,l=t.lastLoginAt??void 0,{uid:d,emailVerified:h,isAnonymous:u,providerData:p,stsTokenManager:m}=t,m=(g(d&&m,e,"internal-error"),$e.fromJSON(this.name,m)),d=(g("string"==typeof d,e,"internal-error"),v(r,e.name),v(i,e.name),g("boolean"==typeof h,e,"internal-error"),g("boolean"==typeof u,e,"internal-error"),v(n,e.name),v(s,e.name),v(a,e.name),v(o,e.name),v(c,e.name),v(l,e.name),new _({uid:d,auth:e,email:i,emailVerified:h,displayName:r,isAnonymous:u,photoURL:s,phoneNumber:n,tenantId:a,stsTokenManager:m,createdAt:c,lastLoginAt:l}));return p&&Array.isArray(p)&&(d.providerData=p.map(e=>({...e}))),o&&(d._redirectEventId=o),d}static async _fromIdTokenResponse(e,t,r=!1){var i=new $e,i=(i.updateFromServerResponse(t),new _({uid:t.localId,auth:e,stsTokenManager:i,isAnonymous:r}));return await Je(i),i}static async _fromGetAccountInfoResponse(e,t,r){var i=t.users[0],n=(g(void 0!==i.localId,"internal-error"),void 0!==i.providerUserInfo?Ye(i.providerUserInfo):[]),s=!(i.email&&i.passwordHash||n?.length),a=new $e,a=(a.updateFromIdToken(r),new _({uid:i.localId,auth:e,stsTokenManager:a,isAnonymous:s})),s={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:n,metadata:new Ke(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash||n?.length)};return Object.assign(a,s),a}}let Xe=new Map;function y(e){o(e instanceof Function,"Expected a class definition");var t=Xe.get(e);return t?o(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Xe.set(e,t)),t}class Qe{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){var t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Qe.type="NONE";let Ze=Qe;function et(e,t,r){return`firebase:${e}:${t}:`+r}class tt{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;var{config:i,name:n}=this.auth;this.fullUserKey=et(this.userKey,i.apiKey,n),this.fullPersistenceKey=et("persistence",i.apiKey,n),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){var e,t=await this.persistence._get(this.fullUserKey);return t?"string"==typeof t?(e=await He(this.auth,{idToken:t}).catch(()=>{}))?_._fromGetAccountInfoResponse(this.auth,e,t):null:_._fromJSON(this.auth,t):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){var t;if(this.persistence!==e)return t=await this.getCurrentUser(),await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(t,e,r="authUser"){if(!e.length)return new tt(y(Ze),t,r);var i,n=(await Promise.all(e.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let s=n[0]||y(Ze),a=et(r,t.config.apiKey,t.name),o=null;for(i of e)try{var c=await i._get(a);if(c){let e;if("string"==typeof c){var l=await He(t,{idToken:c}).catch(()=>{});if(!l)break;e=await _._fromGetAccountInfoResponse(t,l,c)}else e=_._fromJSON(t,c);i!==s&&(o=e),s=i;break}}catch{}n=n.filter(e=>e._shouldAllowMigration);return s._shouldAllowMigration&&n.length&&(s=n[0],o&&await s._set(a,o.toJSON()),await Promise.all(e.map(async e=>{if(e!==s)try{await e._remove(a)}catch{}}))),new tt(s,t,r)}}function rt(e){var t=e.toLowerCase();return t.includes("opera/")||t.includes("opr/")||t.includes("opios/")?"Opera":at(t)?"IEMobile":t.includes("msie")||t.includes("trident/")?"IE":t.includes("edge/")?"Edge":it(t)?"Firefox":t.includes("silk/")?"Silk":ct(t)?"Blackberry":lt(t)?"Webos":nt(t)?"Safari":!t.includes("chrome/")&&!st(t)||t.includes("edge/")?ot(t)?"Android":2===(t=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))?.length?t[1]:"Other":"Chrome"}function it(e=l()){return/firefox\//i.test(e)}function nt(e=l()){var t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function st(e=l()){return/crios\//i.test(e)}function at(e=l()){return/iemobile/i.test(e)}function ot(e=l()){return/android/i.test(e)}function ct(e=l()){return/blackberry/i.test(e)}function lt(e=l()){return/webos/i.test(e)}function dt(e=l()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function ht(e=l()){return dt(e)||ot(e)||lt(e)||ct(e)||/windows phone/i.test(e)||at(e)}function ut(e,t=[]){let r;switch(e){case"Browser":r=rt(l());break;case"Worker":r=rt(l())+"-"+e;break;default:r=e}var i=t.length?t.join(","):"FirebaseCore-web";return`${r}/JsCore/${Bn.SDK_VERSION}/`+i}class pt{constructor(e){this.auth=e,this.queue=[]}pushCallback(i,e){var t=r=>new Promise((e,t)=>{try{e(i(r))}catch(e){t(e)}});t.onAbort=e,this.queue.push(t);let r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser!==e){var t=[];try{for(var r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(e){t.reverse();for(var i of t)try{i()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:e?.message})}}}}class mt{constructor(e){var t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??6,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),void 0!==t.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),void 0!==t.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),void 0!==t.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),void 0!==t.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){var t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){var r=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),i&&(t.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,t){var r;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let i=0;i<e.length;i++)r=e.charAt(i),this.updatePasswordCharacterOptionsStatuses(t,"a"<=r&&r<="z","A"<=r&&r<="Z","0"<=r&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,i,n){this.customStrengthOptions.containsLowercaseLetter&&!e.containsLowercaseLetter&&(e.containsLowercaseLetter=t),this.customStrengthOptions.containsUppercaseLetter&&!e.containsUppercaseLetter&&(e.containsUppercaseLetter=r),this.customStrengthOptions.containsNumericCharacter&&!e.containsNumericCharacter&&(e.containsNumericCharacter=i),this.customStrengthOptions.containsNonAlphanumericCharacter&&!e.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter=n)}}class gt{constructor(e,t,r,i){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new ft(this),this.idTokenSubscription=new ft(this),this.beforeStateQueue=new pt(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=_e,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion,this._persistenceManagerAvailable=new Promise(e=>this._resolvePersistenceManagerAvailable=e)}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=y(t)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await tt.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){var e;!this._deleted&&(e=await this.assertedPersistence.getCurrentUser(),this.currentUser||e)&&(this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),await this.currentUser.getIdToken()):await this._updateCurrentUser(e,!0))}async initializeCurrentUserFromIdToken(e){try{var t=await He(this,{idToken:e}),r=await _._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(Bn._isFirebaseServerApp(this.app)){let t=this.app.settings.authIdToken;return t?new Promise(e=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(t).then(e,e))}):this.directlySetCurrentUser(null)}var t,r,i,n=await this.assertedPersistence.getCurrentUser();let s=n,a=!1;if(e&&this.config.authDomain&&(await this.getOrInitRedirectPersistenceManager(),t=this.redirectUser?._redirectEventId,r=s?._redirectEventId,i=await this.tryRedirectSignIn(e),t&&t!==r||!i?.user||(s=i.user,a=!0)),!s)return this.directlySetCurrentUser(null);if(s._redirectEventId)return g(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===s._redirectEventId?this.directlySetCurrentUser(s):this.reloadAndSetCurrentUserOrClear(s);if(a)try{await this.beforeStateQueue.runMiddleware(s)}catch(e){s=n,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(e))}return s?this.reloadAndSetCurrentUserOrClear(s):this.directlySetCurrentUser(null)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Je(e)}catch(e){if("auth/network-request-failed"!==e?.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){var e;this.languageCode="undefined"!=typeof navigator&&((e=navigator).languages&&e.languages[0]||e.language)||null}async _delete(){this._deleted=!0}async updateCurrentUser(e){var t;return Bn._isFirebaseServerApp(this.app)?Promise.reject(c(this)):((t=e?a(e):null)&&g(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this)))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&g(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return Bn._isFirebaseServerApp(this.app)?Promise.reject(c(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return Bn._isFirebaseServerApp(this.app)?Promise.reject(c(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(y(e))})}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();var t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){var e,t=await m(e=this,"GET","/v2/passwordPolicy",p(e,{})),t=new mt(t);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new Q("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise((t,r)=>{if(this.currentUser)t();else{let e=this.onAuthStateChanged(()=>{e(),t()},r)}})}async revokeAccessToken(e){var t;this.currentUser&&(t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()},null!=this.tenantId&&(t.tenantId=this.tenantId),await m(e=this,"POST","/v2/accounts:revokeToken",p(e,t)))}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){var r=await this.getOrInitRedirectPersistenceManager(t);return null===e?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){var t;return this.redirectPersistenceManager||(g(t=e&&y(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await tt.create(this,[y(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()),this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:`+this.name}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e;this._isInitialized&&(this.idTokenSubscription.next(this.currentUser),e=this.currentUser?.uid??null,this.lastNotifiedUid!==e)&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(t,r,i,n){if(this._deleted)return()=>{};let e="function"==typeof r?r:r.next.bind(r),s=!1;var a=this._isInitialized?Promise.resolve():this._initializationPromise;if(g(a,this,"internal-error"),a.then(()=>{s||e(this.currentUser)}),"function"==typeof r){let e=t.addObserver(r,i,n);return()=>{s=!0,e()}}{let e=t.addObserver(r);return()=>{s=!0,e()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),(this.currentUser=e)?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return g(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=ut(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e={"X-Client-Version":this.clientVersion},t=(this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId),await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader()),t=(t&&(e["X-Firebase-Client"]=t),await this._getAppCheckToken());return t&&(e["X-Firebase-AppCheck"]=t),e}async _getAppCheckToken(){var e,t,r;return Bn._isFirebaseServerApp(this.app)&&this.app.settings.appCheckToken?this.app.settings.appCheckToken:((e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken())?.error&&(t="Error while retrieving App Check token: "+e.error,r=[],ye.logLevel<=i.WARN)&&ye.warn(`Auth (${Bn.SDK_VERSION}): `+t,...r),e?.token)}}function I(e){return a(e)}class ft{constructor(e){var t,r;this.auth=e,this.observer=null,this.addObserver=(e=e=>this.observer=e,(r=new se(e,t)).subscribe.bind(r))}get next(){return g(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let vt={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function _t(e){return vt.loadJS(e)}function yt(e){return"__"+e+Math.floor(1e6*Math.random())}class It{constructor(e){this.auth=e,this.counter=1e12,this._widgets=new Map}render(e,t){var r=this.counter;return this._widgets.set(r,new Et(e,this.auth.name,t||{})),this.counter++,r}reset(e){var t=e||1e12;this._widgets.get(t)?.delete(),this._widgets.delete(t)}getResponse(e){return this._widgets.get(e||1e12)?.getResponse()||""}async execute(e){return this._widgets.get(e||1e12)?.execute(),""}}class wt{constructor(){this.enterprise=new Tt}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class Tt{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class Et{constructor(e,t,r){this.params=r,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};var i="string"==typeof e?document.getElementById(e):e;g(i,"argument-error",{appName:t}),this.container=i,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout(()=>{this.responseToken=(e=>{var t=[],r="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let i=0;i<e;i++)t.push(r.charAt(Math.floor(Math.random()*r.length)));return t.join("")})(50);let{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout(()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()},6e4)},500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}let bt="NO_RECAPTCHA",kt="onFirebaseAuthREInstanceReady";class w{constructor(e){this.type="recaptcha-enterprise",this.auth=I(e)}async verify(n="verify",e=!1){function s(e,t,r){let i=window.grecaptcha;Ve(i)?i.enterprise.ready(()=>{i.enterprise.execute(e,{action:n}).then(e=>{t(e)}).catch(()=>{t(bt)})}):r(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?(new wt).execute("siteKey",{action:"verify"}):new Promise((r,i)=>{(async n=>{if(!e){if(null==n.tenantId&&null!=n._agentRecaptchaConfig)return n._agentRecaptchaConfig.siteKey;if(null!=n.tenantId&&void 0!==n._tenantRecaptchaConfigs[n.tenantId])return n._tenantRecaptchaConfigs[n.tenantId].siteKey}return new Promise(async(r,i)=>{We(n,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(e=>{var t;if(void 0!==e.recaptchaKey)return t=new xe(e),null==n.tenantId?n._agentRecaptchaConfig=t:n._tenantRecaptchaConfigs[n.tenantId]=t,r(t.siteKey);i(new Error("recaptcha Enterprise site key undefined"))}).catch(e=>{i(e)})})})(this.auth).then(async t=>{if(!e&&Ve(window.grecaptcha)&&w.scriptInjectionDeferred)await w.scriptInjectionDeferred.promise,s(t,r,i);else if("undefined"==typeof window)i(new Error("RecaptchaVerifier is only supported in browser"));else{let e=vt.recaptchaEnterpriseScript;0!==e.length&&(e+=t+("&onload="+kt)),w.scriptInjectionDeferred=new G,window[kt]=()=>{w.scriptInjectionDeferred?.resolve()},_t(e).then(()=>w.scriptInjectionDeferred?.promise).then(()=>{s(t,r,i)}).catch(e=>{i(e)})}}).catch(e=>{i(e)})})}}async function St(e,t,r,i=!1,n=!1){var s=new w(e);let a;if(n)a=bt;else try{a=await s.verify(r)}catch(e){a=await s.verify(r,!0)}var o,c,s={...t};return"mfaSmsEnrollment"===r||"mfaSmsSignIn"===r?"phoneEnrollmentInfo"in s?(c=s.phoneEnrollmentInfo.phoneNumber,o=s.phoneEnrollmentInfo.recaptchaToken,Object.assign(s,{phoneEnrollmentInfo:{phoneNumber:c,recaptchaToken:o,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})):"phoneSignInInfo"in s&&(c=s.phoneSignInInfo.recaptchaToken,Object.assign(s,{phoneSignInInfo:{recaptchaToken:c,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})):(i?Object.assign(s,{captchaResp:a}):Object.assign(s,{captchaResponse:a}),Object.assign(s,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(s,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"})),s}async function T(r,i,n,s,e){var t;return"EMAIL_PASSWORD_PROVIDER"===e?r._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")?(t=await St(r,i,n,"getOobCode"===n),s(r,t)):s(r,i).catch(async e=>{var t;return"auth/missing-recaptcha-token"===e.code?(console.log(n+" is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow."),t=await St(r,i,n,"getOobCode"===n),s(r,t)):Promise.reject(e)}):"PHONE_PROVIDER"===e?r._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")?(t=await St(r,i,n),s(r,t).catch(async e=>{var t;if("AUDIT"===r._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")&&("auth/missing-recaptcha-token"===e.code||"auth/invalid-app-credential"===e.code))return console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${n} flow.`),t=await St(r,i,n,!1,!0),s(r,t);return Promise.reject(e)})):(t=await St(r,i,n,!1,!0),s(r,t)):Promise.reject(e+" provider is not supported.")}function Rt(e,t,r){var i=I(e),n=(g(/^https?:\/\//.test(t),i,"invalid-emulator-scheme"),!!r?.disableWarnings),s=At(t),{host:a,port:o}=(e=>{var t,r=At(e);return(r=/(\/\/)?([^?#/]+)/.exec(e.substr(r.length)))?(r=r[2].split("@").pop()||"",(t=/^(\[[^\]]+\])(:|$)/.exec(r))?{host:t=t[1],port:Pt(r.substr(t.length+1))}:([t,r]=r.split(":"),{host:t,port:Pt(r)})):{host:"",port:null}})(t),c=null===o?"":":"+o,l={url:s+`//${a}${c}/`},o=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:n})});function d(){var e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}i._canInitEmulator?(i.config.emulator=l,i.emulatorConfig=o,i.settings.appVerificationDisabledForTesting=!0,oe(a)?(async e=>(await fetch(e,{credentials:"include"})).ok)(s+"//"+a+c):n||("undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",d):d()))):(g(i.config.emulator&&i.emulatorConfig,i,"emulator-config-failed"),g(ee(l,i.config.emulator)&&ee(o,i.emulatorConfig),i,"emulator-config-failed"))}function At(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function Pt(e){var t;return!e||(t=Number(e),isNaN(t))?null:t}w.scriptInjectionDeferred=null;class Ct{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return n("not implemented")}_getIdTokenResponse(e){return n("not implemented")}_linkToIdToken(e,t){return n("not implemented")}_getReauthenticationResolver(e){return n("not implemented")}}async function Nt(e,t){return m(e,"POST","/v1/accounts:resetPassword",p(e,t))}async function Ot(e,t){return m(e,"POST","/v1/accounts:signUp",t)}async function Lt(e,t){return s(e,"POST","/v1/accounts:signInWithPassword",p(e,t))}async function Dt(e,t){return m(e,"POST","/v1/accounts:sendOobCode",p(e,t))}async function Mt(e,t){return Dt(e,t)}async function Ut(e,t){return Dt(e,t)}class Ft extends Ct{constructor(e,t,r,i=null){super("password",r),this._email=e,this._password=t,this._tenantId=i}static _fromEmailAndPassword(e,t){return new Ft(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new Ft(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e;if(t?.email&&t?.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return T(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",Lt,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return(async(e,t)=>s(e,"POST","/v1/accounts:signInWithEmailLink",p(e,t)))(e,{email:this._email,oobCode:this._password});default:h(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return T(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",Ot,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return(async(e,t)=>s(e,"POST","/v1/accounts:signInWithEmailLink",p(e,t)))(e,{idToken:t,email:this._email,oobCode:this._password});default:h(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function E(e,t){return s(e,"POST","/v1/accounts:signInWithIdp",p(e,t))}class b extends Ct{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){var t=new b(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):h("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){var t;let{providerId:r,signInMethod:i,...n}="string"==typeof e?JSON.parse(e):e;return r&&i?((t=new b(r,i)).idToken=n.idToken||void 0,t.accessToken=n.accessToken||void 0,t.secret=n.secret,t.nonce=n.nonce,t.pendingToken=n.pendingToken||null,t):null}_getIdTokenResponse(e){return E(e,this.buildRequest())}_linkToIdToken(e,t){var r=this.buildRequest();return r.idToken=t,E(e,r)}_getReauthenticationResolver(e){var t=this.buildRequest();return t.autoCreate=!1,E(e,t)}buildRequest(){var e,t={requestUri:"http://localhost",returnSecureToken:!0};return this.pendingToken?t.pendingToken=this.pendingToken:(e={},this.idToken&&(e.id_token=this.idToken),this.accessToken&&(e.access_token=this.accessToken),this.secret&&(e.oauth_token_secret=this.secret),e.providerId=this.providerId,this.nonce&&!this.pendingToken&&(e.nonce=this.nonce),t.postBody=re(e)),t}}async function Vt(e,t){return m(e,"POST","/v1/accounts:sendVerificationCode",p(e,t))}let xt={USER_NOT_FOUND:"user-not-found"};class Wt extends Ct{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new Wt({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new Wt({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return(async(e,t)=>s(e,"POST","/v1/accounts:signInWithPhoneNumber",p(e,t)))(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return(async(e,t)=>{var r=await s(e,"POST","/v1/accounts:signInWithPhoneNumber",p(e,t));if(r.temporaryProof)throw Ue(e,"account-exists-with-different-credential",r);return r})(e,{idToken:t,...this._makeVerificationRequest()})}_getReauthenticationResolver(e){return(async(e,t)=>s(e,"POST","/v1/accounts:signInWithPhoneNumber",p(e,{...t,operation:"REAUTH"}),xt))(e,this._makeVerificationRequest())}_makeVerificationRequest(){var{temporaryProof:e,phoneNumber:t,verificationId:r,verificationCode:i}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:r,code:i}}toJSON(){var e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){var{verificationId:t,verificationCode:r,phoneNumber:i,temporaryProof:n}=e="string"==typeof e?JSON.parse(e):e;return r||t||i||n?new Wt({verificationId:t,verificationCode:r,phoneNumber:i,temporaryProof:n}):null}}class Ht{constructor(e){var t=ie(ne(e)),r=t.apiKey??null,i=t.oobCode??null,n=(e=>{switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}})(t.mode??null);g(r&&i&&n,"argument-error"),this.apiKey=r,this.operation=n,this.code=i,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){t=ie(ne(e=e)).link,r=t?ie(ne(t)).deep_link_id:null;var t,r,i=((i=ie(ne(e)).deep_link_id)?ie(ne(i)).link:null)||i||r||t||e;try{return new Ht(i)}catch{return null}}}class jt{constructor(){this.providerId=jt.PROVIDER_ID}static credential(e,t){return Ft._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var r=Ht.parseLink(t);return g(r,"argument-error"),Ft._fromEmailAndCode(e,r.code,r.tenantId)}}jt.PROVIDER_ID="password",jt.EMAIL_PASSWORD_SIGN_IN_METHOD="password",jt.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class k{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class qt extends k{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class Bt extends qt{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return g("providerId"in t&&"signInMethod"in t,"argument-error"),b._fromParams(t)}credential(e){return this._credential({...e,nonce:e.rawNonce})}_credential(e){return g(e.idToken||e.accessToken,"argument-error"),b._fromParams({...e,providerId:this.providerId,signInMethod:this.providerId})}static credentialFromResult(e){return Bt.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return Bt.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:r,oauthTokenSecret:i,pendingToken:n,nonce:s,providerId:a}=e;if(!(r||i||t||n))return null;if(!a)return null;try{return new Bt(a)._credential({idToken:t,accessToken:r,nonce:s,pendingToken:n})}catch(e){return null}}}class S extends qt{constructor(){super("facebook.com")}static credential(e){return b._fromParams({providerId:S.PROVIDER_ID,signInMethod:S.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return S.credentialFromTaggedObject(e)}static credentialFromError(e){return S.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return S.credential(e.oauthAccessToken)}catch{return null}}}S.FACEBOOK_SIGN_IN_METHOD="facebook.com",S.PROVIDER_ID="facebook.com";class R extends qt{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return b._fromParams({providerId:R.PROVIDER_ID,signInMethod:R.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return R.credentialFromTaggedObject(e)}static credentialFromError(e){return R.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return R.credential(t,r)}catch{return null}}}R.GOOGLE_SIGN_IN_METHOD="google.com",R.PROVIDER_ID="google.com";class A extends qt{constructor(){super("github.com")}static credential(e){return b._fromParams({providerId:A.PROVIDER_ID,signInMethod:A.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return A.credentialFromTaggedObject(e)}static credentialFromError(e){return A.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return A.credential(e.oauthAccessToken)}catch{return null}}}A.GITHUB_SIGN_IN_METHOD="github.com",A.PROVIDER_ID="github.com";class zt extends Ct{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return E(e,this.buildRequest())}_linkToIdToken(e,t){var r=this.buildRequest();return r.idToken=t,E(e,r)}_getReauthenticationResolver(e){var t=this.buildRequest();return t.autoCreate=!1,E(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){var{providerId:t,signInMethod:r,pendingToken:i}="string"==typeof e?JSON.parse(e):e;return t&&r&&i&&t===r?new zt(t,i):null}static _create(e,t){return new zt(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class Gt extends k{constructor(e){g(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return Gt.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return Gt.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=zt.fromJSON(e);return g(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{pendingToken:t,providerId:r}=e;if(!t||!r)return null;try{return zt._create(r,t)}catch(e){return null}}}class P extends qt{constructor(){super("twitter.com")}static credential(e,t){return b._fromParams({providerId:P.PROVIDER_ID,signInMethod:P.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return P.credentialFromTaggedObject(e)}static credentialFromError(e){return P.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return P.credential(t,r)}catch{return null}}}async function Kt(e,t){return s(e,"POST","/v1/accounts:signUp",p(e,t))}P.TWITTER_SIGN_IN_METHOD="twitter.com",P.PROVIDER_ID="twitter.com";class C{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,i=!1){var n=await _._fromIdTokenResponse(e,r,i),s=Jt(r);return new C({user:n,providerId:s,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);var i=Jt(r);return new C({user:e,providerId:i,_tokenResponse:r,operationType:t})}}function Jt(e){return e.providerId||("phoneNumber"in e?"phone":null)}class Yt extends d{constructor(e,t,r,i){super(t.code,t.message),this.operationType=r,this.user=i,Object.setPrototypeOf(this,Yt.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,i){return new Yt(e,t,r,i)}}function $t(t,r,e,i){return("reauthenticate"===r?e._getReauthenticationResolver(t):e._getIdTokenResponse(t)).catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw Yt._fromErrorAndOperation(t,e,r,i);throw e})}function Xt(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Qt(e,t){var r=a(e),i=(await er(!0,r,t),e=r.auth,t={idToken:await r.getIdToken(),deleteProvider:[t]},await m(e,"POST","/v1/accounts:update",t)).providerUserInfo;let n=Xt(i||[]);return r.providerData=r.providerData.filter(e=>n.has(e.providerId)),n.has("phone")||(r.phoneNumber=null),await r.auth._persistUserIfCurrent(r),r}async function Zt(e,t,r=!1){var i=await f(e,t._linkToIdToken(e.auth,await e.getIdToken()),r);return C._forOperation(e,"link",i)}async function er(e,t,r){await Je(t);var i=!1===e?"provider-already-linked":"no-such-provider";g(Xt(t.providerData).has(r)===e,t.auth,i)}async function tr(e,t,r=!1){var i=e.auth;if(Bn._isFirebaseServerApp(i.app))return Promise.reject(c(i));var n="reauthenticate";try{var s=await f(e,$t(i,n,t,e),r),a=(g(s.idToken,i,"internal-error"),Be(s.idToken)),o=(g(a,i,"internal-error"),a).sub;return g(e.uid===o,i,"user-mismatch"),C._forOperation(e,n,s)}catch(e){throw"auth/user-not-found"===e?.code&&h(i,"user-mismatch"),e}}async function rr(e,t,r=!1){var i;return Bn._isFirebaseServerApp(e.app)?Promise.reject(c(e)):(i=await $t(e,"signIn",t),i=await C._fromIdTokenResponse(e,"signIn",i),r||await e._updateCurrentUser(i.user),i)}async function ir(e,t){return rr(I(e),t)}async function nr(e,t){var r=a(e);return await er(!1,r,t.providerId),Zt(r,t)}async function sr(e,t){return tr(a(e),t)}async function ar(e,t){var r,i;return Bn._isFirebaseServerApp(e.app)?Promise.reject(c(e)):(i=await s(r=I(e),"POST","/v1/accounts:signInWithCustomToken",p(r,{token:t,returnSecureToken:!0})),i=await C._fromIdTokenResponse(r,"signIn",i),await r._updateCurrentUser(i.user),i)}class or{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?cr._fromServerResponse(e,t):"totpInfo"in t?lr._fromServerResponse(e,t):h(e,"internal-error")}}class cr extends or{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new cr(t)}}class lr extends or{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new lr(t)}}function dr(e,t,r){g(0<r.url?.length,e,"invalid-continue-uri"),g(void 0===r.dynamicLinkDomain||0<r.dynamicLinkDomain.length,e,"invalid-dynamic-link-domain"),g(void 0===r.linkDomain||0<r.linkDomain.length,e,"invalid-hosting-link-domain"),t.continueUrl=r.url,t.dynamicLinkDomain=r.dynamicLinkDomain,t.linkDomain=r.linkDomain,t.canHandleCodeInApp=r.handleCodeInApp,r.iOS&&(g(0<r.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=r.iOS.bundleId),r.android&&(g(0<r.android.packageName.length,e,"missing-android-pkg-name"),t.androidInstallApp=r.android.installApp,t.androidMinimumVersionCode=r.android.minimumVersion,t.androidPackageName=r.android.packageName)}async function hr(e){var t=I(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function ur(e,t){await m(e=a(e),"POST","/v1/accounts:update",p(e,{oobCode:t}))}async function pr(e,t){var r=a(e),i=await Nt(r,{oobCode:t}),n=i.requestType;switch(g(n,r,"internal-error"),n){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":g(i.newEmail,r,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":g(i.mfaInfo,r,"internal-error");default:g(i.email,r,"internal-error")}let s=null;return i.mfaInfo&&(s=or._fromServerResponse(I(r),i.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===i.requestType?i.newEmail:i.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===i.requestType?i.email:i.newEmail)||null,multiFactorInfo:s},operation:n}}async function mr(e,t){var r=ke()?be():"http://localhost",r=(await m(e=a(e),"POST","/v1/accounts:createAuthUri",p(e,{identifier:t,continueUri:r}))).signinMethods;return r||[]}async function gr(e,t){var r=a(e),i={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()},r=(t&&dr(r.auth,i,t),await Dt(r.auth,i)).email;r!==e.email&&await e.reload()}async function fr(e,t,r){var i=a(e),n={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t},i=(r&&dr(i.auth,n,r),await Dt(i.auth,n)).email;i!==e.email&&await e.reload()}async function vr(e,{displayName:t,photoURL:r}){var i,n,s;void 0===t&&void 0===r||(n=await(i=a(e)).getIdToken(),n=await f(i,(async(e,t)=>m(e,"POST","/v1/accounts:update",t))(i.auth,{idToken:n,displayName:t,photoUrl:r,returnSecureToken:!0})),i.displayName=n.displayName||null,i.photoURL=n.photoUrl||null,(s=i.providerData.find(({providerId:e})=>"password"===e))&&(s.displayName=i.displayName,s.photoURL=i.photoURL),await i._updateTokensIfNecessary(n))}async function _r(e,t,r){var i=e.auth,n={idToken:await e.getIdToken(),returnSecureToken:!0},i=(t&&(n.email=t),r&&(n.password=r),await f(e,(async(e,t)=>m(e,"POST","/v1/accounts:update",t))(i,n)));await e._updateTokensIfNecessary(i,!0)}class yr{constructor(e,t,r={}){this.isNewUser=e,this.providerId=t,this.profile=r}}class Ir extends yr{constructor(e,t,r,i){super(e,t,r),this.username=i}}class wr extends yr{constructor(e,t){super(e,"facebook.com",t)}}class Tr extends Ir{constructor(e,t){super(e,"github.com",t,"string"==typeof t?.login?t?.login:null)}}class Er extends yr{constructor(e,t){super(e,"google.com",t)}}class br extends Ir{constructor(e,t,r){super(e,"twitter.com",t,r)}}function kr(e){var{user:t,_tokenResponse:r}=e;if(t.isAnonymous&&!r)return{providerId:null,isNewUser:!1,profile:null};var i=r;if(!i)return null;var n=i.providerId,s=i.rawUserInfo?JSON.parse(i.rawUserInfo):{},a=i.isNewUser||"identitytoolkit#SignupNewUserResponse"===i.kind;if(!n&&i?.idToken){t=Be(i.idToken)?.firebase?.sign_in_provider;if(t)return t="anonymous"!==t&&"custom"!==t?t:null,new yr(a,t)}if(!n)return null;switch(n){case"facebook.com":return new wr(a,s);case"github.com":return new Tr(a,s);case"google.com":return new Er(a,s);case"twitter.com":return new br(a,s,i.screenName||null);case"custom":case"anonymous":return new yr(a,null);default:return new yr(a,n,s)}}class Sr{constructor(e,t,r){this.type=e,this.credential=t,this.user=r}static _fromIdtoken(e,t){return new Sr("enroll",e,t)}static _fromMfaPendingCredential(e){return new Sr("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){if(e?.multiFactorSession){if(e.multiFactorSession?.pendingCredential)return Sr._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(e.multiFactorSession?.idToken)return Sr._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Rr{constructor(e,t,r){this.session=e,this.hints=t,this.signInResolver=r}static _fromError(e,n){let s=I(e),a=n.customData._serverResponse;var t=(a.mfaInfo||[]).map(e=>or._fromServerResponse(s,e));g(a.mfaPendingCredential,s,"internal-error");let o=Sr._fromMfaPendingCredential(a.mfaPendingCredential);return new Rr(o,t,async e=>{var t=await e._process(s,o),r=(delete a.mfaInfo,delete a.mfaPendingCredential,{...a,idToken:t.idToken,refreshToken:t.refreshToken});switch(n.operationType){case"signIn":var i=await C._fromIdTokenResponse(s,n.operationType,r);return await s._updateCurrentUser(i.user),i;case"reauthenticate":return g(n.user,s,"internal-error"),C._forOperation(n.user,n.operationType,r);default:h(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}function Ar(e,t){return m(e,"POST","/v2/accounts/mfaEnrollment:start",p(e,t))}class Pr{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>or._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new Pr(e)}async getSession(){return Sr._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){var r=e,i=await this.getSession(),r=await f(this.user,r._process(this.user.auth,i,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){let t="string"==typeof e?e:e.uid;var r,i,n=await this.user.getIdToken();try{var s=await f(this.user,(r=this.user.auth,i={idToken:n,mfaEnrollmentId:t},m(r,"POST","/v2/accounts/mfaEnrollment:withdraw",p(r,i))));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(s),await this.user.reload()}catch(e){throw e}}}let Cr=new WeakMap;let Nr="__sak";class Or{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Nr,"1"),this.storage.removeItem(Nr),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){var t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class Lr extends Or{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=ht(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(var t of Object.keys(this.listeners)){var r=this.storage.getItem(t),i=this.localCache[t];r!==i&&e(t,i,r)}}onStorageEvent(e,r=!1){if(e.key){let t=e.key;r?this.detachListener():this.stopPolling();var i=()=>{var e=this.storage.getItem(t);!r&&this.localCache[t]===e||this.notifyListeners(t,e)},n=this.storage.getItem(t);$()&&10===document.documentMode&&n!==e.newValue&&e.newValue!==e.oldValue?setTimeout(i,10):i()}else this.forAllChangedKeys((e,t,r)=>{this.notifyListeners(e,r)})}notifyListeners(e,t){this.localCache[e]=t;var r=this.listeners[e];if(r)for(var i of Array.from(r))i(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:r}),!0)})},1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size)&&delete this.listeners[e],0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){var t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}Lr.type="LOCAL";let Dr=Lr;class Mr extends Or{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}Mr.type="SESSION";let Ur=Mr;class Fr{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){var e=this.receivers.find(e=>e.isListeningto(t));return e||(e=new Fr(t),this.receivers.push(e),e)}isListeningto(e){return this.eventTarget===e}async handleEvent(e){let t=e,{eventId:r,eventType:i,data:n}=t.data;var s=this.handlersMap[i];s?.size&&(t.ports[0].postMessage({status:"ack",eventId:r,eventType:i}),s=Array.from(s).map(async e=>e(t.origin,n)),s=await Promise.all(s.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})),t.ports[0].postMessage({status:"done",eventId:r,eventType:i,response:s}))}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function Vr(e="",t=10){let r="";for(let i=0;i<t;i++)r+=Math.floor(10*Math.random());return e+r}Fr.receivers=[];class xr{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,a=50){let o="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!o)throw new Error("connection_unavailable");let c,l;return new Promise((r,i)=>{let n=Vr("",20),s=(o.port1.start(),setTimeout(()=>{i(new Error("unsupported_event"))},a));l={messageChannel:o,onMessage(e){var t=e;if(t.data.eventId===n)switch(t.data.status){case"ack":clearTimeout(s),c=setTimeout(()=>{i(new Error("timeout"))},3e3);break;case"done":clearTimeout(c),r(t.data.response);break;default:clearTimeout(s),clearTimeout(c),i(new Error("invalid_response"))}}},this.handlers.add(l),o.port1.addEventListener("message",l.onMessage),this.target.postMessage({eventType:e,eventId:n,data:t},[o.port2])}).finally(()=>{l&&this.removeMessageHandler(l)})}}function N(){return window}function Wr(){return void 0!==N().WorkerGlobalScope&&"function"==typeof N().importScripts}let Hr="firebaseLocalStorageDb",jr="firebaseLocalStorage",qr="fbase_key";class Br{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function zr(e,t){return e.transaction([jr],t?"readwrite":"readonly").objectStore(jr)}function Gr(){let i=indexedDB.open(Hr,1);return new Promise((t,r)=>{i.addEventListener("error",()=>{r(i.error)}),i.addEventListener("upgradeneeded",()=>{var e=i.result;try{e.createObjectStore(jr,{keyPath:qr})}catch(e){r(e)}}),i.addEventListener("success",async()=>{var e=i.result;e.objectStoreNames.contains(jr)?t(e):(e.close(),e=indexedDB.deleteDatabase(Hr),await new Br(e).toPromise(),t(await Gr()))})})}async function Kr(e,t,r){var i=zr(e,!0).put({fbase_key:t,value:r});return new Br(i).toPromise()}function Jr(e,t){var r=zr(e,!0).delete(t);return new Br(r).toPromise()}class Yr{constructor(){this.type="LOCAL",this.dbPromise=null,this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.dbPromise||(this.dbPromise=Gr(),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}async _withRetries(e){let t=0;for(;;)try{return await e(await this._openDb())}catch(e){if(3<t++)throw e;this.dbPromise&&((await this.dbPromise).close(),this.dbPromise=null)}}async initializeServiceWorkerMessaging(){return Wr()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Fr._getInstance(Wr()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e;this.activeServiceWorker=await(async()=>{if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}})(),this.activeServiceWorker&&(this.sender=new xr(this.activeServiceWorker),e=await this.sender._send("ping",{},800))&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&(navigator?.serviceWorker?.controller||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{return indexedDB?(await this._withRetries(async e=>{await Kr(e,Nr,"1"),await Jr(e,Nr)}),!0):!1}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(t,r){return this._withPendingWrite(async()=>(await this._withRetries(e=>Kr(e,t,r)),this.localCache[t]=r,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>(async(e,t)=>{var r=zr(e,!1).get(t);return void 0===(r=await new Br(r).toPromise())?null:r.value})(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>Jr(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e=await this._withRetries(e=>{var t=zr(e,!1).getAll();return new Br(t).toPromise()});if(!e)return[];if(0!==this.pendingWrites)return[];var t,r=[],i=new Set;if(0!==e.length)for(var{fbase_key:n,value:s}of e)i.add(n),JSON.stringify(this.localCache[n])!==JSON.stringify(s)&&(this.notifyListeners(n,s),r.push(n));for(t of Object.keys(this.localCache))this.localCache[t]&&!i.has(t)&&(this.notifyListeners(t,null),r.push(t));return r}notifyListeners(e,t){this.localCache[e]=t;var r=this.listeners[e];if(r)for(var i of Array.from(r))i(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size)&&delete this.listeners[e],0===Object.keys(this.listeners).length&&this.stopPolling()}}Yr.type="LOCAL";let $r=Yr;function Xr(e,t){return m(e,"POST","/v2/accounts/mfaSignIn:start",p(e,t))}let Qr=yt("rcb"),Zr=new Re(3e4,6e4);class ei{constructor(){this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!N().grecaptcha?.render}load(n,s=""){var e;return g((e=s).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),n,"argument-error"),this.shouldResolveImmediately(s)&&Fe(N().grecaptcha)?Promise.resolve(N().grecaptcha):new Promise((t,r)=>{let i=N().setTimeout(()=>{r(u(n,"network-request-failed"))},Zr.get());N()[Qr]=()=>{N().clearTimeout(i),delete N()[Qr];var e=N().grecaptcha;if(e&&Fe(e)){let i=e.render;e.render=(e,t)=>{var r=i(e,t);return this.counter++,r},this.hostLanguage=s,t(e)}else r(u(n,"internal-error"))},_t(vt.recaptchaV2Script+"?"+re({onload:Qr,render:"explicit",hl:s})).catch(()=>{clearTimeout(i),r(u(n,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!N().grecaptcha?.render&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class ti{async load(e){return new It(e)}clearedOneInstance(){}}let ri="recaptcha",ii={theme:"light",type:"image"};class ni{constructor(e,t,r={...ii}){this.parameters=r,this.type=ri,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=I(e),this.isInvisible="invisible"===this.parameters.size,g("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var i="string"==typeof t?document.getElementById(t):t;g(i,this.auth,"argument-error"),this.container=i,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?ti:ei),this.validateStartingState()}async verify(){this.assertNotDestroyed();let e=await this.render(),i=this.getAssertedRecaptcha();var t=i.getResponse(e);return t||new Promise(t=>{let r=e=>{e&&(this.tokenChangeListeners.delete(r),t(e))};this.tokenChangeListeners.add(r),this.isInvisible&&i.execute(e)})}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch(e=>{throw this.renderPromise=null,e})),this.renderPromise}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach(e=>{this.container.removeChild(e)})}validateStartingState(){g(!this.parameters.sitekey,this.auth,"argument-error"),g(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),g("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(r){return t=>{var e;this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof r?r(t):"string"==typeof r&&"function"==typeof(e=N()[r])&&e(t)}}assertNotDestroyed(){g(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;var t;this.isInvisible||(t=document.createElement("div"),e.appendChild(t),e=t),this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){g(ke()&&!Wr(),this.auth,"internal-error"),await(()=>{let t=null;return new Promise(e=>{"complete"===document.readyState?e():(t=()=>e(),window.addEventListener("load",t))}).catch(e=>{throw t&&window.removeEventListener("load",t),e})})(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);var e=await((await m(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");g(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return g(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class si{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=Wt._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function ai(t,r,i){if(!t._getRecaptchaConfig())try{e=I(t),n=await We(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}),n=new xe(n),null==e.tenantId?e._agentRecaptchaConfig=n:e._tenantRecaptchaConfigs[e.tenantId]=n,await(!n.isAnyProviderEnabled()||!new w(e).verify())}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}var e,n,s,a,o,c,l;try{let e;return("session"in(e="string"==typeof r?{phoneNumber:r}:r)?(s=e.session,"phoneNumber"in e?(g("enroll"===s.type,t,"internal-error"),a={idToken:s.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"}},(await T(t,a,"mfaSmsEnrollment",async(e,t)=>t.phoneEnrollmentInfo.captchaResponse===bt?(g(i?.type===ri,e,"argument-error"),Ar(e,await oi(e,t,i))):Ar(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e))).phoneSessionInfo):(g("signin"===s.type,t,"internal-error"),g(o=e.multiFactorHint?.uid||e.multiFactorUid,t,"missing-multi-factor-info"),c={mfaPendingCredential:s.credential,mfaEnrollmentId:o,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}},(await T(t,c,"mfaSmsSignIn",async(e,t)=>t.phoneSignInInfo.captchaResponse===bt?(g(i?.type===ri,e,"argument-error"),Xr(e,await oi(e,t,i))):Xr(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e))).phoneResponseInfo)):(l={phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"},await T(t,l,"sendVerificationCode",async(e,t)=>t.captchaResponse===bt?(g(i?.type===ri,e,"argument-error"),Vt(e,await oi(e,t,i))):Vt(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e)))).sessionInfo}finally{i?._reset()}}async function oi(e,t,r){g(r.type===ri,e,"argument-error");var i,n,s,a,o=await r.verify(),c=(g("string"==typeof o,e,"argument-error"),{...t});return"phoneEnrollmentInfo"in c?(n=c.phoneEnrollmentInfo.phoneNumber,s=c.phoneEnrollmentInfo.captchaResponse,a=c.phoneEnrollmentInfo.clientType,i=c.phoneEnrollmentInfo.recaptchaVersion,Object.assign(c,{phoneEnrollmentInfo:{phoneNumber:n,recaptchaToken:o,captchaResponse:s,clientType:a,recaptchaVersion:i}})):"phoneSignInInfo"in c?(n=c.phoneSignInInfo.captchaResponse,s=c.phoneSignInInfo.clientType,a=c.phoneSignInInfo.recaptchaVersion,Object.assign(c,{phoneSignInInfo:{recaptchaToken:o,captchaResponse:n,clientType:s,recaptchaVersion:a}})):Object.assign(c,{recaptchaToken:o}),c}class O{constructor(e){this.providerId=O.PROVIDER_ID,this.auth=I(e)}verifyPhoneNumber(e,t){return ai(this.auth,e,a(t))}static credential(e,t){return Wt._fromVerification(e,t)}static credentialFromResult(e){var t=e;return O.credentialFromTaggedObject(t)}static credentialFromError(e){return O.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){var t,r;return e&&({phoneNumber:t,temporaryProof:r}=e,t)&&r?Wt._fromTokenResponse(t,r):null}}function ci(e,t){return t?y(t):(g(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}O.PROVIDER_ID="phone",O.PHONE_SIGN_IN_METHOD="phone";class li extends Ct{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return E(e,this._buildIdpRequest())}_linkToIdToken(e,t){return E(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return E(e,this._buildIdpRequest())}_buildIdpRequest(e){var t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function di(e){return rr(e.auth,new li(e),e.bypassAuthState)}function hi(e){var{auth:t,user:r}=e;return g(r,t,"internal-error"),tr(r,new li(e),e.bypassAuthState)}async function ui(e){var{auth:t,user:r}=e;return g(r,t,"internal-error"),Zt(r,new li(e),e.bypassAuthState)}class pi{constructor(e,t,r,i,n=!1){this.auth=e,this.resolver=r,this.user=i,this.bypassAuthState=n,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}})}async onAuthEvent(e){var{urlResponse:t,sessionId:r,postBody:i,tenantId:n,error:s,type:a}=e;if(s)this.reject(s);else{s={auth:this.auth,requestUri:t,sessionId:r,tenantId:n||void 0,postBody:i||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(s))}catch(e){this.reject(e)}}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return di;case"linkViaPopup":case"linkViaRedirect":return ui;case"reauthViaPopup":case"reauthViaRedirect":return hi;default:h(this.auth,"internal-error")}}resolve(e){o(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){o(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}let mi=new Re(2e3,1e4);class L extends pi{constructor(e,t,r,i,n){super(e,t,i,n),this.provider=r,this.authWindow=null,this.pollId=null,L.currentPopupAction&&L.currentPopupAction.cancel(),L.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return g(e,this.auth,"internal-error"),e}async onExecution(){o(1===this.filter.length,"Popup operations only handle one event");var e=Vr();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(u(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(u(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,L.currentPopupAction=null}pollUserCancellation(){let e=()=>{this.authWindow?.window?.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(u(this.auth,"popup-closed-by-user"))},8e3):this.pollId=window.setTimeout(e,mi.get())};e()}}L.currentPopupAction=null;let gi="pendingRedirect",fi=new Map;class vi extends pi{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let t=fi.get(this.auth._key());if(!t){try{let e=await(async(e,t)=>{var r,i=wi(t),n=Ii(e);return!!await n._isAvailable()&&(r="true"===await n._get(i),await n._remove(i),r)})(this.resolver,this.auth)?await super.execute():null;t=()=>Promise.resolve(e)}catch(e){t=()=>Promise.reject(e)}fi.set(this.auth._key(),t)}return this.bypassAuthState||fi.set(this.auth._key(),()=>Promise.resolve(null)),t()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"===e.type)this.resolve(null);else if(e.eventId){var t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function _i(e,t){return Ii(e)._set(wi(t),"true")}function yi(e,t){fi.set(e._key(),t)}function Ii(e){return y(e._redirectPersistence)}function wi(e){return et(gi,e.config.apiKey,e.name)}function Ti(e,t,r){return(async(e,t,r)=>{var i,n;return Bn._isFirebaseServerApp(e.app)?Promise.reject(c(e)):(i=I(e),Te(e,t,k),await i._initializationPromise,await _i(n=ci(i,r),i),n._openRedirect(i,t,"signInViaRedirect"))})(e,t,r)}function Ei(e,t,r){return(async(e,t,r)=>{var i=a(e);if(Te(i.auth,t,k),Bn._isFirebaseServerApp(i.auth.app))return Promise.reject(c(i.auth));await i.auth._initializationPromise;var n=ci(i.auth,r),s=(await _i(n,i.auth),await Si(i));return n._openRedirect(i.auth,t,"reauthViaRedirect",s)})(e,t,r)}function bi(e,t,r){return(async(e,t,r)=>{var i=a(e),n=(Te(i.auth,t,k),await i.auth._initializationPromise,ci(i.auth,r)),s=(await er(!1,i,t.providerId),await _i(n,i.auth),await Si(i));return n._openRedirect(i.auth,t,"linkViaRedirect",s)})(e,t,r)}async function ki(e,t,r=!1){var i,n;return Bn._isFirebaseServerApp(e.app)?Promise.reject(c(e)):(n=ci(i=I(e),t),(n=await new vi(i,n,r).execute())&&!r&&(delete n.user._redirectEventId,await i._persistUserIfCurrent(n.user),await i._setRedirectUser(null,t)),n)}async function Si(e){var t=Vr(e.uid+":::");return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class Ri{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(t){if(this.hasEventBeenHandled(t))return!1;let r=!1;return this.consumers.forEach(e=>{this.isEventForConsumer(t,e)&&(r=!0,this.sendToConsumer(t,e),this.saveEventToCache(t))}),this.hasHandledPotentialRedirect||!(e=>{switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return 1;case"unknown":return Pi(e);default:return}})(t)||(this.hasHandledPotentialRedirect=!0,r)||(this.queuedRedirectEvent=t,r=!0),r}sendToConsumer(e,t){var r;e.error&&!Pi(e)?(r=e.error.code?.split("auth/")[1]||"internal-error",t.onError(u(this.auth,r))):t.onAuthEvent(e)}isEventForConsumer(e,t){var r=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return 6e5<=Date.now()-this.lastProcessedEventTime&&this.cachedEventUids.clear(),this.cachedEventUids.has(Ai(e))}saveEventToCache(e){this.cachedEventUids.add(Ai(e)),this.lastProcessedEventTime=Date.now()}}function Ai(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function Pi({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===t?.code}async function Ci(e,t={}){return m(e,"GET","/v1/projects",t)}let Ni=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Oi=/^https?/;async function Li(e){if(!e.config.emulator){var t,r=(await Ci(e)).authorizedDomains;for(t of r)try{if((e=>{var t,r=be(),{protocol:i,hostname:n}=new URL(r);return e.startsWith("chrome-extension://")?""===(t=new URL(e)).hostname&&""===n?"chrome-extension:"===i&&e.replace("chrome-extension://","")===r.replace("chrome-extension://",""):"chrome-extension:"===i&&t.hostname===n:Oi.test(i)&&(Ni.test(e)?n===e:(r=e.replace(/\./g,"\\."),(t=new RegExp("^(.+\\."+r+"|"+r+")$","i")).test(n)))})(t))return}catch{}h(e,"unauthorized-domain")}}let Di=new Re(3e4,6e4);function Mi(){var t=N().___jsl;if(t?.H)for(var r of Object.keys(t.H))if(t.H[r].r=t.H[r].r||[],t.H[r].L=t.H[r].L||[],t.H[r].r=[...t.H[r].L],t.CP)for(let e=0;e<t.CP.length;e++)t.CP[e]=null}function Ui(n){return new Promise((e,t)=>{function r(){Mi(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Mi(),t(u(n,"network-request-failed"))},timeout:Di.get()})}if(N().gapi?.iframes?.Iframe)e(gapi.iframes.getContext());else{var i;if(!N().gapi?.load)return i=yt("iframefcb"),N()[i]=()=>{gapi.load?r():t(u(n,"network-request-failed"))},_t(vt.gapiScript+"?onload="+i).catch(e=>t(e));r()}}).catch(e=>{throw Fi=null,e})}let Fi=null;let Vi=new Re(5e3,15e3),xi="__/auth/iframe",Wi="emulator/auth/iframe",Hi={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},ji=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function qi(a){e=a;var e,t,r,i=await(Fi=Fi||Ui(e)),n=N().gapi;return g(n,a,"internal-error"),i.open({where:document.body,url:(g((i=(e=a).config).authDomain,e,"auth-domain-config-required"),t=i.emulator?Ae(i,Wi):`https://${e.config.authDomain}/`+xi,i={apiKey:i.apiKey,appName:e.name,v:Bn.SDK_VERSION},(r=ji.get(e.config.apiHost))&&(i.eid=r),(r=e._getFrameworks()).length&&(i.fw=r.join(",")),t+"?"+re(i).slice(1)),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Hi,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});let r=u(a,"network-request-failed"),i=N().setTimeout(()=>{t(r)},Vi.get());function n(){N().clearTimeout(i),e(s)}s.ping(n).then(n,()=>{t(r)})}))}let Bi={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class zi{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function Gi(e,t,r,i=500,n=600){var s=Math.max((window.screen.availHeight-n)/2,0).toString(),a=Math.max((window.screen.availWidth-i)/2,0).toString();let o="";var c,s={...Bi,width:i.toString(),height:n.toString(),top:s,left:a},a=l().toLowerCase(),s=(r&&(o=st(a)?"_blank":r),it(a)&&(t=t||"http://localhost",s.scrollbars="yes"),Object.entries(s).reduce((e,[t,r])=>""+e+t+`=${r},`,""));if([i=l()]=[a],dt(i)&&window.navigator?.standalone&&"_self"!==o)return n=t||"",r=o,(a=document.createElement("a")).href=n,a.target=r,(c=document.createEvent("MouseEvent")).initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),a.dispatchEvent(c),new zi(null);a=window.open(t||"",o,s);g(a,e,"popup-blocked");try{a.focus()}catch(e){}return new zi(a)}let Ki="__/auth/handler",Ji="emulator/auth/handler",Yi=encodeURIComponent("fac");async function $i(e,t,r,i,n,s){g(e.config.authDomain,e,"auth-domain-config-required"),g(e.config.apiKey,e,"invalid-api-key");var a={apiKey:e.config.apiKey,appName:e.name,authType:r,redirectUrl:i,v:Bn.SDK_VERSION,eventId:n};if(t instanceof k){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",(e=>{for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return;return 1})(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(var[o,c]of Object.entries(s||{}))a[o]=c}t instanceof qt&&0<(h=t.getScopes().filter(e=>""!==e)).length&&(a.scopes=h.join(",")),e.tenantId&&(a.tid=e.tenantId);var l,d=a;for(l of Object.keys(d))void 0===d[l]&&delete d[l];var h=await e._getAppCheckToken(),h=h?`#${Yi}=`+encodeURIComponent(h):"";return`${r=[e.config][0],r.emulator?Ae(r,Ji):`https://${r.authDomain}/`+Ki}?`+re(d).slice(1)+h}let Xi="webStorageSupport";class Qi{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Ur,this._completeRedirectFn=ki,this._overrideRedirectResult=yi}async _openPopup(e,t,r,i){return o(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()"),Gi(e,await $i(e,t,r,be(),i),Vr())}async _openRedirect(e,t,r,i){await this._originValidation(e);var n=await $i(e,t,r,be(),i);return N().location.href=n,new Promise(()=>{})}_initialize(e){let r=e._key();if(this.eventManagers[r]){let{manager:e,promise:t}=this.eventManagers[r];return e?Promise.resolve(e):(o(t,"If manager is not set, promise should be"),t)}let t=this.initAndGetManager(e);return this.eventManagers[r]={promise:t},t.catch(()=>{delete this.eventManagers[r]}),t}async initAndGetManager(t){var e=await qi(t);let r=new Ri(t);return e.register("authEvent",e=>(g(e?.authEvent,t,"invalid-auth-event"),{status:r.onEvent(e.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:r},this.iframes[t._key()]=e,r}_isIframeWebStorageSupported(r,i){this.iframes[r._key()].send(Xi,{type:Xi},e=>{var t=e?.[0]?.[Xi];void 0!==t&&i(!!t),h(r,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Li(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return ht()||nt()||dt()}}let Zi=Qi;class en extends class{constructor(e){this.factorId=e}_process(e,t,r){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,r);case"signin":return this._finalizeSignIn(e,t.credential);default:return n("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new en(e)}_finalizeEnroll(e,t,r){return e=e,t={idToken:t,displayName:r,phoneVerificationInfo:this.credential._makeVerificationRequest()},m(e,"POST","/v2/accounts/mfaEnrollment:finalize",p(e,t))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},m(e,"POST","/v2/accounts/mfaSignIn:finalize",p(e,t))}}class tn{constructor(){}static assertion(e){return en._fromCredential(e)}}tn.FACTOR_ID="phone";var rn="@firebase/auth";class nn{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t(e?.stsTokenManager.accessToken||null)}),this.internalListeners.set(t,e),this.updateProactiveRefresh())}removeAuthTokenListener(e){this.assertAuthConfigured();var t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){g(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}var sn;function an(){return window}z()?._authIdTokenMaxAge,vt={loadJS(i){return new Promise((e,r)=>{var t=document.createElement("script");t.setAttribute("src",i),t.onload=e,t.onerror=e=>{var t=u("internal-error");t.customData=e,r(t)},t.type="text/javascript",t.charset="UTF-8",(document.getElementsByTagName("head")?.[0]??document).appendChild(t)})},gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="},sn="Browser",Bn._registerComponent(new ue("auth",(e,{options:t})=>{var r=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),n=e.getProvider("app-check-internal"),{apiKey:s,authDomain:a}=r.options,s=(g(s&&!s.includes(":"),"invalid-api-key",{appName:r.name}),{apiKey:s,authDomain:a,clientPlatform:sn,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:ut(sn)}),a=new gt(r,i,n,s);return e=a,r=(t=t)?.persistence||[],r=(Array.isArray(r)?r:[r]).map(y),t?.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,t?.popupRedirectResolver),a},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider("auth-internal").initialize()})),Bn._registerComponent(new ue("auth-internal",e=>{var t=I(e.getProvider("auth").getImmediate());return e=t,new nn(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),Bn.registerVersion(rn,"1.13.3",(e=>{switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}})(sn)),Bn.registerVersion(rn,"1.13.3","esm2020");async function on(e,t,r){var i=an().BuildInfo,n=(o(t.sessionId,"AuthEvent did not contain a session ID"),n=(e=>{if(o(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);var t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i);return r})(t.sessionId),n=await crypto.subtle.digest("SHA-256",n),await(n=Array.from(new Uint8Array(n))).map(e=>e.toString(16).padStart(2,"0")).join("")),s={};return dt()?s.ibi=i.packageName:ot()?s.apn=i.packageName:h(e,"operation-not-supported-in-this-environment"),i.displayName&&(s.appDisplayName=i.displayName),s.sessionId=n,$i(e,r,t.type,void 0,t.eventId??void 0,s)}function cn(i){let n=an().cordova;return new Promise(r=>{n.plugins.browsertab.isAvailable(e=>{let t=null;e?n.plugins.browsertab.openUrl(i):t=n.InAppBrowser.open(i,(e=l(),/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)?"_blank":"_system"),"location=yes"),r(t)})})}let ln=20;class dn extends Ri{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInitialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInitialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function hn(e,t,r=null){return{type:t,eventId:r,urlResponse:null,sessionId:(()=>{var e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let i=0;i<ln;i++){var r=Math.floor(Math.random()*t.length);e.push(t.charAt(r))}return e.join("")})(),postBody:null,tenantId:e.tenantId,error:u(e,"no-auth-event")}}async function un(e){var t=await mn()._get(gn(e));return t&&await mn()._remove(gn(e)),t}function pn(e,t){n=fn(t=t),r=n.link?decodeURIComponent(n.link):void 0,i=fn(r).link,n=n.deep_link_id?decodeURIComponent(n.deep_link_id):void 0;var r,i,n=fn(n).link||n||i||r||t;return n.includes("/__/auth/callback")?(i=(r=((i=fn(n)).firebaseError?(e=>{try{return JSON.parse(e)}catch(e){return null}})(decodeURIComponent(i.firebaseError)):null)?.code?.split("auth/")?.[1])?u(r):null)?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:i,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:n,postBody:null}:null}function mn(){return y(Dr)}function gn(e){return et("authEvent",e.config.apiKey,e.name)}function fn(e){var t,r;return e?.includes("?")?([t,...r]=e.split("?"),ie(r.join("?"))):{}}class vn{constructor(){this._redirectPersistence=Ur,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=ki,this._overrideRedirectResult=yi}async _initialize(e){var t=e._key();let r=this.eventManagers.get(t);return r||(r=new dn(e),this.eventManagers.set(t,r),this.attachCallbackListeners(e,r)),r}_openPopup(e){h(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,r,i){n=e,g("function"==typeof(s=an())?.universalLinks?.subscribe,n,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),g(void 0!==s?.BuildInfo?.packageName,n,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),g("function"==typeof s?.cordova?.plugins?.browsertab?.openUrl,n,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),g("function"==typeof s?.cordova?.plugins?.browsertab?.isAvailable,n,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),g("function"==typeof s?.cordova?.InAppBrowser?.open,n,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});var n,s=await this._initialize(e),a=(await s.initialized(),s.resetRedirect(),fi.clear(),await this._originValidation(e),hn(e,r,i)),a=(n=e,r=a,await mn()._set(gn(n),r),await on(e,a,t));return(async(a,o,c)=>{let l=an().cordova,d=()=>{};try{await new Promise((t,e)=>{let r=null;function i(){t();var e=l.plugins.browsertab?.close;"function"==typeof e&&e(),"function"==typeof c?.close&&c.close()}function n(){r=r||window.setTimeout(()=>{e(u(a,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===document?.visibilityState&&n()}o.addPassiveListener(i),document.addEventListener("resume",n,!1),ot()&&document.addEventListener("visibilitychange",s,!1),d=()=>{o.removePassiveListener(i),document.removeEventListener("resume",n,!1),document.removeEventListener("visibilitychange",s,!1),r&&window.clearTimeout(r)}})}finally{d()}})(e,s,await cn(a))}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=(async e=>{var t=an().BuildInfo,r={};dt()?r.iosBundleId=t.packageName:ot()?r.androidPackageName=t.packageName:h(e,"operation-not-supported-in-this-environment"),await Ci(e,r)})(e)),this.originValidationPromises[t]}attachCallbackListeners(i,n){var{universalLinks:e,handleOpenURL:t,BuildInfo:r}=an();let s=setTimeout(async()=>{await un(i),n.onEvent(yn())},500),a=async e=>{clearTimeout(s);var t=await un(i);let r=null;t&&e?.url&&(r=pn(t,e.url)),n.onEvent(r||yn())},o=(void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,a),t),c=r.packageName.toLowerCase()+"://";an().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&a({url:e}),"function"==typeof o)try{o(e)}catch(e){console.error(e)}}}}let _n=vn;function yn(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:u("no-auth-event")}}var e;function In(){return self?.location?.protocol||null}function wn(e=l()){return!("file:"!==In()&&"ionic:"!==In()&&"capacitor:"!==In()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function Tn(e=l()){return $()&&11===document?.documentMode||([e=l()]=[e],/Edge\/\d+/.test(e))}function En(){try{var e=self.localStorage,t=Vr();if(e)return e.setItem(t,"1"),e.removeItem(t),!Tn()||X()}catch(e){return bn()&&X()}return!1}function bn(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function kn(){return("http:"===In()||"https:"===In()||J()||wn())&&!(Y()||K())&&En()&&!bn()}function Sn(){return wn()&&"undefined"!=typeof document}let D={LOCAL:"local",NONE:"none",SESSION:"session"},Rn=g,An="persistence";async function Pn(e){await e._initializationPromise;var t=Cn(),r=et(An,e.config.apiKey,e.name);t&&t.setItem(r,e._getPersistenceType())}function Cn(){try{return("undefined"!=typeof window?window:null)?.sessionStorage||null}catch(e){return null}}let Nn=g;class M{constructor(){this.browserResolver=y(Zi),this.cordovaResolver=y(_n),this.underlyingResolver=null,this._redirectPersistence=Ur,this._completeRedirectFn=ki,this._overrideRedirectResult=yi}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,r,i){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,r,i)}async _openRedirect(e,t,r,i){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,r,i)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return Sn()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return Nn(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!Sn()&&new Promise(e=>{let t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function On(e){return e.unwrap()}function Ln(e,t){var r,i,n,s=t.customData?._tokenResponse;"auth/multi-factor-auth-required"===t?.code?t.resolver=new Un(e,(r=t,i=a(e),g((n=r).customData.operationType,i,"argument-error"),g(n.customData._serverResponse?.mfaPendingCredential,i,"argument-error"),Rr._fromError(i,n))):s&&(n=Dn(i=t))&&(i.credential=n,i.tenantId=s.tenantId||void 0,i.email=s.email||void 0,i.phoneNumber=s.phoneNumber||void 0)}function Dn(e){var t=(e instanceof d?e.customData:e)._tokenResponse;if(!t)return null;if(!(e instanceof d)&&"temporaryProof"in t&&"phoneNumber"in t)return O.credentialFromResult(e);var r=t.providerId;if(!r||r===pe.PASSWORD)return null;let i;switch(r){case pe.GOOGLE:i=R;break;case pe.FACEBOOK:i=S;break;case pe.GITHUB:i=A;break;case pe.TWITTER:i=P;break;default:var{oauthIdToken:n,oauthAccessToken:s,oauthTokenSecret:a,pendingToken:o,nonce:c}=t;return s||a||n||o?o?r.startsWith("saml.")?zt._create(r,o):b._fromParams({providerId:r,signInMethod:r,pendingToken:o,idToken:n,accessToken:s}):new Bt(r).credential({idToken:n,accessToken:s,rawNonce:c}):null}return e instanceof d?i.credentialFromError(e):i.credentialFromResult(e)}function U(t,e){return e.catch(e=>{throw e instanceof d&&Ln(t,e),e}).then(e=>{var t=e.operationType,r=e.user;return{operationType:t,credential:Dn(e),additionalUserInfo:kr(e),user:F.getOrCreate(r)}})}async function Mn(t,e){let r=await e;return{verificationId:r.verificationId,confirm:e=>U(t,r.confirm(e))}}class Un{constructor(e,t){this.resolver=t,this.auth=e.wrapped()}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return U(On(this.auth),this.resolver.resolveSignIn(e))}}class F{constructor(e){var t;this._delegate=e,this.multiFactor=(t=a(e),Cr.has(t)||Cr.set(t,Pr._fromUser(t)),Cr.get(t))}static getOrCreate(e){return F.USER_MAP.has(e)||F.USER_MAP.set(e,new F(e)),F.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return U(this.auth,nr(this._delegate,e))}async linkWithPhoneNumber(e,t){return Mn(this.auth,(async(e,t,r)=>{let i=a(e);await er(!1,i,"phone");var n=await ai(i.auth,t,a(r));return new si(n,e=>nr(i,e))})(this._delegate,e,t))}async linkWithPopup(e){return U(this.auth,(async(e,t,r)=>{var i=a(e),n=(Te(i.auth,t,k),ci(i.auth,r));return new L(i.auth,"linkViaPopup",t,n,i).executeNotNull()})(this._delegate,e,M))}async linkWithRedirect(e){return await Pn(I(this.auth)),bi(this._delegate,e,M)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return U(this.auth,sr(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return Mn(this.auth,(async(e,t,r)=>{let i=a(e);var n;return Bn._isFirebaseServerApp(i.auth.app)?Promise.reject(c(i.auth)):(n=await ai(i.auth,t,a(r)),new si(n,e=>sr(i,e)))})(this._delegate,e,t))}reauthenticateWithPopup(e){return U(this.auth,(async(e,t,r)=>{var i=a(e);if(Bn._isFirebaseServerApp(i.auth.app))return Promise.reject(u(i.auth,"operation-not-supported-in-this-environment"));Te(i.auth,t,k);var n=ci(i.auth,r);return new L(i.auth,"reauthViaPopup",t,n,i).executeNotNull()})(this._delegate,e,M))}async reauthenticateWithRedirect(e){return await Pn(I(this.auth)),Ei(this._delegate,e,M)}sendEmailVerification(e){return gr(this._delegate,e)}async unlink(e){return await Qt(this._delegate,e),this}updateEmail(e){return t=this._delegate,e=e,r=a(t),Bn._isFirebaseServerApp(r.auth.app)?Promise.reject(c(r.auth)):_r(r,e,null);var t,r}updatePassword(e){return _r(a(this._delegate),null,e)}updatePhoneNumber(e){return(async(e,t)=>{var r=a(e);if(Bn._isFirebaseServerApp(r.auth.app))return Promise.reject(c(r.auth));await Zt(r,t)})(this._delegate,e)}updateProfile(e){return vr(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return fr(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}F.USER_MAP=new WeakMap;let Fn=g;class Vn{constructor(e,t){var r,i;this.app=e,t.isInitialized()?this._delegate=t.getImmediate():(r=e.options.apiKey,Fn(r,"invalid-api-key",{appName:e.name}),Fn(r,"invalid-api-key",{appName:e.name}),i="undefined"!=typeof window?M:void 0,this._delegate=t.initialize({options:{persistence:((e,t)=>{var r=((e,t)=>{var r=Cn();if(!r)return[];var i=et(An,e,t);switch(r.getItem(i)){case D.NONE:return[Ze];case D.LOCAL:return[$r,Ur];case D.SESSION:return[Ur];default:return[]}})(e,t);if("undefined"==typeof self||r.includes($r)||r.push($r),"undefined"!=typeof window)for(var i of[Dr,Ur])r.includes(i)||r.push(i);return r.includes(Ze)||r.push(Ze),r})(r,e.name),popupRedirectResolver:i}}),this._delegate._updateErrorMap(fe)),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?F.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){Rt(this._delegate,e,t)}applyActionCode(e){return ur(this._delegate,e)}checkActionCode(e){return pr(this._delegate,e)}confirmPasswordReset(e,t){return(async(t,e,r)=>{await Nt(a(t),{oobCode:e,newPassword:r}).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&hr(t),e})})(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return U(this._delegate,(async(t,e,r)=>{var i,n;return Bn._isFirebaseServerApp(t.app)?Promise.reject(c(t)):(n=await T(i=I(t),{returnSecureToken:!0,email:e,password:r,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",Kt,"EMAIL_PASSWORD_PROVIDER").catch(e=>{throw"auth/password-does-not-meet-requirements"===e.code&&hr(t),e}),n=await C._fromIdTokenResponse(i,"signIn",n),await i._updateCurrentUser(n.user),n)})(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return mr(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===Ht.parseLink(e)?.operation}async getRedirectResult(){Fn(kn(),this._delegate,"operation-not-supported-in-this-environment");e=this._delegate,t=M,await I(e)._initializationPromise;var e,t,r=await ki(e,t,!1);return r?U(this._delegate,Promise.resolve(r)):{credential:null,user:null}}addFrameworkForLogging(e){I(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,r){var{next:i,error:n,complete:s}=xn(e,t,r);return this._delegate.onAuthStateChanged(i,n,s)}onIdTokenChanged(e,t,r){var{next:i,error:n,complete:s}=xn(e,t,r);return this._delegate.onIdTokenChanged(i,n,s)}sendSignInLinkToEmail(e,t){return(async(e,t,r)=>{let i=I(e);var n={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};e=n,g((t=r).handleCodeInApp,i,"argument-error"),t&&dr(i,e,t),await T(i,n,"getOobCode",Ut,"EMAIL_PASSWORD_PROVIDER")})(this._delegate,e,t)}sendPasswordResetEmail(e,t){return(async(e,t,r)=>{var i=I(e),n={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};r&&dr(i,n,r),await T(i,n,"getOobCode",Mt,"EMAIL_PASSWORD_PROVIDER")})(this._delegate,e,t||void 0)}async setPersistence(e){var t,r;t=this._delegate,r=e,Rn(Object.values(D).includes(r),t,"invalid-persistence-type"),Y()?Rn(r!==D.SESSION,t,"unsupported-persistence-type"):K()?Rn(r===D.NONE,t,"unsupported-persistence-type"):bn()?Rn(r===D.NONE||r===D.LOCAL&&X(),t,"unsupported-persistence-type"):Rn(r===D.NONE||En(),t,"unsupported-persistence-type");let i;switch(e){case D.SESSION:i=Ur;break;case D.LOCAL:var n=await y($r)._isAvailable();i=n?$r:Dr;break;case D.NONE:i=Ze;break;default:return h("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(i)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return U(this._delegate,(async e=>{var t,r;return Bn._isFirebaseServerApp(e.app)?Promise.reject(c(e)):(await(t=I(e))._initializationPromise,t.currentUser?.isAnonymous?new C({user:t.currentUser,providerId:null,operationType:"signIn"}):(r=await Kt(t,{returnSecureToken:!0}),r=await C._fromIdTokenResponse(t,"signIn",r,!0),await t._updateCurrentUser(r.user),r))})(this._delegate))}signInWithCredential(e){return U(this._delegate,ir(this._delegate,e))}signInWithCustomToken(e){return U(this._delegate,ar(this._delegate,e))}signInWithEmailAndPassword(e,t){return U(this._delegate,(r=this._delegate,e=e,t=t,Bn._isFirebaseServerApp(r.app)?Promise.reject(c(r)):ir(a(r),jt.credential(e,t)).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&hr(r),e})));var r}signInWithEmailLink(e,t){return U(this._delegate,(async(e,t,r)=>{var i,n;return Bn._isFirebaseServerApp(e.app)?Promise.reject(c(e)):(i=a(e),g((n=jt.credentialWithLink(t,r||be()))._tenantId===(i.tenantId||null),i,"tenant-id-mismatch"),ir(i,n))})(this._delegate,e,t))}signInWithPhoneNumber(e,t){return Mn(this._delegate,(async(e,t,r)=>{if(Bn._isFirebaseServerApp(e.app))return Promise.reject(c(e));let i=I(e);var n=await ai(i,t,a(r));return new si(n,e=>ir(i,e))})(this._delegate,e,t))}async signInWithPopup(e){return Fn(kn(),this._delegate,"operation-not-supported-in-this-environment"),U(this._delegate,(async(e,t,r)=>{var i,n;return Bn._isFirebaseServerApp(e.app)?Promise.reject(u(e,"operation-not-supported-in-this-environment")):(i=I(e),Te(e,t,k),n=ci(i,r),new L(i,"signInViaPopup",t,n).executeNotNull())})(this._delegate,e,M))}async signInWithRedirect(e){return Fn(kn(),this._delegate,"operation-not-supported-in-this-environment"),await Pn(this._delegate),Ti(this._delegate,e,M)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return(async(e,t)=>{var r=(await pr(a(e),t)).data;return r.email})(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function xn(e,t,r){let i=e,n=("function"!=typeof e&&({next:i,error:t,complete:r}=e),i);return{next:e=>n(e&&F.getOrCreate(e)),error:t,complete:r}}Vn.Persistence=D;class Wn{static credential(e,t){return O.credential(e,t)}constructor(){this.providerId="phone",this._delegate=new O(On(V.default.auth()))}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}Wn.PHONE_SIGN_IN_METHOD=O.PHONE_SIGN_IN_METHOD,Wn.PROVIDER_ID=O.PROVIDER_ID;let Hn=g;class jn{constructor(e,t,r=V.default.app()){Hn(r.options?.apiKey,"invalid-api-key",{appName:r.name}),this._delegate=new ni(r.auth(),e,t),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(e=V.default).INTERNAL.registerComponent(new ue("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("auth");return new Vn(t,r)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:me.EMAIL_SIGNIN,PASSWORD_RESET:me.PASSWORD_RESET,RECOVER_EMAIL:me.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:me.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:me.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:me.VERIFY_EMAIL}},EmailAuthProvider:jt,FacebookAuthProvider:S,GithubAuthProvider:A,GoogleAuthProvider:R,OAuthProvider:Bt,SAMLAuthProvider:Gt,PhoneAuthProvider:Wn,PhoneMultiFactorGenerator:tn,RecaptchaVerifier:jn,TwitterAuthProvider:P,Auth:Vn,AuthCredential:Ct,Error:d}).setInstantiationMode("LAZY").setMultipleInstances(!1)),e.registerVersion("@firebase/auth-compat","0.6.8")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-auth-compat.js - be sure to load firebase-app.js first.")}});
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import{_getProvider,_isFirebaseServerApp as e,_registerComponent as t,registerVersion as r,SDK_VERSION as n,getApp as i}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";const s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const i=e[t],s=t+1<e.length,o=s?e[t+1]:0,a=t+2<e.length,c=a?e[t+2]:0,d=i>>2,u=(3&i)<<4|o>>4;let l=(15&o)<<2|c>>6,h=63&c;a||(h=64,s||(l=64)),n.push(r[d],r[u],r[l],r[h])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=63&i|128):55296==(64512&i)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++n)),t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const i=e[r++];if(i<128)t[n++]=String.fromCharCode(i);else if(i>191&&i<224){const s=e[r++];t[n++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{const s=e[r++],o=e[r++];t[n++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const i=r[e.charAt(t++)],s=t<e.length?r[e.charAt(t)]:0;++t;const o=t<e.length?r[e.charAt(t)]:64;++t;const a=t<e.length?r[e.charAt(t)]:64;if(++t,null==i||null==s||null==o||null==a)throw new DecodeBase64StringError;const c=i<<2|s>>4;if(n.push(c),64!==o){const e=s<<4&240|o>>2;if(n.push(e),64!==a){const e=o<<6&192|a;n.push(e)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64Decode=function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&base64Decode(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}};class Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,r)=>{t?this.reject(t):this.resolve(r),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,r))}}}function getUA(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,i=this.errors[e],s=i?function replaceTemplate(e,t){return e.replace(o,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(i,r):"Error",a=`${this.serviceName}: ${s} (${n}).`;return new FirebaseError(n,a,r)}}const o=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const r=Object.keys(e),n=Object.keys(t);for(const i of r){if(!n.includes(i))return!1;const r=e[i],s=t[i];if(isObject(r)&&isObject(s)){if(!deepEqual(r,s))return!1}else if(r!==s)return!1}for(const e of n)if(!r.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function querystring(e){const t=[];for(const[r,n]of Object.entries(e))Array.isArray(n)?n.forEach((e=>{t.push(encodeURIComponent(r)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(r)+"="+encodeURIComponent(n));return t.length?"&"+t.join("&"):""}function querystringDecode(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[r,n]=e.split("=");t[decodeURIComponent(r)]=decodeURIComponent(n)}})),t}function extractQuerystring(e){const t=e.indexOf("?");if(!t)return"";const r=e.indexOf("#",t);return e.substring(t,r>0?r:void 0)}class ObserverProxy{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,r){let n;if(void 0===e&&void 0===t&&void 0===r)throw new Error("Missing Observer.");n=function implementsAnyMethods(e,t){if("object"!=typeof e||null===e)return!1;for(const r of t)if(r in e&&"function"==typeof e[r])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:r},void 0===n.next&&(n.next=noop),void 0===n.error&&(n.error=noop),void 0===n.complete&&(n.complete=noop);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?n.error(this.finalError):n.complete()}catch(e){}})),this.observers.push(n),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then((()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function noop(){}function getModularInstance(e){return e&&e._delegate?e._delegate:e}function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var a;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(a||(a={}));const c={debug:a.DEBUG,verbose:a.VERBOSE,info:a.INFO,warn:a.WARN,error:a.ERROR,silent:a.SILENT},d=a.INFO,u={[a.DEBUG]:"log",[a.VERBOSE]:"log",[a.INFO]:"info",[a.WARN]:"warn",[a.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const n=(new Date).toISOString(),i=u[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${n}] ${e.name}:`,...r)};function _prodErrorMap(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const l=function _debugErrorMap(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registered for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is incorrect, malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-password":"A non-empty password must be provided","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.","missing-recaptcha-token":"The reCAPTCHA token is missing when sending request to the backend.","invalid-recaptcha-token":"The reCAPTCHA token is invalid when sending request to the backend.","invalid-recaptcha-action":"The reCAPTCHA action is invalid when sending request to the backend.","recaptcha-not-enabled":"reCAPTCHA Enterprise integration is not enabled for this project.","missing-client-type":"The reCAPTCHA client type is missing when sending request to the backend.","missing-recaptcha-version":"The reCAPTCHA version is missing when sending request to the backend.","invalid-req-type":"Invalid request parameters.","invalid-recaptcha-version":"The reCAPTCHA version is invalid when sending request to the backend.","unsupported-password-policy-schema-version":"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.","password-does-not-meet-requirements":"The password does not meet the requirements.","invalid-hosting-link-domain":"The provided Hosting link domain is not configured in Firebase Hosting or is not owned by the current project. This cannot be a default Hosting domain (`web.app` or `firebaseapp.com`)."}},h=_prodErrorMap,p=new ErrorFactory("auth","Firebase",{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}),f={ADMIN_ONLY_OPERATION:"auth/admin-restricted-operation",ARGUMENT_ERROR:"auth/argument-error",APP_NOT_AUTHORIZED:"auth/app-not-authorized",APP_NOT_INSTALLED:"auth/app-not-installed",CAPTCHA_CHECK_FAILED:"auth/captcha-check-failed",CODE_EXPIRED:"auth/code-expired",CORDOVA_NOT_READY:"auth/cordova-not-ready",CORS_UNSUPPORTED:"auth/cors-unsupported",CREDENTIAL_ALREADY_IN_USE:"auth/credential-already-in-use",CREDENTIAL_MISMATCH:"auth/custom-token-mismatch",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"auth/requires-recent-login",DEPENDENT_SDK_INIT_BEFORE_AUTH:"auth/dependent-sdk-initialized-before-auth",DYNAMIC_LINK_NOT_ACTIVATED:"auth/dynamic-link-not-activated",EMAIL_CHANGE_NEEDS_VERIFICATION:"auth/email-change-needs-verification",EMAIL_EXISTS:"auth/email-already-in-use",EMULATOR_CONFIG_FAILED:"auth/emulator-config-failed",EXPIRED_OOB_CODE:"auth/expired-action-code",EXPIRED_POPUP_REQUEST:"auth/cancelled-popup-request",INTERNAL_ERROR:"auth/internal-error",INVALID_API_KEY:"auth/invalid-api-key",INVALID_APP_CREDENTIAL:"auth/invalid-app-credential",INVALID_APP_ID:"auth/invalid-app-id",INVALID_AUTH:"auth/invalid-user-token",INVALID_AUTH_EVENT:"auth/invalid-auth-event",INVALID_CERT_HASH:"auth/invalid-cert-hash",INVALID_CODE:"auth/invalid-verification-code",INVALID_CONTINUE_URI:"auth/invalid-continue-uri",INVALID_CORDOVA_CONFIGURATION:"auth/invalid-cordova-configuration",INVALID_CUSTOM_TOKEN:"auth/invalid-custom-token",INVALID_DYNAMIC_LINK_DOMAIN:"auth/invalid-dynamic-link-domain",INVALID_EMAIL:"auth/invalid-email",INVALID_EMULATOR_SCHEME:"auth/invalid-emulator-scheme",INVALID_IDP_RESPONSE:"auth/invalid-credential",INVALID_LOGIN_CREDENTIALS:"auth/invalid-credential",INVALID_MESSAGE_PAYLOAD:"auth/invalid-message-payload",INVALID_MFA_SESSION:"auth/invalid-multi-factor-session",INVALID_OAUTH_CLIENT_ID:"auth/invalid-oauth-client-id",INVALID_OAUTH_PROVIDER:"auth/invalid-oauth-provider",INVALID_OOB_CODE:"auth/invalid-action-code",INVALID_ORIGIN:"auth/unauthorized-domain",INVALID_PASSWORD:"auth/wrong-password",INVALID_PERSISTENCE:"auth/invalid-persistence-type",INVALID_PHONE_NUMBER:"auth/invalid-phone-number",INVALID_PROVIDER_ID:"auth/invalid-provider-id",INVALID_RECIPIENT_EMAIL:"auth/invalid-recipient-email",INVALID_SENDER:"auth/invalid-sender",INVALID_SESSION_INFO:"auth/invalid-verification-id",INVALID_TENANT_ID:"auth/invalid-tenant-id",MFA_INFO_NOT_FOUND:"auth/multi-factor-info-not-found",MFA_REQUIRED:"auth/multi-factor-auth-required",MISSING_ANDROID_PACKAGE_NAME:"auth/missing-android-pkg-name",MISSING_APP_CREDENTIAL:"auth/missing-app-credential",MISSING_AUTH_DOMAIN:"auth/auth-domain-config-required",MISSING_CODE:"auth/missing-verification-code",MISSING_CONTINUE_URI:"auth/missing-continue-uri",MISSING_IFRAME_START:"auth/missing-iframe-start",MISSING_IOS_BUNDLE_ID:"auth/missing-ios-bundle-id",MISSING_OR_INVALID_NONCE:"auth/missing-or-invalid-nonce",MISSING_MFA_INFO:"auth/missing-multi-factor-info",MISSING_MFA_SESSION:"auth/missing-multi-factor-session",MISSING_PHONE_NUMBER:"auth/missing-phone-number",MISSING_PASSWORD:"auth/missing-password",MISSING_SESSION_INFO:"auth/missing-verification-id",MODULE_DESTROYED:"auth/app-deleted",NEED_CONFIRMATION:"auth/account-exists-with-different-credential",NETWORK_REQUEST_FAILED:"auth/network-request-failed",NULL_USER:"auth/null-user",NO_AUTH_EVENT:"auth/no-auth-event",NO_SUCH_PROVIDER:"auth/no-such-provider",OPERATION_NOT_ALLOWED:"auth/operation-not-allowed",OPERATION_NOT_SUPPORTED:"auth/operation-not-supported-in-this-environment",POPUP_BLOCKED:"auth/popup-blocked",POPUP_CLOSED_BY_USER:"auth/popup-closed-by-user",PROVIDER_ALREADY_LINKED:"auth/provider-already-linked",QUOTA_EXCEEDED:"auth/quota-exceeded",REDIRECT_CANCELLED_BY_USER:"auth/redirect-cancelled-by-user",REDIRECT_OPERATION_PENDING:"auth/redirect-operation-pending",REJECTED_CREDENTIAL:"auth/rejected-credential",SECOND_FACTOR_ALREADY_ENROLLED:"auth/second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"auth/maximum-second-factor-count-exceeded",TENANT_ID_MISMATCH:"auth/tenant-id-mismatch",TIMEOUT:"auth/timeout",TOKEN_EXPIRED:"auth/user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"auth/too-many-requests",UNAUTHORIZED_DOMAIN:"auth/unauthorized-continue-uri",UNSUPPORTED_FIRST_FACTOR:"auth/unsupported-first-factor",UNSUPPORTED_PERSISTENCE:"auth/unsupported-persistence-type",UNSUPPORTED_TENANT_OPERATION:"auth/unsupported-tenant-operation",UNVERIFIED_EMAIL:"auth/unverified-email",USER_CANCELLED:"auth/user-cancelled",USER_DELETED:"auth/user-not-found",USER_DISABLED:"auth/user-disabled",USER_MISMATCH:"auth/user-mismatch",USER_SIGNED_OUT:"auth/user-signed-out",WEAK_PASSWORD:"auth/weak-password",WEB_STORAGE_UNSUPPORTED:"auth/web-storage-unsupported",ALREADY_INITIALIZED:"auth/already-initialized",RECAPTCHA_NOT_ENABLED:"auth/recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"auth/missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"auth/invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"auth/invalid-recaptcha-action",MISSING_CLIENT_TYPE:"auth/missing-client-type",MISSING_RECAPTCHA_VERSION:"auth/missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"auth/invalid-recaptcha-version",INVALID_REQ_TYPE:"auth/invalid-req-type",INVALID_HOSTING_LINK_DOMAIN:"auth/invalid-hosting-link-domain"},m=new class Logger{constructor(e){this.name=e,this._logLevel=d,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in a))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?c[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,a.DEBUG,...e),this._logHandler(this,a.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,a.VERBOSE,...e),this._logHandler(this,a.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,a.INFO,...e),this._logHandler(this,a.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,a.WARN,...e),this._logHandler(this,a.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,a.ERROR,...e),this._logHandler(this,a.ERROR,...e)}}("@firebase/auth");function _logError(e,...t){m.logLevel<=a.ERROR&&m.error(`Auth (${n}): ${e}`,...t)}function _fail(e,...t){throw createErrorInternal(e,...t)}function _createError(e,...t){return createErrorInternal(e,...t)}function _errorWithCustomMessage(e,t,r){const n={...h(),[t]:r};return new ErrorFactory("auth","Firebase",n).create(t,{appName:e.name})}function _serverAppCurrentUserOperationNotSupportedError(e){return _errorWithCustomMessage(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function createErrorInternal(e,...t){if("string"!=typeof e){const r=t[0],n=[...t.slice(1)];return n[0]&&(n[0].appName=e.name),e._errorFactory.create(r,...n)}return p.create(e,...t)}function _assert(e,t,...r){if(!e)throw createErrorInternal(t,...r)}function debugFail(e){const t="INTERNAL ASSERTION FAILED: "+e;throw _logError(t),new Error(t)}function debugAssert(e,t){e||debugFail(t)}function _getCurrentUrl(){return"undefined"!=typeof self&&self.location?.href||""}function _isHttpOrHttps(){return"http:"===_getCurrentScheme()||"https:"===_getCurrentScheme()}function _getCurrentScheme(){return"undefined"!=typeof self&&self.location?.protocol||null}function _isOnline(){return!("undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(_isHttpOrHttps()||function isBrowserExtension(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}()||"connection"in navigator))||navigator.onLine}class FetchProvider{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!=typeof self&&"fetch"in self?self.fetch:"undefined"!=typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!=typeof fetch?fetch:void debugFail("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"undefined"!=typeof self&&"Headers"in self?self.Headers:"undefined"!=typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!=typeof Headers?Headers:void debugFail("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"undefined"!=typeof self&&"Response"in self?self.Response:"undefined"!=typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!=typeof Response?Response:void debugFail("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const g={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},_=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],I=new class Delay{constructor(e,t){this.shortDelay=e,this.longDelay=t,debugAssert(t>e,"Short delay should be less than long delay!"),this.isMobile=function isMobileCordova(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())}()||function isReactNative(){return"object"==typeof navigator&&"ReactNative"===navigator.product}()}get(){return _isOnline()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}(3e4,6e4);function _addTidIfNecessary(e,t){return e.tenantId&&!t.tenantId?{...t,tenantId:e.tenantId}:t}async function _performApiRequest(e,t,r,n,i={}){return _performFetchWithErrorHandling(e,i,(async()=>{let i={},s={};n&&("GET"===t?s=n:i={body:JSON.stringify(n)});const o=querystring({...s,key:e.config.apiKey}).slice(1),a=await e._getAdditionalHeaders();a["Content-Type"]="application/json",e.languageCode&&(a["X-Firebase-Locale"]=e.languageCode);const c={method:t,headers:a,...i};return function isCloudflareWorker(){return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent}()||(c.referrerPolicy="strict-origin-when-cross-origin"),e.emulatorConfig&&isCloudWorkstation(e.emulatorConfig.host)&&(c.credentials="include"),FetchProvider.fetch()(await _getFinalTarget(e,e.config.apiHost,r,o),c)}))}async function _performFetchWithErrorHandling(e,t,r){e._canInitEmulator=!1;const n={...g,...t};try{const t=new NetworkTimeout(e),i=await Promise.race([r(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if("needConfirmation"in s)throw _makeTaggedError(e,"account-exists-with-different-credential",s);if(i.ok&&!("errorMessage"in s))return s;{const t=i.ok?s.errorMessage:s.error.message,[r,o]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===r)throw _makeTaggedError(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===r)throw _makeTaggedError(e,"email-already-in-use",s);if("USER_DISABLED"===r)throw _makeTaggedError(e,"user-disabled",s);const a=n[r]||r.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw _errorWithCustomMessage(e,a,o);_fail(e,a)}}catch(t){if(t instanceof FirebaseError)throw t;_fail(e,"network-request-failed",{message:String(t)})}}async function _performSignInRequest(e,t,r,n,i={}){const s=await _performApiRequest(e,t,r,n,i);return"mfaPendingCredential"in s&&_fail(e,"multi-factor-auth-required",{_serverResponse:s}),s}async function _getFinalTarget(e,t,r,n){const i=`${t}${r}?${n}`,s=e,o=s.config.emulator?function _emulatorUrl(e,t){debugAssert(e.emulator,"Emulator should always be set here");const{url:r}=e.emulator;return t?`${r}${t.startsWith("/")?t.slice(1):t}`:r}(e.config,i):`${e.config.apiScheme}://${i}`;if(_.includes(r)&&(await s._persistenceManagerAvailable,"COOKIE"===s._getPersistenceType())){return s._getPersistence()._getFinalTarget(o).toString()}return o}function _parseEnforcementState(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class NetworkTimeout{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(_createError(this.auth,"network-request-failed"))),I.get())}))}}function _makeTaggedError(e,t,r){const n={appName:e.name};r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber);const i=_createError(e,t,n);return i.customData._tokenResponse=r,i}function isEnterprise(e){return void 0!==e&&void 0!==e.enterprise}class RecaptchaConfig{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return _parseEnforcementState(t.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function getRecaptchaConfig(e,t){return _performApiRequest(e,"GET","/v2/recaptchaConfig",_addTidIfNecessary(e,t))}async function getAccountInfo(e,t){return _performApiRequest(e,"POST","/v1/accounts:lookup",t)}function utcTimestampToDateString(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function getIdToken(e,t=!1){return getModularInstance(e).getIdToken(t)}async function getIdTokenResult(e,t=!1){const r=getModularInstance(e),n=await r.getIdToken(t),i=_parseToken(n);_assert(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error");const s="object"==typeof i.firebase?i.firebase:void 0,o=s?.sign_in_provider;return{claims:i,token:n,authTime:utcTimestampToDateString(secondsStringToMilliseconds(i.auth_time)),issuedAtTime:utcTimestampToDateString(secondsStringToMilliseconds(i.iat)),expirationTime:utcTimestampToDateString(secondsStringToMilliseconds(i.exp)),signInProvider:o||null,signInSecondFactor:s?.sign_in_second_factor||null}}function secondsStringToMilliseconds(e){return 1e3*Number(e)}function _parseToken(e){const[t,r,n]=e.split(".");if(void 0===t||void 0===r||void 0===n)return _logError("JWT malformed, contained fewer than 3 sections"),null;try{const e=base64Decode(r);return e?JSON.parse(e):(_logError("Failed to decode base64 JWT payload"),null)}catch(e){return _logError("Caught error parsing JWT payload as JSON",e?.toString()),null}}function _tokenExpiresIn(e){const t=_parseToken(e);return _assert(t,"internal-error"),_assert(void 0!==t.exp,"internal-error"),_assert(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function _logoutIfInvalidated(e,t,r=!1){if(r)return t;try{return await t}catch(t){throw t instanceof FirebaseError&&function isUserInvalidated({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class ProactiveRefresh{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,e)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout((async()=>{await this.iteration()}),t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===e?.code&&this.schedule(!0))}this.schedule()}}class UserMetadata{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=utcTimestampToDateString(this.lastLoginAt),this.creationTime=utcTimestampToDateString(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function _reloadWithoutSaving(e){const t=e.auth,r=await e.getIdToken(),n=await _logoutIfInvalidated(e,getAccountInfo(t,{idToken:r}));_assert(n?.users.length,t,"internal-error");const i=n.users[0];e._notifyReloadListener(i);const s=i.providerUserInfo?.length?extractProviderData(i.providerUserInfo):[],o=function mergeProviderData(e,t){return[...e.filter((e=>!t.some((t=>t.providerId===e.providerId)))),...t]}(e.providerData,s),a=e.isAnonymous,c=!(e.email&&i.passwordHash||o?.length),d=!!a&&c,u={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:o,metadata:new UserMetadata(i.createdAt,i.lastLoginAt),isAnonymous:d};Object.assign(e,u)}async function reload(e){const t=getModularInstance(e);await _reloadWithoutSaving(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}function extractProviderData(e){return e.map((({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null})))}class StsTokenManager{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){_assert(e.idToken,"internal-error"),_assert(void 0!==e.idToken,"internal-error"),_assert(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):_tokenExpiresIn(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){_assert(0!==e.length,"internal-error");const t=_tokenExpiresIn(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(_assert(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null):this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:r,refreshToken:n,expiresIn:i}=await async function requestStsToken(e,t){const r=await _performFetchWithErrorHandling(e,{},(async()=>{const r=querystring({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:n,apiKey:i}=e.config,s=await _getFinalTarget(e,n,"/v1/token",`key=${i}`),o=await e._getAdditionalHeaders();o["Content-Type"]="application/x-www-form-urlencoded";const a={method:"POST",headers:o,body:r};return e.emulatorConfig&&isCloudWorkstation(e.emulatorConfig.host)&&(a.credentials="include"),FetchProvider.fetch()(s,a)}));return{accessToken:r.access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token}}(e,t);this.updateTokensAndExpiration(r,n,Number(i))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*r}static fromJSON(e,t){const{refreshToken:r,accessToken:n,expirationTime:i}=t,s=new StsTokenManager;return r&&(_assert("string"==typeof r,"internal-error",{appName:e}),s.refreshToken=r),n&&(_assert("string"==typeof n,"internal-error",{appName:e}),s.accessToken=n),i&&(_assert("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new StsTokenManager,this.toJSON())}_performRefresh(){return debugFail("not implemented")}}function assertStringOrUndefined(e,t){_assert("string"==typeof e||void 0===e,"internal-error",{appName:t})}class UserImpl{constructor({uid:e,auth:t,stsTokenManager:r,...n}){this.providerId="firebase",this.proactiveRefresh=new ProactiveRefresh(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=n.displayName||null,this.email=n.email||null,this.emailVerified=n.emailVerified||!1,this.phoneNumber=n.phoneNumber||null,this.photoURL=n.photoURL||null,this.isAnonymous=n.isAnonymous||!1,this.tenantId=n.tenantId||null,this.providerData=n.providerData?[...n.providerData]:[],this.metadata=new UserMetadata(n.createdAt||void 0,n.lastLoginAt||void 0)}async getIdToken(e){const t=await _logoutIfInvalidated(this,this.stsTokenManager.getToken(this.auth,e));return _assert(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return getIdTokenResult(this,e)}reload(){return reload(this)}_assign(e){this!==e&&(_assert(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map((e=>({...e}))),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new UserImpl({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){_assert(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await _reloadWithoutSaving(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(e(this.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));const t=await this.getIdToken();return await _logoutIfInvalidated(this,async function deleteAccount(e,t){return _performApiRequest(e,"POST","/v1/accounts:delete",t)}(this.auth,{idToken:t})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map((e=>({...e}))),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){const r=t.displayName??void 0,n=t.email??void 0,i=t.phoneNumber??void 0,s=t.photoURL??void 0,o=t.tenantId??void 0,a=t._redirectEventId??void 0,c=t.createdAt??void 0,d=t.lastLoginAt??void 0,{uid:u,emailVerified:l,isAnonymous:h,providerData:p,stsTokenManager:f}=t;_assert(u&&f,e,"internal-error");const m=StsTokenManager.fromJSON(this.name,f);_assert("string"==typeof u,e,"internal-error"),assertStringOrUndefined(r,e.name),assertStringOrUndefined(n,e.name),_assert("boolean"==typeof l,e,"internal-error"),_assert("boolean"==typeof h,e,"internal-error"),assertStringOrUndefined(i,e.name),assertStringOrUndefined(s,e.name),assertStringOrUndefined(o,e.name),assertStringOrUndefined(a,e.name),assertStringOrUndefined(c,e.name),assertStringOrUndefined(d,e.name);const g=new UserImpl({uid:u,auth:e,email:n,emailVerified:l,displayName:r,isAnonymous:h,photoURL:s,phoneNumber:i,tenantId:o,stsTokenManager:m,createdAt:c,lastLoginAt:d});return p&&Array.isArray(p)&&(g.providerData=p.map((e=>({...e})))),a&&(g._redirectEventId=a),g}static async _fromIdTokenResponse(e,t,r=!1){const n=new StsTokenManager;n.updateFromServerResponse(t);const i=new UserImpl({uid:t.localId,auth:e,stsTokenManager:n,isAnonymous:r});return await _reloadWithoutSaving(i),i}static async _fromGetAccountInfoResponse(e,t,r){const n=t.users[0];_assert(void 0!==n.localId,"internal-error");const i=void 0!==n.providerUserInfo?extractProviderData(n.providerUserInfo):[],s=!(n.email&&n.passwordHash||i?.length),o=new StsTokenManager;o.updateFromIdToken(r);const a=new UserImpl({uid:n.localId,auth:e,stsTokenManager:o,isAnonymous:s}),c={uid:n.localId,displayName:n.displayName||null,photoURL:n.photoUrl||null,email:n.email||null,emailVerified:n.emailVerified||!1,phoneNumber:n.phoneNumber||null,tenantId:n.tenantId||null,providerData:i,metadata:new UserMetadata(n.createdAt,n.lastLoginAt),isAnonymous:!(n.email&&n.passwordHash||i?.length)};return Object.assign(a,c),a}}const v=new Map;function _getInstance(e){debugAssert(e instanceof Function,"Expected a class definition");let t=v.get(e);return t?(debugAssert(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,v.set(e,t),t)}class InMemoryPersistence{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}InMemoryPersistence.type="NONE";const T=InMemoryPersistence;function _persistenceKeyName(e,t,r){return`firebase:${e}:${t}:${r}`}class PersistenceUserManager{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;const{config:n,name:i}=this.auth;this.fullUserKey=_persistenceKeyName(this.userKey,n.apiKey,i),this.fullPersistenceKey=_persistenceKeyName("persistence",n.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);if(!e)return null;if("string"==typeof e){const t=await getAccountInfo(this.auth,{idToken:e}).catch((()=>{}));return t?UserImpl._fromGetAccountInfoResponse(this.auth,t,e):null}return UserImpl._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,r="authUser"){if(!t.length)return new PersistenceUserManager(_getInstance(T),e,r);const n=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let i=n[0]||_getInstance(T);const s=_persistenceKeyName(r,e.config.apiKey,e.name);let o=null;for(const r of t)try{const t=await r._get(s);if(t){let n;if("string"==typeof t){const r=await getAccountInfo(e,{idToken:t}).catch((()=>{}));if(!r)break;n=await UserImpl._fromGetAccountInfoResponse(e,r,t)}else n=UserImpl._fromJSON(e,t);r!==i&&(o=n),i=r;break}}catch{}const a=n.filter((e=>e._shouldAllowMigration));return i._shouldAllowMigration&&a.length?(i=a[0],o&&await i._set(s,o.toJSON()),await Promise.all(t.map((async e=>{if(e!==i)try{await e._remove(s)}catch{}}))),new PersistenceUserManager(i,e,r)):new PersistenceUserManager(i,e,r)}}function _getBrowserName(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(function _isIEMobile(e=getUA()){return/iemobile/i.test(e)}(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(function _isFirefox(e=getUA()){return/firefox\//i.test(e)}(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(function _isBlackBerry(e=getUA()){return/blackberry/i.test(e)}(t))return"Blackberry";if(function _isWebOS(e=getUA()){return/webos/i.test(e)}(t))return"Webos";if(function _isSafari(e=getUA()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}(t))return"Safari";if((t.includes("chrome/")||function _isChromeIOS(e=getUA()){return/crios\//i.test(e)}(t))&&!t.includes("edge/"))return"Chrome";if(function _isAndroid(e=getUA()){return/android/i.test(e)}(t))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=e.match(t);if(2===r?.length)return r[1]}return"Other"}function _getClientVersion(e,t=[]){let r;switch(e){case"Browser":r=_getBrowserName(getUA());break;case"Worker":r=`${_getBrowserName(getUA())}-${e}`;break;default:r=e}const i=t.length?t.join(","):"FirebaseCore-web";return`${r}/JsCore/${n}/${i}`}class AuthMiddlewareQueue{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const wrappedCallback=t=>new Promise(((r,n)=>{try{r(e(t))}catch(e){n(e)}}));wrappedCallback.onAbort=t,this.queue.push(wrappedCallback);const r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(e){t.reverse();for(const e of t)try{e()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:e?.message})}}}class PasswordPolicyImpl{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??6,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),void 0!==t.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),void 0!==t.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),void 0!==t.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),void 0!==t.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){const t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){const r=this.customStrengthOptions.minPasswordLength,n=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),n&&(t.meetsMaxPasswordLength=e.length<=n)}validatePasswordCharacterOptions(e,t){let r;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let n=0;n<e.length;n++)r=e.charAt(n),this.updatePasswordCharacterOptionsStatuses(t,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,n,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=n)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class AuthImpl{constructor(e,t,r,n){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Subscription(this),this.idTokenSubscription=new Subscription(this),this.beforeStateQueue=new AuthMiddlewareQueue(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=p,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion,this._persistenceManagerAvailable=new Promise((e=>this._resolvePersistenceManagerAvailable=e))}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=_getInstance(t)),this._initializationPromise=this.queue((async()=>{if(!this._deleted&&(this.persistenceManager=await PersistenceUserManager.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0):void 0}async initializeCurrentUserFromIdToken(e){try{const t=await getAccountInfo(this,{idToken:e}),r=await UserImpl._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(t){if(e(this.app)){const e=this.app.settings.authIdToken;return e?new Promise((t=>{setTimeout((()=>this.initializeCurrentUserFromIdToken(e).then(t,t)))})):this.directlySetCurrentUser(null)}const r=await this.assertedPersistence.getCurrentUser();let n=r,i=!1;if(t&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const e=this.redirectUser?._redirectEventId,r=n?._redirectEventId,s=await this.tryRedirectSignIn(t);e&&e!==r||!s?.user||(n=s.user,i=!0)}if(!n)return this.directlySetCurrentUser(null);if(!n._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(n)}catch(e){n=r,this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(e)))}return n?this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}return _assert(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId?this.directlySetCurrentUser(n):this.reloadAndSetCurrentUserOrClear(n)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await _reloadWithoutSaving(e)}catch(e){if("auth/network-request-failed"!==e?.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function _getUserLanguage(){if("undefined"==typeof navigator)return null;const e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(t){if(e(this.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));const r=t?getModularInstance(t):null;return r&&_assert(r.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(r&&r._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&_assert(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue((async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()}))}async signOut(){return e(this.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(t){return e(this.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)):this.queue((async()=>{await this.assertedPersistence.setPersistence(_getInstance(t))}))}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await async function _getPasswordPolicy(e,t={}){return _performApiRequest(e,"GET","/v2/passwordPolicy",_addTidIfNecessary(e,t))}(this),t=new PasswordPolicyImpl(e);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new ErrorFactory("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser)e();else{const r=this.onAuthStateChanged((()=>{r(),e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await async function revokeToken(e,t){return _performApiRequest(e,"POST","/v2/accounts:revokeToken",_addTidIfNecessary(e,t))}(this,t)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){const r=await this.getOrInitRedirectPersistenceManager(t);return null===e?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&_getInstance(e)||this._popupRedirectResolver;_assert(t,this,"argument-error"),this.redirectPersistenceManager=await PersistenceUserManager.create(this,[_getInstance(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue((async()=>{})),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(e)))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,r,n){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t);let s=!1;const o=this._isInitialized?Promise.resolve():this._initializationPromise;if(_assert(o,this,"internal-error"),o.then((()=>{s||i(this.currentUser)})),"function"==typeof t){const i=e.addObserver(t,r,n);return()=>{s=!0,i()}}{const r=e.addObserver(t);return()=>{s=!0,r()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return _assert(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=_getClientVersion(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);const t=await(this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader());t&&(e["X-Firebase-Client"]=t);const r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(e(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const t=await(this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken());return t?.error&&function _logWarn(e,...t){m.logLevel<=a.WARN&&m.warn(`Auth (${n}): ${e}`,...t)}(`Error while retrieving App Check token: ${t.error}`),t?.token}}function _castAuth(e){return getModularInstance(e)}class Subscription{constructor(e){this.auth=e,this.observer=null,this.addObserver=function createSubscribe(e,t){const r=new ObserverProxy(e,t);return r.subscribe.bind(r)}((e=>this.observer=e))}get next(){return _assert(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let A={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};class MockGreCAPTCHATopLevel{constructor(){this.enterprise=new MockGreCAPTCHA}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class MockGreCAPTCHA{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}const E="NO_RECAPTCHA",y="onFirebaseAuthREInstanceReady";class RecaptchaEnterpriseVerifier{constructor(e){this.type="recaptcha-enterprise",this.auth=_castAuth(e)}async verify(e="verify",t=!1){function retrieveRecaptchaToken(t,r,n){const i=window.grecaptcha;isEnterprise(i)?i.enterprise.ready((()=>{i.enterprise.execute(t,{action:e}).then((e=>{r(e)})).catch((()=>{r(E)}))})):n(Error("No reCAPTCHA enterprise script loaded."))}if(this.auth.settings.appVerificationDisabledForTesting){return(new MockGreCAPTCHATopLevel).execute("siteKey",{action:"verify"})}return new Promise(((e,r)=>{(async function retrieveSiteKey(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise((async(t,r)=>{getRecaptchaConfig(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((n=>{if(void 0!==n.recaptchaKey){const r=new RecaptchaConfig(n);return null==e.tenantId?e._agentRecaptchaConfig=r:e._tenantRecaptchaConfigs[e.tenantId]=r,t(r.siteKey)}r(new Error("recaptcha Enterprise site key undefined"))})).catch((e=>{r(e)}))}))})(this.auth).then((async n=>{if(!t&&isEnterprise(window.grecaptcha)&&RecaptchaEnterpriseVerifier.scriptInjectionDeferred)await RecaptchaEnterpriseVerifier.scriptInjectionDeferred.promise,retrieveRecaptchaToken(n,e,r);else{if("undefined"==typeof window)return void r(new Error("RecaptchaVerifier is only supported in browser"));let t=function _recaptchaEnterpriseScriptUrl(){return A.recaptchaEnterpriseScript}();0!==t.length&&(t+=n+`&onload=${y}`),RecaptchaEnterpriseVerifier.scriptInjectionDeferred=new Deferred,window[y]=()=>{RecaptchaEnterpriseVerifier.scriptInjectionDeferred?.resolve()},function _loadJS(e){return A.loadJS(e)}(t).then((()=>RecaptchaEnterpriseVerifier.scriptInjectionDeferred?.promise)).then((()=>{retrieveRecaptchaToken(n,e,r)})).catch((e=>{r(e)}))}})).catch((e=>{r(e)}))}))}}async function injectRecaptchaFields(e,t,r,n=!1,i=!1){const s=new RecaptchaEnterpriseVerifier(e);let o;if(i)o=E;else try{o=await s.verify(r)}catch(e){o=await s.verify(r,!0)}const a={...t};if("mfaSmsEnrollment"===r||"mfaSmsSignIn"===r){if("phoneEnrollmentInfo"in a){const e=a.phoneEnrollmentInfo.phoneNumber,t=a.phoneEnrollmentInfo.recaptchaToken;Object.assign(a,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:t,captchaResponse:o,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in a){const e=a.phoneSignInInfo.recaptchaToken;Object.assign(a,{phoneSignInInfo:{recaptchaToken:e,captchaResponse:o,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return a}return n?Object.assign(a,{captchaResp:o}):Object.assign(a,{captchaResponse:o}),Object.assign(a,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(a,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),a}async function handleRecaptchaFlow(e,t,r,n,i){if("EMAIL_PASSWORD_PROVIDER"===i){if(e._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await injectRecaptchaFields(e,t,r,"getOobCode"===r);return n(e,i)}return n(e,t).catch((async i=>{if("auth/missing-recaptcha-token"===i.code){console.log(`${r} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const i=await injectRecaptchaFields(e,t,r,"getOobCode"===r);return n(e,i)}return Promise.reject(i)}))}if("PHONE_PROVIDER"===i){if(e._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){const i=await injectRecaptchaFields(e,t,r);return n(e,i).catch((async i=>{if("AUDIT"===e._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")&&("auth/missing-recaptcha-token"===i.code||"auth/invalid-app-credential"===i.code)){console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${r} flow.`);const i=await injectRecaptchaFields(e,t,r,!1,!0);return n(e,i)}return Promise.reject(i)}))}{const i=await injectRecaptchaFields(e,t,r,!1,!0);return n(e,i)}}return Promise.reject(i+" provider is not supported.")}function initializeAuth(e,t){const r=_getProvider(e,"auth");if(r.isInitialized()){const e=r.getImmediate();if(deepEqual(r.getOptions(),t??{}))return e;_fail(e,"already-initialized")}return r.initialize({options:t})}function connectAuthEmulator(e,t,r){const n=_castAuth(e);_assert(/^https?:\/\//.test(t),n,"invalid-emulator-scheme");const i=!!r?.disableWarnings,s=extractProtocol(t),{host:o,port:a}=function extractHostAndPort(e){const t=extractProtocol(e),r=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!r)return{host:"",port:null};const n=r[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(n);if(i){const e=i[1];return{host:e,port:parsePort(n.substr(e.length+1))}}{const[e,t]=n.split(":");return{host:e,port:parsePort(t)}}}(t),c=null===a?"":`:${a}`,d={url:`${s}//${o}${c}/`},u=Object.freeze({host:o,port:a,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})});if(!n._canInitEmulator)return _assert(n.config.emulator&&n.emulatorConfig,n,"emulator-config-failed"),void _assert(deepEqual(d,n.config.emulator)&&deepEqual(u,n.emulatorConfig),n,"emulator-config-failed");n.config.emulator=d,n.emulatorConfig=u,n.settings.appVerificationDisabledForTesting=!0,isCloudWorkstation(o)?async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(`${s}//${o}${c}`):i||function emitEmulatorWarning(){function attachBanner(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials.");"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",attachBanner):attachBanner())}()}function extractProtocol(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function parsePort(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}RecaptchaEnterpriseVerifier.scriptInjectionDeferred=null;class AuthCredential{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return debugFail("not implemented")}_getIdTokenResponse(e){return debugFail("not implemented")}_linkToIdToken(e,t){return debugFail("not implemented")}_getReauthenticationResolver(e){return debugFail("not implemented")}}async function resetPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:resetPassword",_addTidIfNecessary(e,t))}async function linkEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:signUp",t)}async function signInWithPassword(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPassword",_addTidIfNecessary(e,t))}async function sendOobCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendOobCode",_addTidIfNecessary(e,t))}async function sendPasswordResetEmail$1(e,t){return sendOobCode(e,t)}async function sendSignInLinkToEmail$1(e,t){return sendOobCode(e,t)}class EmailAuthCredential extends AuthCredential{constructor(e,t,r,n=null){super("password",r),this._email=e,this._password=t,this._tenantId=n}static _fromEmailAndPassword(e,t){return new EmailAuthCredential(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new EmailAuthCredential(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e;if(t?.email&&t?.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return handleRecaptchaFlow(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",signInWithPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return async function signInWithEmailLink$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}(e,{email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return handleRecaptchaFlow(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",linkEmailPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return async function signInWithEmailLinkForLinking(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function signInWithIdp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithIdp",_addTidIfNecessary(e,t))}class OAuthCredential extends AuthCredential{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new OAuthCredential(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):_fail("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:r,signInMethod:n,...i}=t;if(!r||!n)return null;const s=new OAuthCredential(r,n);return s.idToken=i.idToken||void 0,s.accessToken=i.accessToken||void 0,s.secret=i.secret,s.nonce=i.nonce,s.pendingToken=i.pendingToken||null,s}_getIdTokenResponse(e){return signInWithIdp(e,this.buildRequest())}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,signInWithIdp(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,signInWithIdp(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=querystring(t)}return e}}const S={USER_NOT_FOUND:"user-not-found"};class PhoneAuthCredential extends AuthCredential{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new PhoneAuthCredential({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new PhoneAuthCredential({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function signInWithPhoneNumber(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function linkWithPhoneNumber(e,t){const r=await _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t));if(r.temporaryProof)throw _makeTaggedError(e,"account-exists-with-different-credential",r);return r}(e,{idToken:t,...this._makeVerificationRequest()})}_getReauthenticationResolver(e){return async function verifyPhoneNumberForExisting(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,{...t,operation:"REAUTH"}),S)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:r,verificationCode:n}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:r,code:n}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}=e;return r||t||n||i?new PhoneAuthCredential({verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}):null}}class ActionCodeURL{constructor(e){const t=querystringDecode(extractQuerystring(e)),r=t.apiKey??null,n=t.oobCode??null,i=function parseMode(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(t.mode??null);_assert(r&&n&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=n,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){const t=function parseDeepLink(e){const t=querystringDecode(extractQuerystring(e)).link,r=t?querystringDecode(extractQuerystring(t)).deep_link_id:null,n=querystringDecode(extractQuerystring(e)).deep_link_id;return(n?querystringDecode(extractQuerystring(n)).link:null)||n||r||t||e}(e);try{return new ActionCodeURL(t)}catch{return null}}}function parseActionCodeURL(e){return ActionCodeURL.parseLink(e)}class EmailAuthProvider{constructor(){this.providerId=EmailAuthProvider.PROVIDER_ID}static credential(e,t){return EmailAuthCredential._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const r=ActionCodeURL.parseLink(t);return _assert(r,"argument-error"),EmailAuthCredential._fromEmailAndCode(e,r.code,r.tenantId)}}EmailAuthProvider.PROVIDER_ID="password",EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD="password",EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class FederatedAuthProvider{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class BaseOAuthProvider extends FederatedAuthProvider{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class OAuthProvider extends BaseOAuthProvider{static credentialFromJSON(e){const t="string"==typeof e?JSON.parse(e):e;return _assert("providerId"in t&&"signInMethod"in t,"argument-error"),OAuthCredential._fromParams(t)}credential(e){return this._credential({...e,nonce:e.rawNonce})}_credential(e){return _assert(e.idToken||e.accessToken,"argument-error"),OAuthCredential._fromParams({...e,providerId:this.providerId,signInMethod:this.providerId})}static credentialFromResult(e){return OAuthProvider.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return OAuthProvider.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r,oauthTokenSecret:n,pendingToken:i,nonce:s,providerId:o}=e;if(!(r||n||t||i))return null;if(!o)return null;try{return new OAuthProvider(o)._credential({idToken:t,accessToken:r,nonce:s,pendingToken:i})}catch(e){return null}}}class FacebookAuthProvider extends BaseOAuthProvider{constructor(){super("facebook.com")}static credential(e){return OAuthCredential._fromParams({providerId:FacebookAuthProvider.PROVIDER_ID,signInMethod:FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return FacebookAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return FacebookAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return FacebookAuthProvider.credential(e.oauthAccessToken)}catch{return null}}}FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD="facebook.com",FacebookAuthProvider.PROVIDER_ID="facebook.com";class GoogleAuthProvider extends BaseOAuthProvider{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return OAuthCredential._fromParams({providerId:GoogleAuthProvider.PROVIDER_ID,signInMethod:GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return GoogleAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GoogleAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return GoogleAuthProvider.credential(t,r)}catch{return null}}}GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD="google.com",GoogleAuthProvider.PROVIDER_ID="google.com";class GithubAuthProvider extends BaseOAuthProvider{constructor(){super("github.com")}static credential(e){return OAuthCredential._fromParams({providerId:GithubAuthProvider.PROVIDER_ID,signInMethod:GithubAuthProvider.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return GithubAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GithubAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return GithubAuthProvider.credential(e.oauthAccessToken)}catch{return null}}}GithubAuthProvider.GITHUB_SIGN_IN_METHOD="github.com",GithubAuthProvider.PROVIDER_ID="github.com";class SAMLAuthCredential extends AuthCredential{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return signInWithIdp(e,this.buildRequest())}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,signInWithIdp(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,signInWithIdp(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:r,signInMethod:n,pendingToken:i}=t;return r&&n&&i&&r===n?new SAMLAuthCredential(r,i):null}static _create(e,t){return new SAMLAuthCredential(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class SAMLAuthProvider extends FederatedAuthProvider{constructor(e){_assert(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){const t=SAMLAuthCredential.fromJSON(e);return _assert(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{pendingToken:t,providerId:r}=e;if(!t||!r)return null;try{return SAMLAuthCredential._create(r,t)}catch(e){return null}}}class TwitterAuthProvider extends BaseOAuthProvider{constructor(){super("twitter.com")}static credential(e,t){return OAuthCredential._fromParams({providerId:TwitterAuthProvider.PROVIDER_ID,signInMethod:TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return TwitterAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return TwitterAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return TwitterAuthProvider.credential(t,r)}catch{return null}}}async function signUp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signUp",_addTidIfNecessary(e,t))}TwitterAuthProvider.TWITTER_SIGN_IN_METHOD="twitter.com",TwitterAuthProvider.PROVIDER_ID="twitter.com";class UserCredentialImpl{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,n=!1){const i=await UserImpl._fromIdTokenResponse(e,r,n),s=providerIdForResponse(r);return new UserCredentialImpl({user:i,providerId:s,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);const n=providerIdForResponse(r);return new UserCredentialImpl({user:e,providerId:n,_tokenResponse:r,operationType:t})}}function providerIdForResponse(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}async function signInAnonymously(t){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const r=_castAuth(t);if(await r._initializationPromise,r.currentUser?.isAnonymous)return new UserCredentialImpl({user:r.currentUser,providerId:null,operationType:"signIn"});const n=await signUp(r,{returnSecureToken:!0}),i=await UserCredentialImpl._fromIdTokenResponse(r,"signIn",n,!0);return await r._updateCurrentUser(i.user),i}class MultiFactorError extends FirebaseError{constructor(e,t,r,n){super(t.code,t.message),this.operationType=r,this.user=n,Object.setPrototypeOf(this,MultiFactorError.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,n){return new MultiFactorError(e,t,r,n)}}function _processCredentialSavingMfaContextIfNecessary(e,t,r,n){return("reauthenticate"===t?r._getReauthenticationResolver(e):r._getIdTokenResponse(e)).catch((r=>{if("auth/multi-factor-auth-required"===r.code)throw MultiFactorError._fromErrorAndOperation(e,r,t,n);throw r}))}function providerDataAsNames(e){return new Set(e.map((({providerId:e})=>e)).filter((e=>!!e)))}async function unlink(e,t){const r=getModularInstance(e);await _assertLinkedStatus(!0,r,t);const{providerUserInfo:n}=await async function deleteLinkedAccounts(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}(r.auth,{idToken:await r.getIdToken(),deleteProvider:[t]}),i=providerDataAsNames(n||[]);return r.providerData=r.providerData.filter((e=>i.has(e.providerId))),i.has("phone")||(r.phoneNumber=null),await r.auth._persistUserIfCurrent(r),r}async function _assertLinkedStatus(e,t,r){await _reloadWithoutSaving(t);const n=!1===e?"provider-already-linked":"no-such-provider";_assert(providerDataAsNames(t.providerData).has(r)===e,t.auth,n)}async function signInWithCredential(t,r){return async function _signInWithCredential(t,r,n=!1){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i="signIn",s=await _processCredentialSavingMfaContextIfNecessary(t,i,r),o=await UserCredentialImpl._fromIdTokenResponse(t,i,s);return n||await t._updateCurrentUser(o.user),o}(_castAuth(t),r)}async function linkWithCredential(e,t){const r=getModularInstance(e);return await _assertLinkedStatus(!1,r,t.providerId),async function _link(e,t,r=!1){const n=await _logoutIfInvalidated(e,t._linkToIdToken(e.auth,await e.getIdToken()),r);return UserCredentialImpl._forOperation(e,"link",n)}(r,t)}async function reauthenticateWithCredential(t,r){return async function _reauthenticate(t,r,n=!1){const{auth:i}=t;if(e(i.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i));const s="reauthenticate";try{const e=await _logoutIfInvalidated(t,_processCredentialSavingMfaContextIfNecessary(i,s,r,t),n);_assert(e.idToken,i,"internal-error");const o=_parseToken(e.idToken);_assert(o,i,"internal-error");const{sub:a}=o;return _assert(t.uid===a,i,"user-mismatch"),UserCredentialImpl._forOperation(t,s,e)}catch(e){throw"auth/user-not-found"===e?.code&&_fail(i,"user-mismatch"),e}}(getModularInstance(t),r)}async function signInWithCustomToken(t,r){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const n=_castAuth(t),i=await async function signInWithCustomToken$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithCustomToken",_addTidIfNecessary(e,t))}(n,{token:r,returnSecureToken:!0}),s=await UserCredentialImpl._fromIdTokenResponse(n,"signIn",i);return await n._updateCurrentUser(s.user),s}class MultiFactorInfoImpl{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?PhoneMultiFactorInfoImpl._fromServerResponse(e,t):"totpInfo"in t?TotpMultiFactorInfoImpl._fromServerResponse(e,t):_fail(e,"internal-error")}}class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new PhoneMultiFactorInfoImpl(t)}}class TotpMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new TotpMultiFactorInfoImpl(t)}}function _setActionCodeSettingsOnRequest(e,t,r){_assert(r.url?.length>0,e,"invalid-continue-uri"),_assert(void 0===r.dynamicLinkDomain||r.dynamicLinkDomain.length>0,e,"invalid-dynamic-link-domain"),_assert(void 0===r.linkDomain||r.linkDomain.length>0,e,"invalid-hosting-link-domain"),t.continueUrl=r.url,t.dynamicLinkDomain=r.dynamicLinkDomain,t.linkDomain=r.linkDomain,t.canHandleCodeInApp=r.handleCodeInApp,r.iOS&&(_assert(r.iOS.bundleId.length>0,e,"missing-ios-bundle-id"),t.iOSBundleId=r.iOS.bundleId),r.android&&(_assert(r.android.packageName.length>0,e,"missing-android-pkg-name"),t.androidInstallApp=r.android.installApp,t.androidMinimumVersionCode=r.android.minimumVersion,t.androidPackageName=r.android.packageName)}async function recachePasswordPolicy(e){const t=_castAuth(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function sendPasswordResetEmail(e,t,r){const n=_castAuth(e),i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};r&&_setActionCodeSettingsOnRequest(n,i,r),await handleRecaptchaFlow(n,i,"getOobCode",sendPasswordResetEmail$1,"EMAIL_PASSWORD_PROVIDER")}async function confirmPasswordReset(e,t,r){await resetPassword(getModularInstance(e),{oobCode:t,newPassword:r}).catch((async t=>{throw"auth/password-does-not-meet-requirements"===t.code&&recachePasswordPolicy(e),t}))}async function applyActionCode(e,t){await async function applyActionCode$1(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",_addTidIfNecessary(e,t))}(getModularInstance(e),{oobCode:t})}async function checkActionCode(e,t){const r=getModularInstance(e),n=await resetPassword(r,{oobCode:t}),i=n.requestType;switch(_assert(i,r,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":_assert(n.newEmail,r,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":_assert(n.mfaInfo,r,"internal-error");default:_assert(n.email,r,"internal-error")}let s=null;return n.mfaInfo&&(s=MultiFactorInfoImpl._fromServerResponse(_castAuth(r),n.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===n.requestType?n.newEmail:n.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===n.requestType?n.email:n.newEmail)||null,multiFactorInfo:s},operation:i}}async function verifyPasswordResetCode(e,t){const{data:r}=await checkActionCode(getModularInstance(e),t);return r.email}async function createUserWithEmailAndPassword(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t),s=handleRecaptchaFlow(i,{returnSecureToken:!0,email:r,password:n,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",signUp,"EMAIL_PASSWORD_PROVIDER"),o=await s.catch((e=>{throw"auth/password-does-not-meet-requirements"===e.code&&recachePasswordPolicy(t),e})),a=await UserCredentialImpl._fromIdTokenResponse(i,"signIn",o);return await i._updateCurrentUser(a.user),a}function signInWithEmailAndPassword(t,r,n){return e(t.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t)):signInWithCredential(getModularInstance(t),EmailAuthProvider.credential(r,n)).catch((async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&recachePasswordPolicy(t),e}))}async function sendSignInLinkToEmail(e,t,r){const n=_castAuth(e),i={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};!function setActionCodeSettings(e,t){_assert(t.handleCodeInApp,n,"argument-error"),t&&_setActionCodeSettingsOnRequest(n,e,t)}(i,r),await handleRecaptchaFlow(n,i,"getOobCode",sendSignInLinkToEmail$1,"EMAIL_PASSWORD_PROVIDER")}function isSignInWithEmailLink(e,t){const r=ActionCodeURL.parseLink(t);return"EMAIL_SIGNIN"===r?.operation}async function signInWithEmailLink(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=getModularInstance(t),s=EmailAuthProvider.credentialWithLink(r,n||_getCurrentUrl());return _assert(s._tenantId===(i.tenantId||null),i,"tenant-id-mismatch"),signInWithCredential(i,s)}async function fetchSignInMethodsForEmail(e,t){const r={identifier:t,continueUri:_isHttpOrHttps()?_getCurrentUrl():"http://localhost"},{signinMethods:n}=await async function createAuthUri(e,t){return _performApiRequest(e,"POST","/v1/accounts:createAuthUri",_addTidIfNecessary(e,t))}(getModularInstance(e),r);return n||[]}async function sendEmailVerification(e,t){const r=getModularInstance(e),n={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&_setActionCodeSettingsOnRequest(r.auth,n,t);const{email:i}=await async function sendEmailVerification$1(e,t){return sendOobCode(e,t)}(r.auth,n);i!==e.email&&await e.reload()}async function verifyBeforeUpdateEmail(e,t,r){const n=getModularInstance(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};r&&_setActionCodeSettingsOnRequest(n.auth,i,r);const{email:s}=await async function verifyAndChangeEmail(e,t){return sendOobCode(e,t)}(n.auth,i);s!==e.email&&await e.reload()}async function updateProfile(e,{displayName:t,photoURL:r}){if(void 0===t&&void 0===r)return;const n=getModularInstance(e),i={idToken:await n.getIdToken(),displayName:t,photoUrl:r,returnSecureToken:!0},s=await _logoutIfInvalidated(n,async function updateProfile$1(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}(n.auth,i));n.displayName=s.displayName||null,n.photoURL=s.photoUrl||null;const o=n.providerData.find((({providerId:e})=>"password"===e));o&&(o.displayName=n.displayName,o.photoURL=n.photoURL),await n._updateTokensIfNecessary(s)}function updateEmail(t,r){const n=getModularInstance(t);return e(n.auth.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth)):updateEmailOrPassword(n,r,null)}function updatePassword(e,t){return updateEmailOrPassword(getModularInstance(e),null,t)}async function updateEmailOrPassword(e,t,r){const{auth:n}=e,i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),r&&(i.password=r);const s=await _logoutIfInvalidated(e,async function updateEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}(n,i));await e._updateTokensIfNecessary(s,!0)}class GenericAdditionalUserInfo{constructor(e,t,r={}){this.isNewUser=e,this.providerId=t,this.profile=r}}class FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo{constructor(e,t,r,n){super(e,t,r),this.username=n}}class FacebookAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,"facebook.com",t)}}class GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t){super(e,"github.com",t,"string"==typeof t?.login?t?.login:null)}}class GoogleAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,"google.com",t)}}class TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t,r){super(e,"twitter.com",t,r)}}function getAdditionalUserInfo(e){const{user:t,_tokenResponse:r}=e;return t.isAnonymous&&!r?{providerId:null,isNewUser:!1,profile:null}:function _fromIdTokenResponse(e){if(!e)return null;const{providerId:t}=e,r=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},n=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!t&&e?.idToken){const t=_parseToken(e.idToken)?.firebase?.sign_in_provider;if(t)return new GenericAdditionalUserInfo(n,"anonymous"!==t&&"custom"!==t?t:null)}if(!t)return null;switch(t){case"facebook.com":return new FacebookAdditionalUserInfo(n,r);case"github.com":return new GithubAdditionalUserInfo(n,r);case"google.com":return new GoogleAdditionalUserInfo(n,r);case"twitter.com":return new TwitterAdditionalUserInfo(n,r,e.screenName||null);case"custom":case"anonymous":return new GenericAdditionalUserInfo(n,null);default:return new GenericAdditionalUserInfo(n,t,r)}}(r)}function setPersistence(e,t){return getModularInstance(e).setPersistence(t)}function initializeRecaptchaConfig(e){return async function _initializeRecaptchaConfig(e){const t=_castAuth(e),r=await getRecaptchaConfig(t,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}),n=new RecaptchaConfig(r);null==t.tenantId?t._agentRecaptchaConfig=n:t._tenantRecaptchaConfigs[t.tenantId]=n,n.isAnyProviderEnabled()&&new RecaptchaEnterpriseVerifier(t).verify()}(e)}async function validatePassword(e,t){return _castAuth(e).validatePassword(t)}function onIdTokenChanged(e,t,r,n){return getModularInstance(e).onIdTokenChanged(t,r,n)}function beforeAuthStateChanged(e,t,r){return getModularInstance(e).beforeAuthStateChanged(t,r)}function onAuthStateChanged(e,t,r,n){return getModularInstance(e).onAuthStateChanged(t,r,n)}function useDeviceLanguage(e){getModularInstance(e).useDeviceLanguage()}function updateCurrentUser(e,t){return getModularInstance(e).updateCurrentUser(t)}function signOut(e){return getModularInstance(e).signOut()}function revokeAccessToken(e,t){return _castAuth(e).revokeAccessToken(t)}async function deleteUser(e){return getModularInstance(e).delete()}class MultiFactorSessionImpl{constructor(e,t,r){this.type=e,this.credential=t,this.user=r}static _fromIdtoken(e,t){return new MultiFactorSessionImpl("enroll",e,t)}static _fromMfaPendingCredential(e){return new MultiFactorSessionImpl("signin",e)}toJSON(){const e="enroll"===this.type?"idToken":"pendingCredential";return{multiFactorSession:{[e]:this.credential}}}static fromJSON(e){if(e?.multiFactorSession){if(e.multiFactorSession?.pendingCredential)return MultiFactorSessionImpl._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(e.multiFactorSession?.idToken)return MultiFactorSessionImpl._fromIdtoken(e.multiFactorSession.idToken)}return null}}class MultiFactorResolverImpl{constructor(e,t,r){this.session=e,this.hints=t,this.signInResolver=r}static _fromError(e,t){const r=_castAuth(e),n=t.customData._serverResponse,i=(n.mfaInfo||[]).map((e=>MultiFactorInfoImpl._fromServerResponse(r,e)));_assert(n.mfaPendingCredential,r,"internal-error");const s=MultiFactorSessionImpl._fromMfaPendingCredential(n.mfaPendingCredential);return new MultiFactorResolverImpl(s,i,(async e=>{const i=await e._process(r,s);delete n.mfaInfo,delete n.mfaPendingCredential;const o={...n,idToken:i.idToken,refreshToken:i.refreshToken};switch(t.operationType){case"signIn":const e=await UserCredentialImpl._fromIdTokenResponse(r,t.operationType,o);return await r._updateCurrentUser(e.user),e;case"reauthenticate":return _assert(t.user,r,"internal-error"),UserCredentialImpl._forOperation(t.user,t.operationType,o);default:_fail(r,"internal-error")}}))}async resolveSignIn(e){const t=e;return this.signInResolver(t)}}function getMultiFactorResolver(e,t){const r=getModularInstance(e),n=t;return _assert(t.customData.operationType,r,"argument-error"),_assert(n.customData._serverResponse?.mfaPendingCredential,r,"argument-error"),MultiFactorResolverImpl._fromError(r,n)}class MultiFactorUserImpl{constructor(e){this.user=e,this.enrolledFactors=[],e._onReload((t=>{t.mfaInfo&&(this.enrolledFactors=t.mfaInfo.map((t=>MultiFactorInfoImpl._fromServerResponse(e.auth,t))))}))}static _fromUser(e){return new MultiFactorUserImpl(e)}async getSession(){return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){const r=e,n=await this.getSession(),i=await _logoutIfInvalidated(this.user,r._process(this.user.auth,n,t));return await this.user._updateTokensIfNecessary(i),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid,r=await this.user.getIdToken();try{const e=await _logoutIfInvalidated(this.user,function withdrawMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:withdraw",_addTidIfNecessary(e,t))}(this.user.auth,{idToken:r,mfaEnrollmentId:t}));this.enrolledFactors=this.enrolledFactors.filter((({uid:e})=>e!==t)),await this.user._updateTokensIfNecessary(e),await this.user.reload()}catch(e){throw e}}}const w=new WeakMap;function multiFactor(e){const t=getModularInstance(e);return w.has(t)||w.set(t,MultiFactorUserImpl._fromUser(t)),w.get(t)}const k="__sak";class Receiver{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t)return t;const r=new Receiver(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:r,eventType:n,data:i}=t.data,s=this.handlersMap[n];if(!s?.size)return;t.ports[0].postMessage({status:"ack",eventId:r,eventType:n});const o=Array.from(s).map((async e=>e(t.origin,i))),a=await function _allSettled(e){return Promise.all(e.map((async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})))}(o);t.ports[0].postMessage({status:"done",eventId:r,eventType:n,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}Receiver.receivers=[];class Sender{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,r=50){const n="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!n)throw new Error("connection_unavailable");let i,s;return new Promise(((o,a)=>{const c=function _generateEventId(e="",t=10){let r="";for(let e=0;e<t;e++)r+=Math.floor(10*Math.random());return e+r}("",20);n.port1.start();const d=setTimeout((()=>{a(new Error("unsupported_event"))}),r);s={messageChannel:n,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(d),i=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(i),o(t.data.response);break;default:clearTimeout(d),clearTimeout(i),a(new Error("invalid_response"))}}},this.handlers.add(s),n.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[n.port2])})).finally((()=>{s&&this.removeMessageHandler(s)}))}}function _window(){return window}function _isWorker(){return void 0!==_window().WorkerGlobalScope&&"function"==typeof _window().importScripts}const P="firebaseLocalStorageDb",C="firebaseLocalStorage",R="fbase_key";class DBPromise{constructor(e){this.request=e}toPromise(){return new Promise(((e,t)=>{this.request.addEventListener("success",(()=>{e(this.request.result)})),this.request.addEventListener("error",(()=>{t(this.request.error)}))}))}}function getObjectStore(e,t){return e.transaction([C],t?"readwrite":"readonly").objectStore(C)}function _openDatabase(){const e=indexedDB.open(P,1);return new Promise(((t,r)=>{e.addEventListener("error",(()=>{r(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(C,{keyPath:R})}catch(e){r(e)}})),e.addEventListener("success",(async()=>{const r=e.result;r.objectStoreNames.contains(C)?t(r):(r.close(),await function _deleteDatabase(){const e=indexedDB.deleteDatabase(P);return new DBPromise(e).toPromise()}(),t(await _openDatabase()))}))}))}async function _putObject(e,t,r){const n=getObjectStore(e,!0).put({[R]:t,value:r});return new DBPromise(n).toPromise()}function _deleteObject(e,t){const r=getObjectStore(e,!0).delete(t);return new DBPromise(r).toPromise()}class IndexedDBLocalPersistence{constructor(){this.type="LOCAL",this.dbPromise=null,this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then((()=>{}),(()=>{}))}async _openDb(){return this.dbPromise||(this.dbPromise=_openDatabase(),this.dbPromise.catch((()=>{this.dbPromise=null}))),this.dbPromise}async _withRetries(e){let t=0;for(;;)try{const t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;if(this.dbPromise){(await this.dbPromise).close(),this.dbPromise=null}}}async initializeServiceWorkerMessaging(){return _isWorker()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Receiver._getInstance(function _getWorkerGlobalScope(){return _isWorker()?self:null}()),this.receiver._subscribe("keyChanged",(async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)}))),this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){if(this.activeServiceWorker=await async function _getActiveServiceWorker(){if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}(),!this.activeServiceWorker)return;this.sender=new Sender(this.activeServiceWorker);const e=await this.sender._send("ping",{},800);e&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&function _getServiceWorkerController(){return navigator?.serviceWorker?.controller||null}()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{return!!indexedDB&&(await this._withRetries((async e=>{await _putObject(e,k,"1"),await _deleteObject(e,k)})),!0)}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>(await this._withRetries((r=>_putObject(r,e,t))),this.localCache[e]=t,this.notifyServiceWorker(e))))}async _get(e){const t=await this._withRetries((t=>async function getObject(e,t){const r=getObjectStore(e,!1).get(t),n=await new DBPromise(r).toPromise();return void 0===n?null:n.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>_deleteObject(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=getObjectStore(e,!1).getAll();return new DBPromise(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],r=new Set;if(0!==e.length)for(const{fbase_key:n,value:i}of e)r.add(n),JSON.stringify(this.localCache[n])!==JSON.stringify(i)&&(this.notifyListeners(n,i),t.push(n));for(const e of Object.keys(this.localCache))this.localCache[e]&&!r.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const e of Array.from(r))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}IndexedDBLocalPersistence.type="LOCAL";const N=IndexedDBLocalPersistence;class MultiFactorAssertionImpl{constructor(e){this.factorId=e}_process(e,t,r){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,r);case"signin":return this._finalizeSignIn(e,t.credential);default:return debugFail("unexpected MultiFactorSessionType")}}}class TotpMultiFactorGenerator{static assertionForEnrollment(e,t){return TotpMultiFactorAssertionImpl._fromSecret(e,t)}static assertionForSignIn(e,t){return TotpMultiFactorAssertionImpl._fromEnrollmentId(e,t)}static async generateSecret(e){const t=e;_assert(void 0!==t.user?.auth,"internal-error");const r=await function startEnrollTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:start",_addTidIfNecessary(e,t))}(t.user.auth,{idToken:t.credential,totpEnrollmentInfo:{}});return TotpSecret._fromStartTotpMfaEnrollmentResponse(r,t.user.auth)}}TotpMultiFactorGenerator.FACTOR_ID="totp";class TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e,t,r){super("totp"),this.otp=e,this.enrollmentId=t,this.secret=r}static _fromSecret(e,t){return new TotpMultiFactorAssertionImpl(t,void 0,e)}static _fromEnrollmentId(e,t){return new TotpMultiFactorAssertionImpl(t,e)}async _finalizeEnroll(e,t,r){return _assert(void 0!==this.secret,e,"argument-error"),function finalizeEnrollTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,t))}(e,{idToken:t,displayName:r,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,t){_assert(void 0!==this.enrollmentId&&void 0!==this.otp,e,"argument-error");const r={verificationCode:this.otp};return function finalizeSignInTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,t))}(e,{mfaPendingCredential:t,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:r})}}class TotpSecret{constructor(e,t,r,n,i,s,o){this.sessionInfo=s,this.auth=o,this.secretKey=e,this.hashingAlgorithm=t,this.codeLength=r,this.codeIntervalSeconds=n,this.enrollmentCompletionDeadline=i}static _fromStartTotpMfaEnrollmentResponse(e,t){return new TotpSecret(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,t)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,t){let r=!1;return(_isEmptyString(e)||_isEmptyString(t))&&(r=!0),r&&(_isEmptyString(e)&&(e=this.auth.currentUser?.email||"unknownuser"),_isEmptyString(t)&&(t=this.auth.name)),`otpauth://totp/${t}:${e}?secret=${this.secretKey}&issuer=${t}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}}function _isEmptyString(e){return void 0===e||0===e?.length}var b="@firebase/auth",O="1.13.3";class AuthInterop{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){if(this.assertAuthConfigured(),await this.auth._initializationPromise,!this.auth.currentUser)return null;return{accessToken:await this.auth.currentUser.getIdToken(e)}}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged((t=>{e(t?.stsTokenManager.accessToken||null)}));this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){_assert(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function getAuth(e=i()){const t=_getProvider(e,"auth");if(t.isInitialized())return t.getImmediate();const r=initializeAuth(e,{persistence:[N]}),n=(s="auth",getDefaults()?.emulatorHosts?.[s]);var s;return n&&connectAuthEmulator(r,`http://${n}`),r}!function registerAuth(e){t(new Component("auth",((t,{options:r})=>{const n=t.getProvider("app").getImmediate(),i=t.getProvider("heartbeat"),s=t.getProvider("app-check-internal"),{apiKey:o,authDomain:a}=n.options;_assert(o&&!o.includes(":"),"invalid-api-key",{appName:n.name});const c={apiKey:o,authDomain:a,clientPlatform:e,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:_getClientVersion(e)},d=new AuthImpl(n,i,s,c);return function _initializeAuthInstance(e,t){const r=t?.persistence||[],n=(Array.isArray(r)?r:[r]).map(_getInstance);t?.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(n,t?.popupRedirectResolver)}(d,r),d}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,r)=>{e.getProvider("auth-internal").initialize()}))),t(new Component("auth-internal",(e=>(e=>new AuthInterop(e))(_castAuth(e.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),r(b,O,function getVersionForPlatform(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}(e)),r(b,O,"esm2020")}("WebExtension");export{ActionCodeURL,AuthCredential,f as AuthErrorCodes,EmailAuthCredential,EmailAuthProvider,FacebookAuthProvider,GithubAuthProvider,GoogleAuthProvider,OAuthCredential,OAuthProvider,PhoneAuthCredential,SAMLAuthProvider,TotpMultiFactorGenerator,TotpSecret,TwitterAuthProvider,applyActionCode,beforeAuthStateChanged,checkActionCode,confirmPasswordReset,connectAuthEmulator,createUserWithEmailAndPassword,l as debugErrorMap,deleteUser,fetchSignInMethodsForEmail,getAdditionalUserInfo,getAuth,getIdToken,getIdTokenResult,getMultiFactorResolver,T as inMemoryPersistence,N as indexedDBLocalPersistence,initializeAuth,initializeRecaptchaConfig,isSignInWithEmailLink,linkWithCredential,multiFactor,onAuthStateChanged,onIdTokenChanged,parseActionCodeURL,h as prodErrorMap,reauthenticateWithCredential,reload,revokeAccessToken,sendEmailVerification,sendPasswordResetEmail,sendSignInLinkToEmail,setPersistence,signInAnonymously,signInWithCredential,signInWithCustomToken,signInWithEmailAndPassword,signInWithEmailLink,signOut,unlink,updateCurrentUser,updateEmail,updatePassword,updateProfile,useDeviceLanguage,validatePassword,verifyBeforeUpdateEmail,verifyPasswordResetCode};
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import{_getProvider,_isFirebaseServerApp as e,_registerComponent as t,registerVersion as r,getApp as n,SDK_VERSION as i}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";const s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const i=e[t],s=t+1<e.length,o=s?e[t+1]:0,a=t+2<e.length,c=a?e[t+2]:0,u=i>>2,d=(3&i)<<4|o>>4;let l=(15&o)<<2|c>>6,h=63&c;a||(h=64,s||(l=64)),n.push(r[u],r[d],r[l],r[h])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=63&i|128):55296==(64512&i)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++n)),t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const i=e[r++];if(i<128)t[n++]=String.fromCharCode(i);else if(i>191&&i<224){const s=e[r++];t[n++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{const s=e[r++],o=e[r++];t[n++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const i=r[e.charAt(t++)],s=t<e.length?r[e.charAt(t)]:0;++t;const o=t<e.length?r[e.charAt(t)]:64;++t;const a=t<e.length?r[e.charAt(t)]:64;if(++t,null==i||null==s||null==o||null==a)throw new DecodeBase64StringError;const c=i<<2|s>>4;if(n.push(c),64!==o){const e=s<<4&240|o>>2;if(n.push(e),64!==a){const e=o<<6&192|a;n.push(e)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64Decode=function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&base64Decode(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getExperimentalSetting=e=>getDefaults()?.[`_${e}`];class Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,r)=>{t?this.reject(t):this.resolve(r),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,r))}}}function getUA(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,i=this.errors[e],s=i?function replaceTemplate(e,t){return e.replace(o,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(i,r):"Error",a=`${this.serviceName}: ${s} (${n}).`;return new FirebaseError(n,a,r)}}const o=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const r=Object.keys(e),n=Object.keys(t);for(const i of r){if(!n.includes(i))return!1;const r=e[i],s=t[i];if(isObject(r)&&isObject(s)){if(!deepEqual(r,s))return!1}else if(r!==s)return!1}for(const e of n)if(!r.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function querystring(e){const t=[];for(const[r,n]of Object.entries(e))Array.isArray(n)?n.forEach((e=>{t.push(encodeURIComponent(r)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(r)+"="+encodeURIComponent(n));return t.length?"&"+t.join("&"):""}function querystringDecode(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[r,n]=e.split("=");t[decodeURIComponent(r)]=decodeURIComponent(n)}})),t}function extractQuerystring(e){const t=e.indexOf("?");if(!t)return"";const r=e.indexOf("#",t);return e.substring(t,r>0?r:void 0)}class ObserverProxy{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,r){let n;if(void 0===e&&void 0===t&&void 0===r)throw new Error("Missing Observer.");n=function implementsAnyMethods(e,t){if("object"!=typeof e||null===e)return!1;for(const r of t)if(r in e&&"function"==typeof e[r])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:r},void 0===n.next&&(n.next=noop),void 0===n.error&&(n.error=noop),void 0===n.complete&&(n.complete=noop);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?n.error(this.finalError):n.complete()}catch(e){}})),this.observers.push(n),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then((()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function noop(){}function getModularInstance(e){return e&&e._delegate?e._delegate:e}function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}var a;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(a||(a={}));const c={debug:a.DEBUG,verbose:a.VERBOSE,info:a.INFO,warn:a.WARN,error:a.ERROR,silent:a.SILENT},u=a.INFO,d={[a.DEBUG]:"log",[a.VERBOSE]:"log",[a.INFO]:"info",[a.WARN]:"warn",[a.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const n=(new Date).toISOString(),i=d[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${n}] ${e.name}:`,...r)};class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const l={PHONE:"phone",TOTP:"totp"},h={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},p={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password",FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PHONE:"phone",TWITTER:"twitter.com"},f={LINK:"link",REAUTHENTICATE:"reauthenticate",SIGN_IN:"signIn"},m={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function _prodErrorMap(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const g=function _debugErrorMap(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registered for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is incorrect, malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-password":"A non-empty password must be provided","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.","missing-recaptcha-token":"The reCAPTCHA token is missing when sending request to the backend.","invalid-recaptcha-token":"The reCAPTCHA token is invalid when sending request to the backend.","invalid-recaptcha-action":"The reCAPTCHA action is invalid when sending request to the backend.","recaptcha-not-enabled":"reCAPTCHA Enterprise integration is not enabled for this project.","missing-client-type":"The reCAPTCHA client type is missing when sending request to the backend.","missing-recaptcha-version":"The reCAPTCHA version is missing when sending request to the backend.","invalid-req-type":"Invalid request parameters.","invalid-recaptcha-version":"The reCAPTCHA version is invalid when sending request to the backend.","unsupported-password-policy-schema-version":"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.","password-does-not-meet-requirements":"The password does not meet the requirements.","invalid-hosting-link-domain":"The provided Hosting link domain is not configured in Firebase Hosting or is not owned by the current project. This cannot be a default Hosting domain (`web.app` or `firebaseapp.com`)."}},_=_prodErrorMap,I=new ErrorFactory("auth","Firebase",{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}),v={ADMIN_ONLY_OPERATION:"auth/admin-restricted-operation",ARGUMENT_ERROR:"auth/argument-error",APP_NOT_AUTHORIZED:"auth/app-not-authorized",APP_NOT_INSTALLED:"auth/app-not-installed",CAPTCHA_CHECK_FAILED:"auth/captcha-check-failed",CODE_EXPIRED:"auth/code-expired",CORDOVA_NOT_READY:"auth/cordova-not-ready",CORS_UNSUPPORTED:"auth/cors-unsupported",CREDENTIAL_ALREADY_IN_USE:"auth/credential-already-in-use",CREDENTIAL_MISMATCH:"auth/custom-token-mismatch",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"auth/requires-recent-login",DEPENDENT_SDK_INIT_BEFORE_AUTH:"auth/dependent-sdk-initialized-before-auth",DYNAMIC_LINK_NOT_ACTIVATED:"auth/dynamic-link-not-activated",EMAIL_CHANGE_NEEDS_VERIFICATION:"auth/email-change-needs-verification",EMAIL_EXISTS:"auth/email-already-in-use",EMULATOR_CONFIG_FAILED:"auth/emulator-config-failed",EXPIRED_OOB_CODE:"auth/expired-action-code",EXPIRED_POPUP_REQUEST:"auth/cancelled-popup-request",INTERNAL_ERROR:"auth/internal-error",INVALID_API_KEY:"auth/invalid-api-key",INVALID_APP_CREDENTIAL:"auth/invalid-app-credential",INVALID_APP_ID:"auth/invalid-app-id",INVALID_AUTH:"auth/invalid-user-token",INVALID_AUTH_EVENT:"auth/invalid-auth-event",INVALID_CERT_HASH:"auth/invalid-cert-hash",INVALID_CODE:"auth/invalid-verification-code",INVALID_CONTINUE_URI:"auth/invalid-continue-uri",INVALID_CORDOVA_CONFIGURATION:"auth/invalid-cordova-configuration",INVALID_CUSTOM_TOKEN:"auth/invalid-custom-token",INVALID_DYNAMIC_LINK_DOMAIN:"auth/invalid-dynamic-link-domain",INVALID_EMAIL:"auth/invalid-email",INVALID_EMULATOR_SCHEME:"auth/invalid-emulator-scheme",INVALID_IDP_RESPONSE:"auth/invalid-credential",INVALID_LOGIN_CREDENTIALS:"auth/invalid-credential",INVALID_MESSAGE_PAYLOAD:"auth/invalid-message-payload",INVALID_MFA_SESSION:"auth/invalid-multi-factor-session",INVALID_OAUTH_CLIENT_ID:"auth/invalid-oauth-client-id",INVALID_OAUTH_PROVIDER:"auth/invalid-oauth-provider",INVALID_OOB_CODE:"auth/invalid-action-code",INVALID_ORIGIN:"auth/unauthorized-domain",INVALID_PASSWORD:"auth/wrong-password",INVALID_PERSISTENCE:"auth/invalid-persistence-type",INVALID_PHONE_NUMBER:"auth/invalid-phone-number",INVALID_PROVIDER_ID:"auth/invalid-provider-id",INVALID_RECIPIENT_EMAIL:"auth/invalid-recipient-email",INVALID_SENDER:"auth/invalid-sender",INVALID_SESSION_INFO:"auth/invalid-verification-id",INVALID_TENANT_ID:"auth/invalid-tenant-id",MFA_INFO_NOT_FOUND:"auth/multi-factor-info-not-found",MFA_REQUIRED:"auth/multi-factor-auth-required",MISSING_ANDROID_PACKAGE_NAME:"auth/missing-android-pkg-name",MISSING_APP_CREDENTIAL:"auth/missing-app-credential",MISSING_AUTH_DOMAIN:"auth/auth-domain-config-required",MISSING_CODE:"auth/missing-verification-code",MISSING_CONTINUE_URI:"auth/missing-continue-uri",MISSING_IFRAME_START:"auth/missing-iframe-start",MISSING_IOS_BUNDLE_ID:"auth/missing-ios-bundle-id",MISSING_OR_INVALID_NONCE:"auth/missing-or-invalid-nonce",MISSING_MFA_INFO:"auth/missing-multi-factor-info",MISSING_MFA_SESSION:"auth/missing-multi-factor-session",MISSING_PHONE_NUMBER:"auth/missing-phone-number",MISSING_PASSWORD:"auth/missing-password",MISSING_SESSION_INFO:"auth/missing-verification-id",MODULE_DESTROYED:"auth/app-deleted",NEED_CONFIRMATION:"auth/account-exists-with-different-credential",NETWORK_REQUEST_FAILED:"auth/network-request-failed",NULL_USER:"auth/null-user",NO_AUTH_EVENT:"auth/no-auth-event",NO_SUCH_PROVIDER:"auth/no-such-provider",OPERATION_NOT_ALLOWED:"auth/operation-not-allowed",OPERATION_NOT_SUPPORTED:"auth/operation-not-supported-in-this-environment",POPUP_BLOCKED:"auth/popup-blocked",POPUP_CLOSED_BY_USER:"auth/popup-closed-by-user",PROVIDER_ALREADY_LINKED:"auth/provider-already-linked",QUOTA_EXCEEDED:"auth/quota-exceeded",REDIRECT_CANCELLED_BY_USER:"auth/redirect-cancelled-by-user",REDIRECT_OPERATION_PENDING:"auth/redirect-operation-pending",REJECTED_CREDENTIAL:"auth/rejected-credential",SECOND_FACTOR_ALREADY_ENROLLED:"auth/second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"auth/maximum-second-factor-count-exceeded",TENANT_ID_MISMATCH:"auth/tenant-id-mismatch",TIMEOUT:"auth/timeout",TOKEN_EXPIRED:"auth/user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"auth/too-many-requests",UNAUTHORIZED_DOMAIN:"auth/unauthorized-continue-uri",UNSUPPORTED_FIRST_FACTOR:"auth/unsupported-first-factor",UNSUPPORTED_PERSISTENCE:"auth/unsupported-persistence-type",UNSUPPORTED_TENANT_OPERATION:"auth/unsupported-tenant-operation",UNVERIFIED_EMAIL:"auth/unverified-email",USER_CANCELLED:"auth/user-cancelled",USER_DELETED:"auth/user-not-found",USER_DISABLED:"auth/user-disabled",USER_MISMATCH:"auth/user-mismatch",USER_SIGNED_OUT:"auth/user-signed-out",WEAK_PASSWORD:"auth/weak-password",WEB_STORAGE_UNSUPPORTED:"auth/web-storage-unsupported",ALREADY_INITIALIZED:"auth/already-initialized",RECAPTCHA_NOT_ENABLED:"auth/recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"auth/missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"auth/invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"auth/invalid-recaptcha-action",MISSING_CLIENT_TYPE:"auth/missing-client-type",MISSING_RECAPTCHA_VERSION:"auth/missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"auth/invalid-recaptcha-version",INVALID_REQ_TYPE:"auth/invalid-req-type",INVALID_HOSTING_LINK_DOMAIN:"auth/invalid-hosting-link-domain"},E=new class Logger{constructor(e){this.name=e,this._logLevel=u,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in a))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?c[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,a.DEBUG,...e),this._logHandler(this,a.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,a.VERBOSE,...e),this._logHandler(this,a.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,a.INFO,...e),this._logHandler(this,a.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,a.WARN,...e),this._logHandler(this,a.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,a.ERROR,...e),this._logHandler(this,a.ERROR,...e)}}("@firebase/auth");function _logError(e,...t){E.logLevel<=a.ERROR&&E.error(`Auth (${i}): ${e}`,...t)}function _fail(e,...t){throw createErrorInternal(e,...t)}function _createError(e,...t){return createErrorInternal(e,...t)}function _errorWithCustomMessage(e,t,r){const n={..._(),[t]:r};return new ErrorFactory("auth","Firebase",n).create(t,{appName:e.name})}function _serverAppCurrentUserOperationNotSupportedError(e){return _errorWithCustomMessage(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function _assertInstanceOf(e,t,r){if(!(t instanceof r))throw r.name!==t.constructor.name&&_fail(e,"argument-error"),_errorWithCustomMessage(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`)}function createErrorInternal(e,...t){if("string"!=typeof e){const r=t[0],n=[...t.slice(1)];return n[0]&&(n[0].appName=e.name),e._errorFactory.create(r,...n)}return I.create(e,...t)}function _assert(e,t,...r){if(!e)throw createErrorInternal(t,...r)}function debugFail(e){const t="INTERNAL ASSERTION FAILED: "+e;throw _logError(t),new Error(t)}function debugAssert(e,t){e||debugFail(t)}function _getCurrentUrl(){return"undefined"!=typeof self&&self.location?.href||""}function _isHttpOrHttps(){return"http:"===_getCurrentScheme()||"https:"===_getCurrentScheme()}function _getCurrentScheme(){return"undefined"!=typeof self&&self.location?.protocol||null}function _isOnline(){return!("undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(_isHttpOrHttps()||function isBrowserExtension(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}()||"connection"in navigator))||navigator.onLine}class Delay{constructor(e,t){this.shortDelay=e,this.longDelay=t,debugAssert(t>e,"Short delay should be less than long delay!"),this.isMobile=function isMobileCordova(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())}()||function isReactNative(){return"object"==typeof navigator&&"ReactNative"===navigator.product}()}get(){return _isOnline()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function _emulatorUrl(e,t){debugAssert(e.emulator,"Emulator should always be set here");const{url:r}=e.emulator;return t?`${r}${t.startsWith("/")?t.slice(1):t}`:r}class FetchProvider{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!=typeof self&&"fetch"in self?self.fetch:"undefined"!=typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!=typeof fetch?fetch:void debugFail("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"undefined"!=typeof self&&"Headers"in self?self.Headers:"undefined"!=typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!=typeof Headers?Headers:void debugFail("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"undefined"!=typeof self&&"Response"in self?self.Response:"undefined"!=typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!=typeof Response?Response:void debugFail("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const T={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},A=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],y=new Delay(3e4,6e4);function _addTidIfNecessary(e,t){return e.tenantId&&!t.tenantId?{...t,tenantId:e.tenantId}:t}async function _performApiRequest(e,t,r,n,i={}){return _performFetchWithErrorHandling(e,i,(async()=>{let i={},s={};n&&("GET"===t?s=n:i={body:JSON.stringify(n)});const o=querystring({...s,key:e.config.apiKey}).slice(1),a=await e._getAdditionalHeaders();a["Content-Type"]="application/json",e.languageCode&&(a["X-Firebase-Locale"]=e.languageCode);const c={method:t,headers:a,...i};return function isCloudflareWorker(){return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent}()||(c.referrerPolicy="strict-origin-when-cross-origin"),e.emulatorConfig&&isCloudWorkstation(e.emulatorConfig.host)&&(c.credentials="include"),FetchProvider.fetch()(await _getFinalTarget(e,e.config.apiHost,r,o),c)}))}async function _performFetchWithErrorHandling(e,t,r){e._canInitEmulator=!1;const n={...T,...t};try{const t=new NetworkTimeout(e),i=await Promise.race([r(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if("needConfirmation"in s)throw _makeTaggedError(e,"account-exists-with-different-credential",s);if(i.ok&&!("errorMessage"in s))return s;{const t=i.ok?s.errorMessage:s.error.message,[r,o]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===r)throw _makeTaggedError(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===r)throw _makeTaggedError(e,"email-already-in-use",s);if("USER_DISABLED"===r)throw _makeTaggedError(e,"user-disabled",s);const a=n[r]||r.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw _errorWithCustomMessage(e,a,o);_fail(e,a)}}catch(t){if(t instanceof FirebaseError)throw t;_fail(e,"network-request-failed",{message:String(t)})}}async function _performSignInRequest(e,t,r,n,i={}){const s=await _performApiRequest(e,t,r,n,i);return"mfaPendingCredential"in s&&_fail(e,"multi-factor-auth-required",{_serverResponse:s}),s}async function _getFinalTarget(e,t,r,n){const i=`${t}${r}?${n}`,s=e,o=s.config.emulator?_emulatorUrl(e.config,i):`${e.config.apiScheme}://${i}`;if(A.includes(r)&&(await s._persistenceManagerAvailable,"COOKIE"===s._getPersistenceType())){return s._getPersistence()._getFinalTarget(o).toString()}return o}function _parseEnforcementState(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class NetworkTimeout{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(_createError(this.auth,"network-request-failed"))),y.get())}))}}function _makeTaggedError(e,t,r){const n={appName:e.name};r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber);const i=_createError(e,t,n);return i.customData._tokenResponse=r,i}function isV2(e){return void 0!==e&&void 0!==e.getResponse}function isEnterprise(e){return void 0!==e&&void 0!==e.enterprise}class RecaptchaConfig{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return _parseEnforcementState(t.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function getRecaptchaConfig(e,t){return _performApiRequest(e,"GET","/v2/recaptchaConfig",_addTidIfNecessary(e,t))}async function getAccountInfo(e,t){return _performApiRequest(e,"POST","/v1/accounts:lookup",t)}function utcTimestampToDateString(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function getIdToken(e,t=!1){return getModularInstance(e).getIdToken(t)}async function getIdTokenResult(e,t=!1){const r=getModularInstance(e),n=await r.getIdToken(t),i=_parseToken(n);_assert(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error");const s="object"==typeof i.firebase?i.firebase:void 0,o=s?.sign_in_provider;return{claims:i,token:n,authTime:utcTimestampToDateString(secondsStringToMilliseconds(i.auth_time)),issuedAtTime:utcTimestampToDateString(secondsStringToMilliseconds(i.iat)),expirationTime:utcTimestampToDateString(secondsStringToMilliseconds(i.exp)),signInProvider:o||null,signInSecondFactor:s?.sign_in_second_factor||null}}function secondsStringToMilliseconds(e){return 1e3*Number(e)}function _parseToken(e){const[t,r,n]=e.split(".");if(void 0===t||void 0===r||void 0===n)return _logError("JWT malformed, contained fewer than 3 sections"),null;try{const e=base64Decode(r);return e?JSON.parse(e):(_logError("Failed to decode base64 JWT payload"),null)}catch(e){return _logError("Caught error parsing JWT payload as JSON",e?.toString()),null}}function _tokenExpiresIn(e){const t=_parseToken(e);return _assert(t,"internal-error"),_assert(void 0!==t.exp,"internal-error"),_assert(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function _logoutIfInvalidated(e,t,r=!1){if(r)return t;try{return await t}catch(t){throw t instanceof FirebaseError&&function isUserInvalidated({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class ProactiveRefresh{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,e)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout((async()=>{await this.iteration()}),t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===e?.code&&this.schedule(!0))}this.schedule()}}class UserMetadata{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=utcTimestampToDateString(this.lastLoginAt),this.creationTime=utcTimestampToDateString(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function _reloadWithoutSaving(e){const t=e.auth,r=await e.getIdToken(),n=await _logoutIfInvalidated(e,getAccountInfo(t,{idToken:r}));_assert(n?.users.length,t,"internal-error");const i=n.users[0];e._notifyReloadListener(i);const s=i.providerUserInfo?.length?extractProviderData(i.providerUserInfo):[],o=function mergeProviderData(e,t){return[...e.filter((e=>!t.some((t=>t.providerId===e.providerId)))),...t]}(e.providerData,s),a=e.isAnonymous,c=!(e.email&&i.passwordHash||o?.length),u=!!a&&c,d={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:o,metadata:new UserMetadata(i.createdAt,i.lastLoginAt),isAnonymous:u};Object.assign(e,d)}async function reload(e){const t=getModularInstance(e);await _reloadWithoutSaving(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}function extractProviderData(e){return e.map((({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null})))}class StsTokenManager{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){_assert(e.idToken,"internal-error"),_assert(void 0!==e.idToken,"internal-error"),_assert(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):_tokenExpiresIn(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){_assert(0!==e.length,"internal-error");const t=_tokenExpiresIn(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(_assert(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null):this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:r,refreshToken:n,expiresIn:i}=await async function requestStsToken(e,t){const r=await _performFetchWithErrorHandling(e,{},(async()=>{const r=querystring({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:n,apiKey:i}=e.config,s=await _getFinalTarget(e,n,"/v1/token",`key=${i}`),o=await e._getAdditionalHeaders();o["Content-Type"]="application/x-www-form-urlencoded";const a={method:"POST",headers:o,body:r};return e.emulatorConfig&&isCloudWorkstation(e.emulatorConfig.host)&&(a.credentials="include"),FetchProvider.fetch()(s,a)}));return{accessToken:r.access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token}}(e,t);this.updateTokensAndExpiration(r,n,Number(i))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*r}static fromJSON(e,t){const{refreshToken:r,accessToken:n,expirationTime:i}=t,s=new StsTokenManager;return r&&(_assert("string"==typeof r,"internal-error",{appName:e}),s.refreshToken=r),n&&(_assert("string"==typeof n,"internal-error",{appName:e}),s.accessToken=n),i&&(_assert("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new StsTokenManager,this.toJSON())}_performRefresh(){return debugFail("not implemented")}}function assertStringOrUndefined(e,t){_assert("string"==typeof e||void 0===e,"internal-error",{appName:t})}class UserImpl{constructor({uid:e,auth:t,stsTokenManager:r,...n}){this.providerId="firebase",this.proactiveRefresh=new ProactiveRefresh(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=n.displayName||null,this.email=n.email||null,this.emailVerified=n.emailVerified||!1,this.phoneNumber=n.phoneNumber||null,this.photoURL=n.photoURL||null,this.isAnonymous=n.isAnonymous||!1,this.tenantId=n.tenantId||null,this.providerData=n.providerData?[...n.providerData]:[],this.metadata=new UserMetadata(n.createdAt||void 0,n.lastLoginAt||void 0)}async getIdToken(e){const t=await _logoutIfInvalidated(this,this.stsTokenManager.getToken(this.auth,e));return _assert(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return getIdTokenResult(this,e)}reload(){return reload(this)}_assign(e){this!==e&&(_assert(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map((e=>({...e}))),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new UserImpl({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){_assert(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await _reloadWithoutSaving(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(e(this.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));const t=await this.getIdToken();return await _logoutIfInvalidated(this,async function deleteAccount(e,t){return _performApiRequest(e,"POST","/v1/accounts:delete",t)}(this.auth,{idToken:t})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map((e=>({...e}))),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){const r=t.displayName??void 0,n=t.email??void 0,i=t.phoneNumber??void 0,s=t.photoURL??void 0,o=t.tenantId??void 0,a=t._redirectEventId??void 0,c=t.createdAt??void 0,u=t.lastLoginAt??void 0,{uid:d,emailVerified:l,isAnonymous:h,providerData:p,stsTokenManager:f}=t;_assert(d&&f,e,"internal-error");const m=StsTokenManager.fromJSON(this.name,f);_assert("string"==typeof d,e,"internal-error"),assertStringOrUndefined(r,e.name),assertStringOrUndefined(n,e.name),_assert("boolean"==typeof l,e,"internal-error"),_assert("boolean"==typeof h,e,"internal-error"),assertStringOrUndefined(i,e.name),assertStringOrUndefined(s,e.name),assertStringOrUndefined(o,e.name),assertStringOrUndefined(a,e.name),assertStringOrUndefined(c,e.name),assertStringOrUndefined(u,e.name);const g=new UserImpl({uid:d,auth:e,email:n,emailVerified:l,displayName:r,isAnonymous:h,photoURL:s,phoneNumber:i,tenantId:o,stsTokenManager:m,createdAt:c,lastLoginAt:u});return p&&Array.isArray(p)&&(g.providerData=p.map((e=>({...e})))),a&&(g._redirectEventId=a),g}static async _fromIdTokenResponse(e,t,r=!1){const n=new StsTokenManager;n.updateFromServerResponse(t);const i=new UserImpl({uid:t.localId,auth:e,stsTokenManager:n,isAnonymous:r});return await _reloadWithoutSaving(i),i}static async _fromGetAccountInfoResponse(e,t,r){const n=t.users[0];_assert(void 0!==n.localId,"internal-error");const i=void 0!==n.providerUserInfo?extractProviderData(n.providerUserInfo):[],s=!(n.email&&n.passwordHash||i?.length),o=new StsTokenManager;o.updateFromIdToken(r);const a=new UserImpl({uid:n.localId,auth:e,stsTokenManager:o,isAnonymous:s}),c={uid:n.localId,displayName:n.displayName||null,photoURL:n.photoUrl||null,email:n.email||null,emailVerified:n.emailVerified||!1,phoneNumber:n.phoneNumber||null,tenantId:n.tenantId||null,providerData:i,metadata:new UserMetadata(n.createdAt,n.lastLoginAt),isAnonymous:!(n.email&&n.passwordHash||i?.length)};return Object.assign(a,c),a}}const w=new Map;function _getInstance(e){debugAssert(e instanceof Function,"Expected a class definition");let t=w.get(e);return t?(debugAssert(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,w.set(e,t),t)}class InMemoryPersistence{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}InMemoryPersistence.type="NONE";const S=InMemoryPersistence;function _persistenceKeyName(e,t,r){return`firebase:${e}:${t}:${r}`}class PersistenceUserManager{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;const{config:n,name:i}=this.auth;this.fullUserKey=_persistenceKeyName(this.userKey,n.apiKey,i),this.fullPersistenceKey=_persistenceKeyName("persistence",n.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);if(!e)return null;if("string"==typeof e){const t=await getAccountInfo(this.auth,{idToken:e}).catch((()=>{}));return t?UserImpl._fromGetAccountInfoResponse(this.auth,t,e):null}return UserImpl._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,r="authUser"){if(!t.length)return new PersistenceUserManager(_getInstance(S),e,r);const n=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let i=n[0]||_getInstance(S);const s=_persistenceKeyName(r,e.config.apiKey,e.name);let o=null;for(const r of t)try{const t=await r._get(s);if(t){let n;if("string"==typeof t){const r=await getAccountInfo(e,{idToken:t}).catch((()=>{}));if(!r)break;n=await UserImpl._fromGetAccountInfoResponse(e,r,t)}else n=UserImpl._fromJSON(e,t);r!==i&&(o=n),i=r;break}}catch{}const a=n.filter((e=>e._shouldAllowMigration));return i._shouldAllowMigration&&a.length?(i=a[0],o&&await i._set(s,o.toJSON()),await Promise.all(t.map((async e=>{if(e!==i)try{await e._remove(s)}catch{}}))),new PersistenceUserManager(i,e,r)):new PersistenceUserManager(i,e,r)}}function _getBrowserName(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(_isIEMobile(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(_isFirefox(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(_isBlackBerry(t))return"Blackberry";if(_isWebOS(t))return"Webos";if(_isSafari(t))return"Safari";if((t.includes("chrome/")||_isChromeIOS(t))&&!t.includes("edge/"))return"Chrome";if(_isAndroid(t))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=e.match(t);if(2===r?.length)return r[1]}return"Other"}function _isFirefox(e=getUA()){return/firefox\//i.test(e)}function _isSafari(e=getUA()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function _isChromeIOS(e=getUA()){return/crios\//i.test(e)}function _isIEMobile(e=getUA()){return/iemobile/i.test(e)}function _isAndroid(e=getUA()){return/android/i.test(e)}function _isBlackBerry(e=getUA()){return/blackberry/i.test(e)}function _isWebOS(e=getUA()){return/webos/i.test(e)}function _isIOS(e=getUA()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function _isIE10(){return function isIE(){const e=getUA();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}()&&10===document.documentMode}function _isMobileBrowser(e=getUA()){return _isIOS(e)||_isAndroid(e)||_isWebOS(e)||_isBlackBerry(e)||/windows phone/i.test(e)||_isIEMobile(e)}function _getClientVersion(e,t=[]){let r;switch(e){case"Browser":r=_getBrowserName(getUA());break;case"Worker":r=`${_getBrowserName(getUA())}-${e}`;break;default:r=e}const n=t.length?t.join(","):"FirebaseCore-web";return`${r}/JsCore/${i}/${n}`}class AuthMiddlewareQueue{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const wrappedCallback=t=>new Promise(((r,n)=>{try{r(e(t))}catch(e){n(e)}}));wrappedCallback.onAbort=t,this.queue.push(wrappedCallback);const r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(e){t.reverse();for(const e of t)try{e()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:e?.message})}}}class PasswordPolicyImpl{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??6,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),void 0!==t.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),void 0!==t.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),void 0!==t.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),void 0!==t.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){const t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){const r=this.customStrengthOptions.minPasswordLength,n=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),n&&(t.meetsMaxPasswordLength=e.length<=n)}validatePasswordCharacterOptions(e,t){let r;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let n=0;n<e.length;n++)r=e.charAt(n),this.updatePasswordCharacterOptionsStatuses(t,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,n,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=n)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class AuthImpl{constructor(e,t,r,n){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Subscription(this),this.idTokenSubscription=new Subscription(this),this.beforeStateQueue=new AuthMiddlewareQueue(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=I,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion,this._persistenceManagerAvailable=new Promise((e=>this._resolvePersistenceManagerAvailable=e))}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=_getInstance(t)),this._initializationPromise=this.queue((async()=>{if(!this._deleted&&(this.persistenceManager=await PersistenceUserManager.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0):void 0}async initializeCurrentUserFromIdToken(e){try{const t=await getAccountInfo(this,{idToken:e}),r=await UserImpl._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(t){if(e(this.app)){const e=this.app.settings.authIdToken;return e?new Promise((t=>{setTimeout((()=>this.initializeCurrentUserFromIdToken(e).then(t,t)))})):this.directlySetCurrentUser(null)}const r=await this.assertedPersistence.getCurrentUser();let n=r,i=!1;if(t&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const e=this.redirectUser?._redirectEventId,r=n?._redirectEventId,s=await this.tryRedirectSignIn(t);e&&e!==r||!s?.user||(n=s.user,i=!0)}if(!n)return this.directlySetCurrentUser(null);if(!n._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(n)}catch(e){n=r,this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(e)))}return n?this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}return _assert(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId?this.directlySetCurrentUser(n):this.reloadAndSetCurrentUserOrClear(n)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await _reloadWithoutSaving(e)}catch(e){if("auth/network-request-failed"!==e?.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function _getUserLanguage(){if("undefined"==typeof navigator)return null;const e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(t){if(e(this.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));const r=t?getModularInstance(t):null;return r&&_assert(r.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(r&&r._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&_assert(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue((async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()}))}async signOut(){return e(this.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(t){return e(this.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)):this.queue((async()=>{await this.assertedPersistence.setPersistence(_getInstance(t))}))}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await async function _getPasswordPolicy(e,t={}){return _performApiRequest(e,"GET","/v2/passwordPolicy",_addTidIfNecessary(e,t))}(this),t=new PasswordPolicyImpl(e);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new ErrorFactory("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser)e();else{const r=this.onAuthStateChanged((()=>{r(),e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await async function revokeToken(e,t){return _performApiRequest(e,"POST","/v2/accounts:revokeToken",_addTidIfNecessary(e,t))}(this,t)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){const r=await this.getOrInitRedirectPersistenceManager(t);return null===e?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&_getInstance(e)||this._popupRedirectResolver;_assert(t,this,"argument-error"),this.redirectPersistenceManager=await PersistenceUserManager.create(this,[_getInstance(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue((async()=>{})),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(e)))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,r,n){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t);let s=!1;const o=this._isInitialized?Promise.resolve():this._initializationPromise;if(_assert(o,this,"internal-error"),o.then((()=>{s||i(this.currentUser)})),"function"==typeof t){const i=e.addObserver(t,r,n);return()=>{s=!0,i()}}{const r=e.addObserver(t);return()=>{s=!0,r()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return _assert(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=_getClientVersion(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);const t=await(this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader());t&&(e["X-Firebase-Client"]=t);const r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(e(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const t=await(this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken());return t?.error&&function _logWarn(e,...t){E.logLevel<=a.WARN&&E.warn(`Auth (${i}): ${e}`,...t)}(`Error while retrieving App Check token: ${t.error}`),t?.token}}function _castAuth(e){return getModularInstance(e)}class Subscription{constructor(e){this.auth=e,this.observer=null,this.addObserver=function createSubscribe(e,t){const r=new ObserverProxy(e,t);return r.subscribe.bind(r)}((e=>this.observer=e))}get next(){return _assert(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let P={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function _loadJS(e){return P.loadJS(e)}function _generateCallbackName(e){return`__${e}${Math.floor(1e6*Math.random())}`}const R=1e12;class MockReCaptcha{constructor(e){this.auth=e,this.counter=R,this._widgets=new Map}render(e,t){const r=this.counter;return this._widgets.set(r,new MockWidget(e,this.auth.name,t||{})),this.counter++,r}reset(e){const t=e||R;this._widgets.get(t)?.delete(),this._widgets.delete(t)}getResponse(e){const t=e||R;return this._widgets.get(t)?.getResponse()||""}async execute(e){const t=e||R;return this._widgets.get(t)?.execute(),""}}class MockGreCAPTCHATopLevel{constructor(){this.enterprise=new MockGreCAPTCHA}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class MockGreCAPTCHA{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class MockWidget{constructor(e,t,r){this.params=r,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};const n="string"==typeof e?document.getElementById(e):e;_assert(n,"argument-error",{appName:t}),this.container=n,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout((()=>{this.responseToken=function generateRandomAlphaNumericString(e){const t=[],r="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<e;n++)t.push(r.charAt(Math.floor(Math.random()*r.length)));return t.join("")}(50);const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout((()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()}),6e4)}),500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}const k="NO_RECAPTCHA",C="onFirebaseAuthREInstanceReady";class RecaptchaEnterpriseVerifier{constructor(e){this.type="recaptcha-enterprise",this.auth=_castAuth(e)}async verify(e="verify",t=!1){function retrieveRecaptchaToken(t,r,n){const i=window.grecaptcha;isEnterprise(i)?i.enterprise.ready((()=>{i.enterprise.execute(t,{action:e}).then((e=>{r(e)})).catch((()=>{r(k)}))})):n(Error("No reCAPTCHA enterprise script loaded."))}if(this.auth.settings.appVerificationDisabledForTesting){return(new MockGreCAPTCHATopLevel).execute("siteKey",{action:"verify"})}return new Promise(((e,r)=>{(async function retrieveSiteKey(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise((async(t,r)=>{getRecaptchaConfig(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((n=>{if(void 0!==n.recaptchaKey){const r=new RecaptchaConfig(n);return null==e.tenantId?e._agentRecaptchaConfig=r:e._tenantRecaptchaConfigs[e.tenantId]=r,t(r.siteKey)}r(new Error("recaptcha Enterprise site key undefined"))})).catch((e=>{r(e)}))}))})(this.auth).then((async n=>{if(!t&&isEnterprise(window.grecaptcha)&&RecaptchaEnterpriseVerifier.scriptInjectionDeferred)await RecaptchaEnterpriseVerifier.scriptInjectionDeferred.promise,retrieveRecaptchaToken(n,e,r);else{if("undefined"==typeof window)return void r(new Error("RecaptchaVerifier is only supported in browser"));let t=function _recaptchaEnterpriseScriptUrl(){return P.recaptchaEnterpriseScript}();0!==t.length&&(t+=n+`&onload=${C}`),RecaptchaEnterpriseVerifier.scriptInjectionDeferred=new Deferred,window[C]=()=>{RecaptchaEnterpriseVerifier.scriptInjectionDeferred?.resolve()},_loadJS(t).then((()=>RecaptchaEnterpriseVerifier.scriptInjectionDeferred?.promise)).then((()=>{retrieveRecaptchaToken(n,e,r)})).catch((e=>{r(e)}))}})).catch((e=>{r(e)}))}))}}async function injectRecaptchaFields(e,t,r,n=!1,i=!1){const s=new RecaptchaEnterpriseVerifier(e);let o;if(i)o=k;else try{o=await s.verify(r)}catch(e){o=await s.verify(r,!0)}const a={...t};if("mfaSmsEnrollment"===r||"mfaSmsSignIn"===r){if("phoneEnrollmentInfo"in a){const e=a.phoneEnrollmentInfo.phoneNumber,t=a.phoneEnrollmentInfo.recaptchaToken;Object.assign(a,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:t,captchaResponse:o,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in a){const e=a.phoneSignInInfo.recaptchaToken;Object.assign(a,{phoneSignInInfo:{recaptchaToken:e,captchaResponse:o,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return a}return n?Object.assign(a,{captchaResp:o}):Object.assign(a,{captchaResponse:o}),Object.assign(a,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(a,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),a}async function handleRecaptchaFlow(e,t,r,n,i){if("EMAIL_PASSWORD_PROVIDER"===i){if(e._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await injectRecaptchaFields(e,t,r,"getOobCode"===r);return n(e,i)}return n(e,t).catch((async i=>{if("auth/missing-recaptcha-token"===i.code){console.log(`${r} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const i=await injectRecaptchaFields(e,t,r,"getOobCode"===r);return n(e,i)}return Promise.reject(i)}))}if("PHONE_PROVIDER"===i){if(e._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){const i=await injectRecaptchaFields(e,t,r);return n(e,i).catch((async i=>{if("AUDIT"===e._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")&&("auth/missing-recaptcha-token"===i.code||"auth/invalid-app-credential"===i.code)){console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${r} flow.`);const i=await injectRecaptchaFields(e,t,r,!1,!0);return n(e,i)}return Promise.reject(i)}))}{const i=await injectRecaptchaFields(e,t,r,!1,!0);return n(e,i)}}return Promise.reject(i+" provider is not supported.")}async function _initializeRecaptchaConfig(e){const t=_castAuth(e),r=await getRecaptchaConfig(t,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}),n=new RecaptchaConfig(r);if(null==t.tenantId?t._agentRecaptchaConfig=n:t._tenantRecaptchaConfigs[t.tenantId]=n,n.isAnyProviderEnabled()){new RecaptchaEnterpriseVerifier(t).verify()}}function initializeAuth(e,t){const r=_getProvider(e,"auth");if(r.isInitialized()){const e=r.getImmediate();if(deepEqual(r.getOptions(),t??{}))return e;_fail(e,"already-initialized")}return r.initialize({options:t})}function connectAuthEmulator(e,t,r){const n=_castAuth(e);_assert(/^https?:\/\//.test(t),n,"invalid-emulator-scheme");const i=!!r?.disableWarnings,s=extractProtocol(t),{host:o,port:a}=function extractHostAndPort(e){const t=extractProtocol(e),r=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!r)return{host:"",port:null};const n=r[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(n);if(i){const e=i[1];return{host:e,port:parsePort(n.substr(e.length+1))}}{const[e,t]=n.split(":");return{host:e,port:parsePort(t)}}}(t),c=null===a?"":`:${a}`,u={url:`${s}//${o}${c}/`},d=Object.freeze({host:o,port:a,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})});if(!n._canInitEmulator)return _assert(n.config.emulator&&n.emulatorConfig,n,"emulator-config-failed"),void _assert(deepEqual(u,n.config.emulator)&&deepEqual(d,n.emulatorConfig),n,"emulator-config-failed");n.config.emulator=u,n.emulatorConfig=d,n.settings.appVerificationDisabledForTesting=!0,isCloudWorkstation(o)?async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(`${s}//${o}${c}`):i||function emitEmulatorWarning(){function attachBanner(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials.");"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",attachBanner):attachBanner())}()}function extractProtocol(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function parsePort(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}RecaptchaEnterpriseVerifier.scriptInjectionDeferred=null;class AuthCredential{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return debugFail("not implemented")}_getIdTokenResponse(e){return debugFail("not implemented")}_linkToIdToken(e,t){return debugFail("not implemented")}_getReauthenticationResolver(e){return debugFail("not implemented")}}async function resetPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:resetPassword",_addTidIfNecessary(e,t))}async function linkEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:signUp",t)}async function signInWithPassword(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPassword",_addTidIfNecessary(e,t))}async function sendOobCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendOobCode",_addTidIfNecessary(e,t))}async function sendPasswordResetEmail$1(e,t){return sendOobCode(e,t)}async function sendSignInLinkToEmail$1(e,t){return sendOobCode(e,t)}class EmailAuthCredential extends AuthCredential{constructor(e,t,r,n=null){super("password",r),this._email=e,this._password=t,this._tenantId=n}static _fromEmailAndPassword(e,t){return new EmailAuthCredential(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new EmailAuthCredential(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e;if(t?.email&&t?.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return handleRecaptchaFlow(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",signInWithPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return async function signInWithEmailLink$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}(e,{email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return handleRecaptchaFlow(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",linkEmailPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return async function signInWithEmailLinkForLinking(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function signInWithIdp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithIdp",_addTidIfNecessary(e,t))}class OAuthCredential extends AuthCredential{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new OAuthCredential(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):_fail("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:r,signInMethod:n,...i}=t;if(!r||!n)return null;const s=new OAuthCredential(r,n);return s.idToken=i.idToken||void 0,s.accessToken=i.accessToken||void 0,s.secret=i.secret,s.nonce=i.nonce,s.pendingToken=i.pendingToken||null,s}_getIdTokenResponse(e){return signInWithIdp(e,this.buildRequest())}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,signInWithIdp(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,signInWithIdp(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=querystring(t)}return e}}async function sendPhoneVerificationCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendVerificationCode",_addTidIfNecessary(e,t))}const b={USER_NOT_FOUND:"user-not-found"};class PhoneAuthCredential extends AuthCredential{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new PhoneAuthCredential({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new PhoneAuthCredential({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function signInWithPhoneNumber$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function linkWithPhoneNumber$1(e,t){const r=await _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t));if(r.temporaryProof)throw _makeTaggedError(e,"account-exists-with-different-credential",r);return r}(e,{idToken:t,...this._makeVerificationRequest()})}_getReauthenticationResolver(e){return async function verifyPhoneNumberForExisting(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,{...t,operation:"REAUTH"}),b)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:r,verificationCode:n}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:r,code:n}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}=e;return r||t||n||i?new PhoneAuthCredential({verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}):null}}class ActionCodeURL{constructor(e){const t=querystringDecode(extractQuerystring(e)),r=t.apiKey??null,n=t.oobCode??null,i=function parseMode(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(t.mode??null);_assert(r&&n&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=n,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){const t=function parseDeepLink(e){const t=querystringDecode(extractQuerystring(e)).link,r=t?querystringDecode(extractQuerystring(t)).deep_link_id:null,n=querystringDecode(extractQuerystring(e)).deep_link_id;return(n?querystringDecode(extractQuerystring(n)).link:null)||n||r||t||e}(e);try{return new ActionCodeURL(t)}catch{return null}}}function parseActionCodeURL(e){return ActionCodeURL.parseLink(e)}class EmailAuthProvider{constructor(){this.providerId=EmailAuthProvider.PROVIDER_ID}static credential(e,t){return EmailAuthCredential._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const r=ActionCodeURL.parseLink(t);return _assert(r,"argument-error"),EmailAuthCredential._fromEmailAndCode(e,r.code,r.tenantId)}}EmailAuthProvider.PROVIDER_ID="password",EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD="password",EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class FederatedAuthProvider{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class BaseOAuthProvider extends FederatedAuthProvider{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class OAuthProvider extends BaseOAuthProvider{static credentialFromJSON(e){const t="string"==typeof e?JSON.parse(e):e;return _assert("providerId"in t&&"signInMethod"in t,"argument-error"),OAuthCredential._fromParams(t)}credential(e){return this._credential({...e,nonce:e.rawNonce})}_credential(e){return _assert(e.idToken||e.accessToken,"argument-error"),OAuthCredential._fromParams({...e,providerId:this.providerId,signInMethod:this.providerId})}static credentialFromResult(e){return OAuthProvider.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return OAuthProvider.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r,oauthTokenSecret:n,pendingToken:i,nonce:s,providerId:o}=e;if(!(r||n||t||i))return null;if(!o)return null;try{return new OAuthProvider(o)._credential({idToken:t,accessToken:r,nonce:s,pendingToken:i})}catch(e){return null}}}class FacebookAuthProvider extends BaseOAuthProvider{constructor(){super("facebook.com")}static credential(e){return OAuthCredential._fromParams({providerId:FacebookAuthProvider.PROVIDER_ID,signInMethod:FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return FacebookAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return FacebookAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return FacebookAuthProvider.credential(e.oauthAccessToken)}catch{return null}}}FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD="facebook.com",FacebookAuthProvider.PROVIDER_ID="facebook.com";class GoogleAuthProvider extends BaseOAuthProvider{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return OAuthCredential._fromParams({providerId:GoogleAuthProvider.PROVIDER_ID,signInMethod:GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return GoogleAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GoogleAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return GoogleAuthProvider.credential(t,r)}catch{return null}}}GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD="google.com",GoogleAuthProvider.PROVIDER_ID="google.com";class GithubAuthProvider extends BaseOAuthProvider{constructor(){super("github.com")}static credential(e){return OAuthCredential._fromParams({providerId:GithubAuthProvider.PROVIDER_ID,signInMethod:GithubAuthProvider.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return GithubAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GithubAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return GithubAuthProvider.credential(e.oauthAccessToken)}catch{return null}}}GithubAuthProvider.GITHUB_SIGN_IN_METHOD="github.com",GithubAuthProvider.PROVIDER_ID="github.com";class SAMLAuthCredential extends AuthCredential{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return signInWithIdp(e,this.buildRequest())}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,signInWithIdp(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,signInWithIdp(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:r,signInMethod:n,pendingToken:i}=t;return r&&n&&i&&r===n?new SAMLAuthCredential(r,i):null}static _create(e,t){return new SAMLAuthCredential(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class SAMLAuthProvider extends FederatedAuthProvider{constructor(e){_assert(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){const t=SAMLAuthCredential.fromJSON(e);return _assert(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{pendingToken:t,providerId:r}=e;if(!t||!r)return null;try{return SAMLAuthCredential._create(r,t)}catch(e){return null}}}class TwitterAuthProvider extends BaseOAuthProvider{constructor(){super("twitter.com")}static credential(e,t){return OAuthCredential._fromParams({providerId:TwitterAuthProvider.PROVIDER_ID,signInMethod:TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return TwitterAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return TwitterAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return TwitterAuthProvider.credential(t,r)}catch{return null}}}async function signUp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signUp",_addTidIfNecessary(e,t))}TwitterAuthProvider.TWITTER_SIGN_IN_METHOD="twitter.com",TwitterAuthProvider.PROVIDER_ID="twitter.com";class UserCredentialImpl{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,n=!1){const i=await UserImpl._fromIdTokenResponse(e,r,n),s=providerIdForResponse(r);return new UserCredentialImpl({user:i,providerId:s,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);const n=providerIdForResponse(r);return new UserCredentialImpl({user:e,providerId:n,_tokenResponse:r,operationType:t})}}function providerIdForResponse(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}async function signInAnonymously(t){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const r=_castAuth(t);if(await r._initializationPromise,r.currentUser?.isAnonymous)return new UserCredentialImpl({user:r.currentUser,providerId:null,operationType:"signIn"});const n=await signUp(r,{returnSecureToken:!0}),i=await UserCredentialImpl._fromIdTokenResponse(r,"signIn",n,!0);return await r._updateCurrentUser(i.user),i}class MultiFactorError extends FirebaseError{constructor(e,t,r,n){super(t.code,t.message),this.operationType=r,this.user=n,Object.setPrototypeOf(this,MultiFactorError.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,n){return new MultiFactorError(e,t,r,n)}}function _processCredentialSavingMfaContextIfNecessary(e,t,r,n){return("reauthenticate"===t?r._getReauthenticationResolver(e):r._getIdTokenResponse(e)).catch((r=>{if("auth/multi-factor-auth-required"===r.code)throw MultiFactorError._fromErrorAndOperation(e,r,t,n);throw r}))}function providerDataAsNames(e){return new Set(e.map((({providerId:e})=>e)).filter((e=>!!e)))}async function unlink(e,t){const r=getModularInstance(e);await _assertLinkedStatus(!0,r,t);const{providerUserInfo:n}=await async function deleteLinkedAccounts(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}(r.auth,{idToken:await r.getIdToken(),deleteProvider:[t]}),i=providerDataAsNames(n||[]);return r.providerData=r.providerData.filter((e=>i.has(e.providerId))),i.has("phone")||(r.phoneNumber=null),await r.auth._persistUserIfCurrent(r),r}async function _link$1(e,t,r=!1){const n=await _logoutIfInvalidated(e,t._linkToIdToken(e.auth,await e.getIdToken()),r);return UserCredentialImpl._forOperation(e,"link",n)}async function _assertLinkedStatus(e,t,r){await _reloadWithoutSaving(t);const n=!1===e?"provider-already-linked":"no-such-provider";_assert(providerDataAsNames(t.providerData).has(r)===e,t.auth,n)}async function _reauthenticate(t,r,n=!1){const{auth:i}=t;if(e(i.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i));const s="reauthenticate";try{const e=await _logoutIfInvalidated(t,_processCredentialSavingMfaContextIfNecessary(i,s,r,t),n);_assert(e.idToken,i,"internal-error");const o=_parseToken(e.idToken);_assert(o,i,"internal-error");const{sub:a}=o;return _assert(t.uid===a,i,"user-mismatch"),UserCredentialImpl._forOperation(t,s,e)}catch(e){throw"auth/user-not-found"===e?.code&&_fail(i,"user-mismatch"),e}}async function _signInWithCredential(t,r,n=!1){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i="signIn",s=await _processCredentialSavingMfaContextIfNecessary(t,i,r),o=await UserCredentialImpl._fromIdTokenResponse(t,i,s);return n||await t._updateCurrentUser(o.user),o}async function signInWithCredential(e,t){return _signInWithCredential(_castAuth(e),t)}async function linkWithCredential(e,t){const r=getModularInstance(e);return await _assertLinkedStatus(!1,r,t.providerId),_link$1(r,t)}async function reauthenticateWithCredential(e,t){return _reauthenticate(getModularInstance(e),t)}async function signInWithCustomToken(t,r){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const n=_castAuth(t),i=await async function signInWithCustomToken$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithCustomToken",_addTidIfNecessary(e,t))}(n,{token:r,returnSecureToken:!0}),s=await UserCredentialImpl._fromIdTokenResponse(n,"signIn",i);return await n._updateCurrentUser(s.user),s}class MultiFactorInfoImpl{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?PhoneMultiFactorInfoImpl._fromServerResponse(e,t):"totpInfo"in t?TotpMultiFactorInfoImpl._fromServerResponse(e,t):_fail(e,"internal-error")}}class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new PhoneMultiFactorInfoImpl(t)}}class TotpMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new TotpMultiFactorInfoImpl(t)}}function _setActionCodeSettingsOnRequest(e,t,r){_assert(r.url?.length>0,e,"invalid-continue-uri"),_assert(void 0===r.dynamicLinkDomain||r.dynamicLinkDomain.length>0,e,"invalid-dynamic-link-domain"),_assert(void 0===r.linkDomain||r.linkDomain.length>0,e,"invalid-hosting-link-domain"),t.continueUrl=r.url,t.dynamicLinkDomain=r.dynamicLinkDomain,t.linkDomain=r.linkDomain,t.canHandleCodeInApp=r.handleCodeInApp,r.iOS&&(_assert(r.iOS.bundleId.length>0,e,"missing-ios-bundle-id"),t.iOSBundleId=r.iOS.bundleId),r.android&&(_assert(r.android.packageName.length>0,e,"missing-android-pkg-name"),t.androidInstallApp=r.android.installApp,t.androidMinimumVersionCode=r.android.minimumVersion,t.androidPackageName=r.android.packageName)}async function recachePasswordPolicy(e){const t=_castAuth(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function sendPasswordResetEmail(e,t,r){const n=_castAuth(e),i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};r&&_setActionCodeSettingsOnRequest(n,i,r),await handleRecaptchaFlow(n,i,"getOobCode",sendPasswordResetEmail$1,"EMAIL_PASSWORD_PROVIDER")}async function confirmPasswordReset(e,t,r){await resetPassword(getModularInstance(e),{oobCode:t,newPassword:r}).catch((async t=>{throw"auth/password-does-not-meet-requirements"===t.code&&recachePasswordPolicy(e),t}))}async function applyActionCode(e,t){await async function applyActionCode$1(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",_addTidIfNecessary(e,t))}(getModularInstance(e),{oobCode:t})}async function checkActionCode(e,t){const r=getModularInstance(e),n=await resetPassword(r,{oobCode:t}),i=n.requestType;switch(_assert(i,r,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":_assert(n.newEmail,r,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":_assert(n.mfaInfo,r,"internal-error");default:_assert(n.email,r,"internal-error")}let s=null;return n.mfaInfo&&(s=MultiFactorInfoImpl._fromServerResponse(_castAuth(r),n.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===n.requestType?n.newEmail:n.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===n.requestType?n.email:n.newEmail)||null,multiFactorInfo:s},operation:i}}async function verifyPasswordResetCode(e,t){const{data:r}=await checkActionCode(getModularInstance(e),t);return r.email}async function createUserWithEmailAndPassword(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t),s=handleRecaptchaFlow(i,{returnSecureToken:!0,email:r,password:n,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",signUp,"EMAIL_PASSWORD_PROVIDER"),o=await s.catch((e=>{throw"auth/password-does-not-meet-requirements"===e.code&&recachePasswordPolicy(t),e})),a=await UserCredentialImpl._fromIdTokenResponse(i,"signIn",o);return await i._updateCurrentUser(a.user),a}function signInWithEmailAndPassword(t,r,n){return e(t.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t)):signInWithCredential(getModularInstance(t),EmailAuthProvider.credential(r,n)).catch((async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&recachePasswordPolicy(t),e}))}async function sendSignInLinkToEmail(e,t,r){const n=_castAuth(e),i={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};!function setActionCodeSettings(e,t){_assert(t.handleCodeInApp,n,"argument-error"),t&&_setActionCodeSettingsOnRequest(n,e,t)}(i,r),await handleRecaptchaFlow(n,i,"getOobCode",sendSignInLinkToEmail$1,"EMAIL_PASSWORD_PROVIDER")}function isSignInWithEmailLink(e,t){const r=ActionCodeURL.parseLink(t);return"EMAIL_SIGNIN"===r?.operation}async function signInWithEmailLink(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=getModularInstance(t),s=EmailAuthProvider.credentialWithLink(r,n||_getCurrentUrl());return _assert(s._tenantId===(i.tenantId||null),i,"tenant-id-mismatch"),signInWithCredential(i,s)}async function fetchSignInMethodsForEmail(e,t){const r={identifier:t,continueUri:_isHttpOrHttps()?_getCurrentUrl():"http://localhost"},{signinMethods:n}=await async function createAuthUri(e,t){return _performApiRequest(e,"POST","/v1/accounts:createAuthUri",_addTidIfNecessary(e,t))}(getModularInstance(e),r);return n||[]}async function sendEmailVerification(e,t){const r=getModularInstance(e),n={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&_setActionCodeSettingsOnRequest(r.auth,n,t);const{email:i}=await async function sendEmailVerification$1(e,t){return sendOobCode(e,t)}(r.auth,n);i!==e.email&&await e.reload()}async function verifyBeforeUpdateEmail(e,t,r){const n=getModularInstance(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};r&&_setActionCodeSettingsOnRequest(n.auth,i,r);const{email:s}=await async function verifyAndChangeEmail(e,t){return sendOobCode(e,t)}(n.auth,i);s!==e.email&&await e.reload()}async function updateProfile(e,{displayName:t,photoURL:r}){if(void 0===t&&void 0===r)return;const n=getModularInstance(e),i={idToken:await n.getIdToken(),displayName:t,photoUrl:r,returnSecureToken:!0},s=await _logoutIfInvalidated(n,async function updateProfile$1(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}(n.auth,i));n.displayName=s.displayName||null,n.photoURL=s.photoUrl||null;const o=n.providerData.find((({providerId:e})=>"password"===e));o&&(o.displayName=n.displayName,o.photoURL=n.photoURL),await n._updateTokensIfNecessary(s)}function updateEmail(t,r){const n=getModularInstance(t);return e(n.auth.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth)):updateEmailOrPassword(n,r,null)}function updatePassword(e,t){return updateEmailOrPassword(getModularInstance(e),null,t)}async function updateEmailOrPassword(e,t,r){const{auth:n}=e,i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),r&&(i.password=r);const s=await _logoutIfInvalidated(e,async function updateEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}(n,i));await e._updateTokensIfNecessary(s,!0)}class GenericAdditionalUserInfo{constructor(e,t,r={}){this.isNewUser=e,this.providerId=t,this.profile=r}}class FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo{constructor(e,t,r,n){super(e,t,r),this.username=n}}class FacebookAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,"facebook.com",t)}}class GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t){super(e,"github.com",t,"string"==typeof t?.login?t?.login:null)}}class GoogleAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,"google.com",t)}}class TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t,r){super(e,"twitter.com",t,r)}}function getAdditionalUserInfo(e){const{user:t,_tokenResponse:r}=e;return t.isAnonymous&&!r?{providerId:null,isNewUser:!1,profile:null}:function _fromIdTokenResponse(e){if(!e)return null;const{providerId:t}=e,r=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},n=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!t&&e?.idToken){const t=_parseToken(e.idToken)?.firebase?.sign_in_provider;if(t)return new GenericAdditionalUserInfo(n,"anonymous"!==t&&"custom"!==t?t:null)}if(!t)return null;switch(t){case"facebook.com":return new FacebookAdditionalUserInfo(n,r);case"github.com":return new GithubAdditionalUserInfo(n,r);case"google.com":return new GoogleAdditionalUserInfo(n,r);case"twitter.com":return new TwitterAdditionalUserInfo(n,r,e.screenName||null);case"custom":case"anonymous":return new GenericAdditionalUserInfo(n,null);default:return new GenericAdditionalUserInfo(n,t,r)}}(r)}function setPersistence(e,t){return getModularInstance(e).setPersistence(t)}function initializeRecaptchaConfig(e){return _initializeRecaptchaConfig(e)}async function validatePassword(e,t){return _castAuth(e).validatePassword(t)}function onIdTokenChanged(e,t,r,n){return getModularInstance(e).onIdTokenChanged(t,r,n)}function beforeAuthStateChanged(e,t,r){return getModularInstance(e).beforeAuthStateChanged(t,r)}function onAuthStateChanged(e,t,r,n){return getModularInstance(e).onAuthStateChanged(t,r,n)}function useDeviceLanguage(e){getModularInstance(e).useDeviceLanguage()}function updateCurrentUser(e,t){return getModularInstance(e).updateCurrentUser(t)}function signOut(e){return getModularInstance(e).signOut()}function revokeAccessToken(e,t){return _castAuth(e).revokeAccessToken(t)}async function deleteUser(e){return getModularInstance(e).delete()}class MultiFactorSessionImpl{constructor(e,t,r){this.type=e,this.credential=t,this.user=r}static _fromIdtoken(e,t){return new MultiFactorSessionImpl("enroll",e,t)}static _fromMfaPendingCredential(e){return new MultiFactorSessionImpl("signin",e)}toJSON(){const e="enroll"===this.type?"idToken":"pendingCredential";return{multiFactorSession:{[e]:this.credential}}}static fromJSON(e){if(e?.multiFactorSession){if(e.multiFactorSession?.pendingCredential)return MultiFactorSessionImpl._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(e.multiFactorSession?.idToken)return MultiFactorSessionImpl._fromIdtoken(e.multiFactorSession.idToken)}return null}}class MultiFactorResolverImpl{constructor(e,t,r){this.session=e,this.hints=t,this.signInResolver=r}static _fromError(e,t){const r=_castAuth(e),n=t.customData._serverResponse,i=(n.mfaInfo||[]).map((e=>MultiFactorInfoImpl._fromServerResponse(r,e)));_assert(n.mfaPendingCredential,r,"internal-error");const s=MultiFactorSessionImpl._fromMfaPendingCredential(n.mfaPendingCredential);return new MultiFactorResolverImpl(s,i,(async e=>{const i=await e._process(r,s);delete n.mfaInfo,delete n.mfaPendingCredential;const o={...n,idToken:i.idToken,refreshToken:i.refreshToken};switch(t.operationType){case"signIn":const e=await UserCredentialImpl._fromIdTokenResponse(r,t.operationType,o);return await r._updateCurrentUser(e.user),e;case"reauthenticate":return _assert(t.user,r,"internal-error"),UserCredentialImpl._forOperation(t.user,t.operationType,o);default:_fail(r,"internal-error")}}))}async resolveSignIn(e){const t=e;return this.signInResolver(t)}}function getMultiFactorResolver(e,t){const r=getModularInstance(e),n=t;return _assert(t.customData.operationType,r,"argument-error"),_assert(n.customData._serverResponse?.mfaPendingCredential,r,"argument-error"),MultiFactorResolverImpl._fromError(r,n)}function startEnrollPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:start",_addTidIfNecessary(e,t))}class MultiFactorUserImpl{constructor(e){this.user=e,this.enrolledFactors=[],e._onReload((t=>{t.mfaInfo&&(this.enrolledFactors=t.mfaInfo.map((t=>MultiFactorInfoImpl._fromServerResponse(e.auth,t))))}))}static _fromUser(e){return new MultiFactorUserImpl(e)}async getSession(){return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){const r=e,n=await this.getSession(),i=await _logoutIfInvalidated(this.user,r._process(this.user.auth,n,t));return await this.user._updateTokensIfNecessary(i),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid,r=await this.user.getIdToken();try{const e=await _logoutIfInvalidated(this.user,function withdrawMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:withdraw",_addTidIfNecessary(e,t))}(this.user.auth,{idToken:r,mfaEnrollmentId:t}));this.enrolledFactors=this.enrolledFactors.filter((({uid:e})=>e!==t)),await this.user._updateTokensIfNecessary(e),await this.user.reload()}catch(e){throw e}}}const N=new WeakMap;function multiFactor(e){const t=getModularInstance(e);return N.has(t)||N.set(t,MultiFactorUserImpl._fromUser(t)),N.get(t)}const O="__sak";class BrowserPersistenceClass{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(O,"1"),this.storage.removeItem(O),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class BrowserLocalPersistence extends BrowserPersistenceClass{constructor(){super((()=>window.localStorage),"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=_isMobileBrowser(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const r=this.storage.getItem(t),n=this.localCache[t];r!==n&&e(t,n,r)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys(((e,t,r)=>{this.notifyListeners(e,r)}));const r=e.key;t?this.detachListener():this.stopPolling();const triggerListeners=()=>{const e=this.storage.getItem(r);(t||this.localCache[r]!==e)&&this.notifyListeners(r,e)},n=this.storage.getItem(r);_isIE10()&&n!==e.newValue&&e.newValue!==e.oldValue?setTimeout(triggerListeners,10):triggerListeners()}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const e of Array.from(r))e(t?JSON.parse(t):t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:r}),!0)}))}),1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}BrowserLocalPersistence.type="LOCAL";const D=BrowserLocalPersistence;function getDocumentCookie(e){const t=e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),r=RegExp(`${t}=([^;]+)`);return document.cookie.match(r)?.[1]??null}function getCookieName(e){return`${"http:"===window.location.protocol?"__dev_":"__HOST-"}FIREBASE_${e.split(":")[3]}`}class CookiePersistence{constructor(){this.type="COOKIE",this.listenerUnsubscribes=new Map}_getFinalTarget(e){if(void 0===typeof window)return e;const t=new URL(`${window.location.origin}/__cookies__`);return t.searchParams.set("finalTarget",e),t}async _isAvailable(){return!("boolean"==typeof isSecureContext&&!isSecureContext)&&("undefined"!=typeof navigator&&"undefined"!=typeof document&&(navigator.cookieEnabled??!0))}async _set(e,t){}async _get(e){if(!this._isAvailable())return null;const t=getCookieName(e);if(window.cookieStore){const e=await window.cookieStore.get(t);return e?.value}return getDocumentCookie(t)}async _remove(e){if(!this._isAvailable())return;if(!await this._get(e))return;const t=getCookieName(e);document.cookie=`${t}=;Max-Age=34560000;Partitioned;Secure;SameSite=Strict;Path=/;Priority=High`,await fetch("/__cookies__",{method:"DELETE"}).catch((()=>{}))}_addListener(e,t){if(!this._isAvailable())return;const r=getCookieName(e);if(window.cookieStore){const cb=e=>{const n=e.changed.find((e=>e.name===r));n&&t(n.value);e.deleted.find((e=>e.name===r))&&t(null)},unsubscribe=()=>window.cookieStore.removeEventListener("change",cb);return this.listenerUnsubscribes.set(t,unsubscribe),window.cookieStore.addEventListener("change",cb)}let n=getDocumentCookie(r);const i=setInterval((()=>{const e=getDocumentCookie(r);e!==n&&(t(e),n=e)}),1e3);this.listenerUnsubscribes.set(t,(()=>clearInterval(i)))}_removeListener(e,t){const r=this.listenerUnsubscribes.get(t);r&&(r(),this.listenerUnsubscribes.delete(t))}}CookiePersistence.type="COOKIE";const L=CookiePersistence;class BrowserSessionPersistence extends BrowserPersistenceClass{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){}_removeListener(e,t){}}BrowserSessionPersistence.type="SESSION";const M=BrowserSessionPersistence;class Receiver{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t)return t;const r=new Receiver(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:r,eventType:n,data:i}=t.data,s=this.handlersMap[n];if(!s?.size)return;t.ports[0].postMessage({status:"ack",eventId:r,eventType:n});const o=Array.from(s).map((async e=>e(t.origin,i))),a=await function _allSettled(e){return Promise.all(e.map((async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})))}(o);t.ports[0].postMessage({status:"done",eventId:r,eventType:n,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function _generateEventId(e="",t=10){let r="";for(let e=0;e<t;e++)r+=Math.floor(10*Math.random());return e+r}Receiver.receivers=[];class Sender{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,r=50){const n="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!n)throw new Error("connection_unavailable");let i,s;return new Promise(((o,a)=>{const c=_generateEventId("",20);n.port1.start();const u=setTimeout((()=>{a(new Error("unsupported_event"))}),r);s={messageChannel:n,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(u),i=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(i),o(t.data.response);break;default:clearTimeout(u),clearTimeout(i),a(new Error("invalid_response"))}}},this.handlers.add(s),n.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[n.port2])})).finally((()=>{s&&this.removeMessageHandler(s)}))}}function _window(){return window}function _isWorker(){return void 0!==_window().WorkerGlobalScope&&"function"==typeof _window().importScripts}const U="firebaseLocalStorageDb",F="firebaseLocalStorage",V="fbase_key";class DBPromise{constructor(e){this.request=e}toPromise(){return new Promise(((e,t)=>{this.request.addEventListener("success",(()=>{e(this.request.result)})),this.request.addEventListener("error",(()=>{t(this.request.error)}))}))}}function getObjectStore(e,t){return e.transaction([F],t?"readwrite":"readonly").objectStore(F)}function _openDatabase(){const e=indexedDB.open(U,1);return new Promise(((t,r)=>{e.addEventListener("error",(()=>{r(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(F,{keyPath:V})}catch(e){r(e)}})),e.addEventListener("success",(async()=>{const r=e.result;r.objectStoreNames.contains(F)?t(r):(r.close(),await function _deleteDatabase(){const e=indexedDB.deleteDatabase(U);return new DBPromise(e).toPromise()}(),t(await _openDatabase()))}))}))}async function _putObject(e,t,r){const n=getObjectStore(e,!0).put({[V]:t,value:r});return new DBPromise(n).toPromise()}function _deleteObject(e,t){const r=getObjectStore(e,!0).delete(t);return new DBPromise(r).toPromise()}class IndexedDBLocalPersistence{constructor(){this.type="LOCAL",this.dbPromise=null,this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then((()=>{}),(()=>{}))}async _openDb(){return this.dbPromise||(this.dbPromise=_openDatabase(),this.dbPromise.catch((()=>{this.dbPromise=null}))),this.dbPromise}async _withRetries(e){let t=0;for(;;)try{const t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;if(this.dbPromise){(await this.dbPromise).close(),this.dbPromise=null}}}async initializeServiceWorkerMessaging(){return _isWorker()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Receiver._getInstance(function _getWorkerGlobalScope(){return _isWorker()?self:null}()),this.receiver._subscribe("keyChanged",(async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)}))),this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){if(this.activeServiceWorker=await async function _getActiveServiceWorker(){if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}(),!this.activeServiceWorker)return;this.sender=new Sender(this.activeServiceWorker);const e=await this.sender._send("ping",{},800);e&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&function _getServiceWorkerController(){return navigator?.serviceWorker?.controller||null}()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{return!!indexedDB&&(await this._withRetries((async e=>{await _putObject(e,O,"1"),await _deleteObject(e,O)})),!0)}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>(await this._withRetries((r=>_putObject(r,e,t))),this.localCache[e]=t,this.notifyServiceWorker(e))))}async _get(e){const t=await this._withRetries((t=>async function getObject(e,t){const r=getObjectStore(e,!1).get(t),n=await new DBPromise(r).toPromise();return void 0===n?null:n.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>_deleteObject(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=getObjectStore(e,!1).getAll();return new DBPromise(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],r=new Set;if(0!==e.length)for(const{fbase_key:n,value:i}of e)r.add(n),JSON.stringify(this.localCache[n])!==JSON.stringify(i)&&(this.notifyListeners(n,i),t.push(n));for(const e of Object.keys(this.localCache))this.localCache[e]&&!r.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const e of Array.from(r))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}IndexedDBLocalPersistence.type="LOCAL";const W=IndexedDBLocalPersistence;function startSignInPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:start",_addTidIfNecessary(e,t))}const x=_generateCallbackName("rcb"),H=new Delay(3e4,6e4);class ReCaptchaLoaderImpl{constructor(){this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!_window().grecaptcha?.render}load(e,t=""){return _assert(function isHostLanguageValid(e){return e.length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e)}(t),e,"argument-error"),this.shouldResolveImmediately(t)&&isV2(_window().grecaptcha)?Promise.resolve(_window().grecaptcha):new Promise(((r,n)=>{const i=_window().setTimeout((()=>{n(_createError(e,"network-request-failed"))}),H.get());_window()[x]=()=>{_window().clearTimeout(i),delete _window()[x];const s=_window().grecaptcha;if(!s||!isV2(s))return void n(_createError(e,"internal-error"));const o=s.render;s.render=(e,t)=>{const r=o(e,t);return this.counter++,r},this.hostLanguage=t,r(s)};_loadJS(`${function _recaptchaV2ScriptUrl(){return P.recaptchaV2Script}()}?${querystring({onload:x,render:"explicit",hl:t})}`).catch((()=>{clearTimeout(i),n(_createError(e,"internal-error"))}))}))}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!_window().grecaptcha?.render&&(e===this.hostLanguage||this.counter>0||this.librarySeparatelyLoaded)}}class MockReCaptchaLoaderImpl{async load(e){return new MockReCaptcha(e)}clearedOneInstance(){}}const q="recaptcha",j={theme:"light",type:"image"};class RecaptchaVerifier{constructor(e,t,r={...j}){this.parameters=r,this.type=q,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=_castAuth(e),this.isInvisible="invisible"===this.parameters.size,_assert("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");const n="string"==typeof t?document.getElementById(t):t;_assert(n,this.auth,"argument-error"),this.container=n,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=this.auth.settings.appVerificationDisabledForTesting?new MockReCaptchaLoaderImpl:new ReCaptchaLoaderImpl,this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),t=this.getAssertedRecaptcha(),r=t.getResponse(e);return r||new Promise((r=>{const tokenChange=e=>{e&&(this.tokenChangeListeners.delete(tokenChange),r(e))};this.tokenChangeListeners.add(tokenChange),this.isInvisible&&t.execute(e)}))}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch((e=>{throw this.renderPromise=null,e}))),this.renderPromise}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach((e=>{this.container.removeChild(e)}))}validateStartingState(){_assert(!this.parameters.sitekey,this.auth,"argument-error"),_assert(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),_assert("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(e){return t=>{if(this.tokenChangeListeners.forEach((e=>e(t))),"function"==typeof e)e(t);else if("string"==typeof e){const r=_window()[e];"function"==typeof r&&r(t)}}}assertNotDestroyed(){_assert(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;if(!this.isInvisible){const t=document.createElement("div");e.appendChild(t),e=t}this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){_assert(_isHttpOrHttps()&&!_isWorker(),this.auth,"internal-error"),await function domReady(){let e=null;return new Promise((t=>{"complete"!==document.readyState?(e=()=>t(),window.addEventListener("load",e)):t()})).catch((t=>{throw e&&window.removeEventListener("load",e),t}))}(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);const e=await async function getRecaptchaParams(e){return(await _performApiRequest(e,"GET","/v1/recaptchaParams")).recaptchaSiteKey||""}(this.auth);_assert(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return _assert(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class ConfirmationResultImpl{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){const t=PhoneAuthCredential._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function signInWithPhoneNumber(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t),s=await _verifyPhoneNumber(i,r,getModularInstance(n));return new ConfirmationResultImpl(s,(e=>signInWithCredential(i,e)))}async function linkWithPhoneNumber(e,t,r){const n=getModularInstance(e);await _assertLinkedStatus(!1,n,"phone");const i=await _verifyPhoneNumber(n.auth,t,getModularInstance(r));return new ConfirmationResultImpl(i,(e=>linkWithCredential(n,e)))}async function reauthenticateWithPhoneNumber(t,r,n){const i=getModularInstance(t);if(e(i.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i.auth));const s=await _verifyPhoneNumber(i.auth,r,getModularInstance(n));return new ConfirmationResultImpl(s,(e=>reauthenticateWithCredential(i,e)))}async function _verifyPhoneNumber(e,t,r){if(!e._getRecaptchaConfig())try{await _initializeRecaptchaConfig(e)}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}try{let n;if(n="string"==typeof t?{phoneNumber:t}:t,"session"in n){const t=n.session;if("phoneNumber"in n){_assert("enroll"===t.type,e,"internal-error");const i={idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:n.phoneNumber,clientType:"CLIENT_TYPE_WEB"}},s=handleRecaptchaFlow(e,i,"mfaSmsEnrollment",(async(e,t)=>{if(t.phoneEnrollmentInfo.captchaResponse===k){_assert(r?.type===q,e,"argument-error");return startEnrollPhoneMfa(e,await injectRecaptchaV2Token(e,t,r))}return startEnrollPhoneMfa(e,t)}),"PHONE_PROVIDER");return(await s.catch((e=>Promise.reject(e)))).phoneSessionInfo.sessionInfo}{_assert("signin"===t.type,e,"internal-error");const i=n.multiFactorHint?.uid||n.multiFactorUid;_assert(i,e,"missing-multi-factor-info");const s={mfaPendingCredential:t.credential,mfaEnrollmentId:i,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}},o=handleRecaptchaFlow(e,s,"mfaSmsSignIn",(async(e,t)=>{if(t.phoneSignInInfo.captchaResponse===k){_assert(r?.type===q,e,"argument-error");return startSignInPhoneMfa(e,await injectRecaptchaV2Token(e,t,r))}return startSignInPhoneMfa(e,t)}),"PHONE_PROVIDER");return(await o.catch((e=>Promise.reject(e)))).phoneResponseInfo.sessionInfo}}{const t={phoneNumber:n.phoneNumber,clientType:"CLIENT_TYPE_WEB"},i=handleRecaptchaFlow(e,t,"sendVerificationCode",(async(e,t)=>{if(t.captchaResponse===k){_assert(r?.type===q,e,"argument-error");return sendPhoneVerificationCode(e,await injectRecaptchaV2Token(e,t,r))}return sendPhoneVerificationCode(e,t)}),"PHONE_PROVIDER");return(await i.catch((e=>Promise.reject(e)))).sessionInfo}}finally{r?._reset()}}async function updatePhoneNumber(t,r){const n=getModularInstance(t);if(e(n.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth));await _link$1(n,r)}async function injectRecaptchaV2Token(e,t,r){_assert(r.type===q,e,"argument-error");const n=await r.verify();_assert("string"==typeof n,e,"argument-error");const i={...t};if("phoneEnrollmentInfo"in i){const e=i.phoneEnrollmentInfo.phoneNumber,t=i.phoneEnrollmentInfo.captchaResponse,r=i.phoneEnrollmentInfo.clientType,s=i.phoneEnrollmentInfo.recaptchaVersion;return Object.assign(i,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:n,captchaResponse:t,clientType:r,recaptchaVersion:s}}),i}if("phoneSignInInfo"in i){const e=i.phoneSignInInfo.captchaResponse,t=i.phoneSignInInfo.clientType,r=i.phoneSignInInfo.recaptchaVersion;return Object.assign(i,{phoneSignInInfo:{recaptchaToken:n,captchaResponse:e,clientType:t,recaptchaVersion:r}}),i}return Object.assign(i,{recaptchaToken:n}),i}class PhoneAuthProvider{constructor(e){this.providerId=PhoneAuthProvider.PROVIDER_ID,this.auth=_castAuth(e)}verifyPhoneNumber(e,t){return _verifyPhoneNumber(this.auth,e,getModularInstance(t))}static credential(e,t){return PhoneAuthCredential._fromVerification(e,t)}static credentialFromResult(e){const t=e;return PhoneAuthProvider.credentialFromTaggedObject(t)}static credentialFromError(e){return PhoneAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:r}=e;return t&&r?PhoneAuthCredential._fromTokenResponse(t,r):null}}function _withDefaultResolver(e,t){return t?_getInstance(t):(_assert(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}PhoneAuthProvider.PROVIDER_ID="phone",PhoneAuthProvider.PHONE_SIGN_IN_METHOD="phone";class IdpCredential extends AuthCredential{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return signInWithIdp(e,this._buildIdpRequest())}_linkToIdToken(e,t){return signInWithIdp(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return signInWithIdp(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function _signIn(e){return _signInWithCredential(e.auth,new IdpCredential(e),e.bypassAuthState)}function _reauth(e){const{auth:t,user:r}=e;return _assert(r,t,"internal-error"),_reauthenticate(r,new IdpCredential(e),e.bypassAuthState)}async function _link(e){const{auth:t,user:r}=e;return _assert(r,t,"internal-error"),_link$1(r,new IdpCredential(e),e.bypassAuthState)}class AbstractPopupRedirectOperation{constructor(e,t,r,n,i=!1){this.auth=e,this.resolver=r,this.user=n,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:r,postBody:n,tenantId:i,error:s,type:o}=e;if(s)return void this.reject(s);const a={auth:this.auth,requestUri:t,sessionId:r,tenantId:i||void 0,postBody:n||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return _signIn;case"linkViaPopup":case"linkViaRedirect":return _link;case"reauthViaPopup":case"reauthViaRedirect":return _reauth;default:_fail(this.auth,"internal-error")}}resolve(e){debugAssert(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){debugAssert(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const G=new Delay(2e3,1e4);async function signInWithPopup(t,r,n){if(e(t.app))return Promise.reject(_createError(t,"operation-not-supported-in-this-environment"));const i=_castAuth(t);_assertInstanceOf(t,r,FederatedAuthProvider);const s=_withDefaultResolver(i,n);return new PopupOperation(i,"signInViaPopup",r,s).executeNotNull()}async function reauthenticateWithPopup(t,r,n){const i=getModularInstance(t);if(e(i.auth.app))return Promise.reject(_createError(i.auth,"operation-not-supported-in-this-environment"));_assertInstanceOf(i.auth,r,FederatedAuthProvider);const s=_withDefaultResolver(i.auth,n);return new PopupOperation(i.auth,"reauthViaPopup",r,s,i).executeNotNull()}async function linkWithPopup(e,t,r){const n=getModularInstance(e);_assertInstanceOf(n.auth,t,FederatedAuthProvider);const i=_withDefaultResolver(n.auth,r);return new PopupOperation(n.auth,"linkViaPopup",t,i,n).executeNotNull()}class PopupOperation extends AbstractPopupRedirectOperation{constructor(e,t,r,n,i){super(e,t,n,i),this.provider=r,this.authWindow=null,this.pollId=null,PopupOperation.currentPopupAction&&PopupOperation.currentPopupAction.cancel(),PopupOperation.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return _assert(e,this.auth,"internal-error"),e}async onExecution(){debugAssert(1===this.filter.length,"Popup operations only handle one event");const e=_generateEventId();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch((e=>{this.reject(e)})),this.resolver._isIframeWebStorageSupported(this.auth,(e=>{e||this.reject(_createError(this.auth,"web-storage-unsupported"))})),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(_createError(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,PopupOperation.currentPopupAction=null}pollUserCancellation(){const poll=()=>{this.authWindow?.window?.closed?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(_createError(this.auth,"popup-closed-by-user"))}),8e3):this.pollId=window.setTimeout(poll,G.get())};poll()}}PopupOperation.currentPopupAction=null;const B=new Map;class RedirectAction extends AbstractPopupRedirectOperation{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let e=B.get(this.auth._key());if(!e){try{const t=await async function _getAndClearPendingRedirectStatus(e,t){const r=pendingRedirectKey(t),n=resolverPersistence(e);if(!await n._isAvailable())return!1;const i="true"===await n._get(r);return await n._remove(r),i}(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}B.set(this.auth._key(),e)}return this.bypassAuthState||B.set(this.auth._key(),(()=>Promise.resolve(null))),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function _setPendingRedirectStatus(e,t){return resolverPersistence(e)._set(pendingRedirectKey(t),"true")}function _overrideRedirectResult(e,t){B.set(e._key(),t)}function resolverPersistence(e){return _getInstance(e._redirectPersistence)}function pendingRedirectKey(e){return _persistenceKeyName("pendingRedirect",e.config.apiKey,e.name)}function signInWithRedirect(t,r,n){return async function _signInWithRedirect(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t);_assertInstanceOf(t,r,FederatedAuthProvider),await i._initializationPromise;const s=_withDefaultResolver(i,n);return await _setPendingRedirectStatus(s,i),s._openRedirect(i,r,"signInViaRedirect")}(t,r,n)}function reauthenticateWithRedirect(t,r,n){return async function _reauthenticateWithRedirect(t,r,n){const i=getModularInstance(t);if(_assertInstanceOf(i.auth,r,FederatedAuthProvider),e(i.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i.auth));await i.auth._initializationPromise;const s=_withDefaultResolver(i.auth,n);await _setPendingRedirectStatus(s,i.auth);const o=await prepareUserForRedirect(i);return s._openRedirect(i.auth,r,"reauthViaRedirect",o)}(t,r,n)}function linkWithRedirect(e,t,r){return async function _linkWithRedirect(e,t,r){const n=getModularInstance(e);_assertInstanceOf(n.auth,t,FederatedAuthProvider),await n.auth._initializationPromise;const i=_withDefaultResolver(n.auth,r);await _assertLinkedStatus(!1,n,t.providerId),await _setPendingRedirectStatus(i,n.auth);const s=await prepareUserForRedirect(n);return i._openRedirect(n.auth,t,"linkViaRedirect",s)}(e,t,r)}async function getRedirectResult(e,t){return await _castAuth(e)._initializationPromise,_getRedirectResult(e,t,!1)}async function _getRedirectResult(t,r,n=!1){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t),s=_withDefaultResolver(i,r),o=new RedirectAction(i,s,n),a=await o.execute();return a&&!n&&(delete a.user._redirectEventId,await i._persistUserIfCurrent(a.user),await i._setRedirectUser(null,r)),a}async function prepareUserForRedirect(e){const t=_generateEventId(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class AuthEventManager{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach((r=>{this.isEventForConsumer(e,r)&&(t=!0,this.sendToConsumer(e,r),this.saveEventToCache(e))})),this.hasHandledPotentialRedirect||!function isRedirectEvent(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return isNullRedirectEvent(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){if(e.error&&!isNullRedirectEvent(e)){const r=e.error.code?.split("auth/")[1]||"internal-error";t.onError(_createError(this.auth,r))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const r=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(eventUid(e))}saveEventToCache(e){this.cachedEventUids.add(eventUid(e)),this.lastProcessedEventTime=Date.now()}}function eventUid(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function isNullRedirectEvent({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===t?.code}const z=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,K=/^https?/;async function _validateOrigin(e){if(e.config.emulator)return;const{authorizedDomains:t}=await async function _getProjectConfig(e,t={}){return _performApiRequest(e,"GET","/v1/projects",t)}(e);for(const e of t)try{if(matchDomain(e))return}catch{}_fail(e,"unauthorized-domain")}function matchDomain(e){const t=_getCurrentUrl(),{protocol:r,hostname:n}=new URL(t);if(e.startsWith("chrome-extension://")){const i=new URL(e);return""===i.hostname&&""===n?"chrome-extension:"===r&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===r&&i.hostname===n}if(!K.test(r))return!1;if(z.test(e))return n===e;const i=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+i+"|"+i+")$","i").test(n)}const $=new Delay(3e4,6e4);function resetUnloadedGapiModules(){const e=_window().___jsl;if(e?.H)for(const t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let t=0;t<e.CP.length;t++)e.CP[t]=null}function loadGapi(e){return new Promise(((t,r)=>{function loadGapiIframe(){resetUnloadedGapiModules(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{resetUnloadedGapiModules(),r(_createError(e,"network-request-failed"))},timeout:$.get()})}if(_window().gapi?.iframes?.Iframe)t(gapi.iframes.getContext());else{if(!_window().gapi?.load){const t=_generateCallbackName("iframefcb");return _window()[t]=()=>{gapi.load?loadGapiIframe():r(_createError(e,"network-request-failed"))},_loadJS(`${function _gapiScriptUrl(){return P.gapiScript}()}?onload=${t}`).catch((e=>r(e)))}loadGapiIframe()}})).catch((e=>{throw J=null,e}))}let J=null;const Y=new Delay(5e3,15e3),X={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Q=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function getIframeUrl(e){const t=e.config;_assert(t.authDomain,e,"auth-domain-config-required");const r=t.emulator?_emulatorUrl(t,"emulator/auth/iframe"):`https://${e.config.authDomain}/__/auth/iframe`,n={apiKey:t.apiKey,appName:e.name,v:i},s=Q.get(e.config.apiHost);s&&(n.eid=s);const o=e._getFrameworks();return o.length&&(n.fw=o.join(",")),`${r}?${querystring(n).slice(1)}`}async function _openIframe(e){const t=await function _loadGapi(e){return J=J||loadGapi(e),J}(e),r=_window().gapi;return _assert(r,e,"internal-error"),t.open({where:document.body,url:getIframeUrl(e),messageHandlersFilter:r.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:X,dontclear:!0},(t=>new Promise((async(r,n)=>{await t.restyle({setHideOnLeave:!1});const i=_createError(e,"network-request-failed"),s=_window().setTimeout((()=>{n(i)}),Y.get());function clearTimerAndResolve(){_window().clearTimeout(s),r(t)}t.ping(clearTimerAndResolve).then(clearTimerAndResolve,(()=>{n(i)}))}))))}const Z={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class AuthPopup{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function _open(e,t,r,n=500,i=600){const s=Math.max((window.screen.availHeight-i)/2,0).toString(),o=Math.max((window.screen.availWidth-n)/2,0).toString();let a="";const c={...Z,width:n.toString(),height:i.toString(),top:s,left:o},u=getUA().toLowerCase();r&&(a=_isChromeIOS(u)?"_blank":r),_isFirefox(u)&&(t=t||"http://localhost",c.scrollbars="yes");const d=Object.entries(c).reduce(((e,[t,r])=>`${e}${t}=${r},`),"");if(function _isIOSStandalone(e=getUA()){return _isIOS(e)&&!!window.navigator?.standalone}(u)&&"_self"!==a)return function openAsNewWindowIOS(e,t){const r=document.createElement("a");r.href=e,r.target=t;const n=document.createEvent("MouseEvent");n.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),r.dispatchEvent(n)}(t||"",a),new AuthPopup(null);const l=window.open(t||"",a,d);_assert(l,e,"popup-blocked");try{l.focus()}catch(e){}return new AuthPopup(l)}const ee="__/auth/handler",te="emulator/auth/handler",re=encodeURIComponent("fac");async function _getRedirectUrl(e,t,r,n,s,o){_assert(e.config.authDomain,e,"auth-domain-config-required"),_assert(e.config.apiKey,e,"invalid-api-key");const a={apiKey:e.config.apiKey,appName:e.name,authType:r,redirectUrl:n,v:i,eventId:s};if(t instanceof FederatedAuthProvider){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",function isEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(o||{}))a[e]=t}if(t instanceof BaseOAuthProvider){const e=t.getScopes().filter((e=>""!==e));e.length>0&&(a.scopes=e.join(","))}e.tenantId&&(a.tid=e.tenantId);const c=a;for(const e of Object.keys(c))void 0===c[e]&&delete c[e];const u=await e._getAppCheckToken(),d=u?`#${re}=${encodeURIComponent(u)}`:"";return`${function getHandlerBase({config:e}){if(!e.emulator)return`https://${e.authDomain}/${ee}`;return _emulatorUrl(e,te)}(e)}?${querystring(c).slice(1)}${d}`}const ne="webStorageSupport";const ie=class BrowserPopupRedirectResolver{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=M,this._completeRedirectFn=_getRedirectResult,this._overrideRedirectResult=_overrideRedirectResult}async _openPopup(e,t,r,n){debugAssert(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()");return _open(e,await _getRedirectUrl(e,t,r,_getCurrentUrl(),n),_generateEventId())}async _openRedirect(e,t,r,n){await this._originValidation(e);return function _setWindowLocation(e){_window().location.href=e}(await _getRedirectUrl(e,t,r,_getCurrentUrl(),n)),new Promise((()=>{}))}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:r}=this.eventManagers[t];return e?Promise.resolve(e):(debugAssert(r,"If manager is not set, promise should be"),r)}const r=this.initAndGetManager(e);return this.eventManagers[t]={promise:r},r.catch((()=>{delete this.eventManagers[t]})),r}async initAndGetManager(e){const t=await _openIframe(e),r=new AuthEventManager(e);return t.register("authEvent",(t=>{_assert(t?.authEvent,e,"invalid-auth-event");return{status:r.onEvent(t.authEvent)?"ACK":"ERROR"}}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:r},this.iframes[e._key()]=t,r}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(ne,{type:ne},(r=>{const n=r?.[0]?.[ne];void 0!==n&&t(!!n),_fail(e,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=_validateOrigin(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return _isMobileBrowser()||_isSafari()||_isIOS()}};class MultiFactorAssertionImpl{constructor(e){this.factorId=e}_process(e,t,r){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,r);case"signin":return this._finalizeSignIn(e,t.credential);default:return debugFail("unexpected MultiFactorSessionType")}}}class PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new PhoneMultiFactorAssertionImpl(e)}_finalizeEnroll(e,t,r){return function finalizeEnrollPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,t))}(e,{idToken:t,displayName:r,phoneVerificationInfo:this.credential._makeVerificationRequest()})}_finalizeSignIn(e,t){return function finalizeSignInPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,t))}(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()})}}class PhoneMultiFactorGenerator{constructor(){}static assertion(e){return PhoneMultiFactorAssertionImpl._fromCredential(e)}}PhoneMultiFactorGenerator.FACTOR_ID="phone";class TotpMultiFactorGenerator{static assertionForEnrollment(e,t){return TotpMultiFactorAssertionImpl._fromSecret(e,t)}static assertionForSignIn(e,t){return TotpMultiFactorAssertionImpl._fromEnrollmentId(e,t)}static async generateSecret(e){const t=e;_assert(void 0!==t.user?.auth,"internal-error");const r=await function startEnrollTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:start",_addTidIfNecessary(e,t))}(t.user.auth,{idToken:t.credential,totpEnrollmentInfo:{}});return TotpSecret._fromStartTotpMfaEnrollmentResponse(r,t.user.auth)}}TotpMultiFactorGenerator.FACTOR_ID="totp";class TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e,t,r){super("totp"),this.otp=e,this.enrollmentId=t,this.secret=r}static _fromSecret(e,t){return new TotpMultiFactorAssertionImpl(t,void 0,e)}static _fromEnrollmentId(e,t){return new TotpMultiFactorAssertionImpl(t,e)}async _finalizeEnroll(e,t,r){return _assert(void 0!==this.secret,e,"argument-error"),function finalizeEnrollTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,t))}(e,{idToken:t,displayName:r,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,t){_assert(void 0!==this.enrollmentId&&void 0!==this.otp,e,"argument-error");const r={verificationCode:this.otp};return function finalizeSignInTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,t))}(e,{mfaPendingCredential:t,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:r})}}class TotpSecret{constructor(e,t,r,n,i,s,o){this.sessionInfo=s,this.auth=o,this.secretKey=e,this.hashingAlgorithm=t,this.codeLength=r,this.codeIntervalSeconds=n,this.enrollmentCompletionDeadline=i}static _fromStartTotpMfaEnrollmentResponse(e,t){return new TotpSecret(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,t)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,t){let r=!1;return(_isEmptyString(e)||_isEmptyString(t))&&(r=!0),r&&(_isEmptyString(e)&&(e=this.auth.currentUser?.email||"unknownuser"),_isEmptyString(t)&&(t=this.auth.name)),`otpauth://totp/${t}:${e}?secret=${this.secretKey}&issuer=${t}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}}function _isEmptyString(e){return void 0===e||0===e?.length}var se="@firebase/auth",oe="1.13.3";class AuthInterop{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){if(this.assertAuthConfigured(),await this.auth._initializationPromise,!this.auth.currentUser)return null;return{accessToken:await this.auth.currentUser.getIdToken(e)}}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged((t=>{e(t?.stsTokenManager.accessToken||null)}));this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){_assert(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}const ae=getExperimentalSetting("authIdTokenMaxAge")||300;let ce=null;function getAuth(e=n()){const t=_getProvider(e,"auth");if(t.isInitialized())return t.getImmediate();const r=initializeAuth(e,{popupRedirectResolver:ie,persistence:[W,D,M]}),i=getExperimentalSetting("authTokenSyncURL");if(i&&"boolean"==typeof isSecureContext&&isSecureContext){const e=new URL(i,location.origin);if(location.origin===e.origin){const t=(s=e.toString(),async e=>{const t=e&&await e.getIdTokenResult(),r=t&&((new Date).getTime()-Date.parse(t.issuedAtTime))/1e3;if(r&&r>ae)return;const n=t?.token;ce!==n&&(ce=n,await fetch(s,{method:n?"POST":"DELETE",headers:n?{Authorization:`Bearer ${n}`}:{}}))});beforeAuthStateChanged(r,t,(()=>t(r.currentUser))),onIdTokenChanged(r,(e=>t(e)))}}var s;const o=(a="auth",getDefaults()?.emulatorHosts?.[a]);var a;return o&&connectAuthEmulator(r,`http://${o}`),r}!function _setExternalJSProvider(e){P=e}({loadJS:e=>new Promise(((t,r)=>{const n=document.createElement("script");n.setAttribute("src",e),n.onload=t,n.onerror=e=>{const t=_createError("internal-error");t.customData=e,r(t)},n.type="text/javascript",n.charset="UTF-8",function getScriptParentElement(){return document.getElementsByTagName("head")?.[0]??document}().appendChild(n)})),gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="}),function registerAuth(e){t(new Component("auth",((t,{options:r})=>{const n=t.getProvider("app").getImmediate(),i=t.getProvider("heartbeat"),s=t.getProvider("app-check-internal"),{apiKey:o,authDomain:a}=n.options;_assert(o&&!o.includes(":"),"invalid-api-key",{appName:n.name});const c={apiKey:o,authDomain:a,clientPlatform:e,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:_getClientVersion(e)},u=new AuthImpl(n,i,s,c);return function _initializeAuthInstance(e,t){const r=t?.persistence||[],n=(Array.isArray(r)?r:[r]).map(_getInstance);t?.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(n,t?.popupRedirectResolver)}(u,r),u}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,r)=>{e.getProvider("auth-internal").initialize()}))),t(new Component("auth-internal",(e=>(e=>new AuthInterop(e))(_castAuth(e.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),r(se,oe,function getVersionForPlatform(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}(e)),r(se,oe,"esm2020")}("Browser");export{m as ActionCodeOperation,ActionCodeURL,AuthCredential,v as AuthErrorCodes,EmailAuthCredential,EmailAuthProvider,FacebookAuthProvider,l as FactorId,GithubAuthProvider,GoogleAuthProvider,OAuthCredential,OAuthProvider,f as OperationType,PhoneAuthCredential,PhoneAuthProvider,PhoneMultiFactorGenerator,h as ProviderId,RecaptchaVerifier,SAMLAuthProvider,p as SignInMethod,TotpMultiFactorGenerator,TotpSecret,TwitterAuthProvider,applyActionCode,beforeAuthStateChanged,L as browserCookiePersistence,D as browserLocalPersistence,ie as browserPopupRedirectResolver,M as browserSessionPersistence,checkActionCode,confirmPasswordReset,connectAuthEmulator,createUserWithEmailAndPassword,g as debugErrorMap,deleteUser,fetchSignInMethodsForEmail,getAdditionalUserInfo,getAuth,getIdToken,getIdTokenResult,getMultiFactorResolver,getRedirectResult,S as inMemoryPersistence,W as indexedDBLocalPersistence,initializeAuth,initializeRecaptchaConfig,isSignInWithEmailLink,linkWithCredential,linkWithPhoneNumber,linkWithPopup,linkWithRedirect,multiFactor,onAuthStateChanged,onIdTokenChanged,parseActionCodeURL,_ as prodErrorMap,reauthenticateWithCredential,reauthenticateWithPhoneNumber,reauthenticateWithPopup,reauthenticateWithRedirect,reload,revokeAccessToken,sendEmailVerification,sendPasswordResetEmail,sendSignInLinkToEmail,setPersistence,signInAnonymously,signInWithCredential,signInWithCustomToken,signInWithEmailAndPassword,signInWithEmailLink,signInWithPhoneNumber,signInWithPopup,signInWithRedirect,signOut,unlink,updateCurrentUser,updateEmail,updatePassword,updatePhoneNumber,updateProfile,useDeviceLanguage,validatePassword,verifyBeforeUpdateEmail,verifyPasswordResetCode};
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import{_removeServiceInstance as e,getApp as t,_getProvider,_registerComponent as s,registerVersion as r,_isFirebaseServerApp as n,SDK_VERSION as i}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";class FirebaseError extends Error{constructor(e,t,s){super(t),this.code=e,this.customData=s,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,s){this.service=e,this.serviceName=t,this.errors=s}create(e,...t){const s=t[0]||{},r=`${this.service}/${e}`,n=this.errors[e],i=n?function replaceTemplate(e,t){return e.replace(o,((e,s)=>{const r=t[s];return null!=r?String(r):`<${s}?>`}))}(n,s):"Error",a=`${this.serviceName}: ${i} (${r}).`;return new FirebaseError(r,a,s)}}const o=/\{\$([^}]+)}/g;function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class Component{constructor(e,t,s){this.name=e,this.instanceFactory=t,this.type=s,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var a;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(a||(a={}));const c={debug:a.DEBUG,verbose:a.VERBOSE,info:a.INFO,warn:a.WARN,error:a.ERROR,silent:a.SILENT},h=a.INFO,u={[a.DEBUG]:"log",[a.VERBOSE]:"log",[a.INFO]:"info",[a.WARN]:"warn",[a.ERROR]:"error"},defaultLogHandler=(e,t,...s)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),n=u[t];if(!n)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[n](`[${r}] ${e.name}:`,...s)};const l="@firebase/data-connect",d="0.7.1";let p="";const g={OTHER:"other",ALREADY_INITIALIZED:"already-initialized",NOT_INITIALIZED:"not-initialized",NOT_SUPPORTED:"not-supported",INVALID_ARGUMENT:"invalid-argument",PARTIAL_ERROR:"partial-error",UNAUTHORIZED:"unauthorized"};class DataConnectError extends FirebaseError{constructor(e,t){super(e,t),this.name="DataConnectError",Object.setPrototypeOf(this,DataConnectError.prototype)}toString(){return`${this.name}[code=${this.code}]: ${this.message}`}}class DataConnectOperationError extends DataConnectError{constructor(e,t){super(g.PARTIAL_ERROR,e),this.name="DataConnectOperationError",this.response=t}}class EntityDataObject{getServerValue(e){return this.serverValues[e]}constructor(e){this.globalID=e,this.serverValues={},this.referencedFrom=new Set}getServerValues(){return this.serverValues}toJSON(){return{globalID:this.globalID,map:this.serverValues,referencedFrom:Array.from(this.referencedFrom)}}static fromJSON(e){const t=new EntityDataObject(e.globalID);return t.serverValues=e.map,t.referencedFrom=new Set(e.referencedFrom),t}updateServerValue(e,t,s){return this.serverValues[e]=t,this.referencedFrom.add(s),Array.from(this.referencedFrom)}}class InMemoryCacheProvider{constructor(e){this._keyId=e,this.edos=new Map,this.resultTrees=new Map}async setResultTree(e,t){this.resultTrees.set(e,t)}async getResultTree(e){return this.resultTrees.get(e)}async updateEntityData(e){this.edos.set(e.globalID,e)}async getEntityData(e){return this.edos.has(e)||this.edos.set(e,new EntityDataObject(e)),this.edos.get(e)}close(){return Promise.resolve()}}const m="_id";class EntityNode{constructor(){this.scalars={},this.references={},this.objectLists={},this.entityDataKeys=new Set}async loadData(e,t,s,r,n){if(void 0!==t){if("object"!=typeof t||Array.isArray(t))throw new DataConnectError(g.INVALID_ARGUMENT,"EntityNode initialized with non-object value");if(null!==t){"object"==typeof t&&s&&s[m]&&"string"==typeof s[m]&&(this.globalId=s[m],this.entityData=await n.getEntityData(this.globalId));for(const i in t)if(t.hasOwnProperty(i))if("object"==typeof t[i])if(Array.isArray(t[i])){const o=s&&s[i],a=[],c=[];for(const[s,h]of t[i].entries())if("object"==typeof h)if(Array.isArray(h));else{const t=new EntityNode;await t.loadData(e,h,o&&o[s],r,n),a.push(t)}else c.push(h);if(c.length>0&&a.length>0)this.scalars[i]=t[i];else if(c.length>0)if(this.entityData){const t=this.entityData.updateServerValue(i,c,e);this.entityDataKeys.add(i),r.add(t)}else this.scalars[i]=c;else a.length>0?this.objectLists[i]=a:this.scalars[i]=[]}else{if(null===t[i]){this.scalars[i]=null;continue}const o=new EntityNode;await o.loadData(e,t[i],s&&s[i],r,n),this.references[i]=o}else if(this.entityData){const s=this.entityData.updateServerValue(i,t[i],e);this.entityDataKeys.add(i),r.add(s)}else this.scalars[i]=t[i];this.entityData&&await n.updateEntityData(this.entityData)}}}toJSON(e){const t={};if(e===b.hydrated){if(this.entityData)for(const e of this.entityDataKeys)t[e]=this.entityData.getServerValue(e);if(this.scalars&&Object.assign(t,this.scalars),this.references)for(const s in this.references)this.references.hasOwnProperty(s)&&(t[s]=this.references[s].toJSON(e));if(this.objectLists)for(const s in this.objectLists)this.objectLists.hasOwnProperty(s)&&(t[s]=this.objectLists[s].map((t=>t.toJSON(e))));return t}if(this.entityData&&(t[m]=this.entityData.globalID),t._entity_data_keys=Array.from(this.entityDataKeys),this.scalars&&(t._scalars=this.scalars),this.references){const s={};for(const t in this.references)this.references.hasOwnProperty(t)&&(s[t]=this.references[t].toJSON(e));t._references=s}if(this.objectLists){const s={};for(const t in this.objectLists)this.objectLists.hasOwnProperty(t)&&(s[t]=this.objectLists[t].map((t=>t.toJSON(e))));t._objectLists=s}return t}static fromJson(e){const t=new EntityNode;if(e.backingData&&(t.entityData=EntityDataObject.fromJSON(e.backingData)),t.globalId=e.globalID,t.scalars=e.scalars,e.references){const s={};for(const t in e.references)e.references.hasOwnProperty(t)&&(s[t]=EntityNode.fromJson(e.references[t]));t.references=s}if(e.objectLists){const s={};for(const t in e.objectLists)e.objectLists.hasOwnProperty(t)&&(s[t]=e.objectLists[t].map((e=>EntityNode.fromJson(e))));t.objectLists=s}return t}}var b;!function(e){e[e.hydrated=0]="hydrated",e[e.dehydrated=1]="dehydrated"}(b||(b={}));class ResultTree{static fromJson(e){return new ResultTree(EntityNode.fromJson(e.rootStub),e.maxAge,e.cachedAt,e.lastAccessed)}constructor(e,t=0,s,r){this.rootStub=e,this.maxAge=t,this.cachedAt=s,this._lastAccessed=r}isStale(){return Date.now()-new Date(this.cachedAt.getTime()).getTime()>1e3*this.maxAge}updateMaxAge(e){this.maxAge=e}updateAccessed(){this._lastAccessed=new Date}get lastAccessed(){return this._lastAccessed}getRootStub(){return this.rootStub}}class ImpactedQueryRefsAccumulator{constructor(e){this.queryId=e,this.impacted=new Set}add(e){e.filter((e=>e!==this.queryId)).forEach((e=>this.impacted.add(e)))}consumeEvents(){const e=Array.from(this.impacted);return this.impacted.clear(),e}}class ResultTreeProcessor{hydrateResults(e){return e.toJSON(b.hydrated)}async dehydrateResults(e,t,s,r){const n=new ImpactedQueryRefsAccumulator(r),i=new EntityNode;return await i.loadData(r,e,t,n,s),{entityNode:i,impacted:n.consumeEvents()}}}class DataConnectCache{constructor(e,t,s,r,n){this.authProvider=e,this.projectId=t,this.connectorConfig=s,this.host=r,this.cacheSettings=n,this.cacheProvider=null,this.uid=null,this.authProvider.addTokenChangeListener((async e=>{const t=this.authProvider.getAuth().getUid();if(this.uid!==t){this.cacheProvider?.close(),this.uid=t;const e=await this.getIdentifier(this.uid);this.cacheProvider=this.initializeNewProviders(e)}}))}async initialize(){if(!this.cacheProvider){const e=await this.getIdentifier(this.uid);this.cacheProvider=this.initializeNewProviders(e)}}async getIdentifier(e){const t=`memory-${this.projectId}-${this.connectorConfig.service}-${this.connectorConfig.connector}-${this.connectorConfig.location}-${e}-${this.host}`;return await async function generateSHA256Hash(e){const t=(new TextEncoder).encode(e),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map((e=>e.toString(16).padStart(2,"0"))).join("")}(t)}initializeNewProviders(e){return this.cacheSettings.cacheProvider.initialize(e)}async containsResultTree(e){await this.initialize();return void 0!==await this.cacheProvider.getResultTree(e)}async getResultTree(e){return await this.initialize(),this.cacheProvider.getResultTree(e)}async getResultJSON(e){await this.initialize();const t=new ResultTreeProcessor,s=this.cacheProvider,r=await s.getResultTree(e);if(!r)throw new DataConnectError(g.INVALID_ARGUMENT,`${e} not found in cache. Call "update()" first.`);return t.hydrateResults(r.getRootStub())}async update(e,t,s){await this.initialize();const r=new ResultTreeProcessor,n=this.cacheProvider,{entityNode:i,impacted:o}=await r.dehydrateResults(t,s,n,e),a=new Date;return await n.setResultTree(e,new ResultTree(i,t.maxAge||this.cacheSettings.maxAgeSeconds,a,a)),o}}class MemoryStub{constructor(){this.type="MEMORY"}initialize(e){return new InMemoryCacheProvider(e)}}class AppCheckTokenProvider{constructor(e,t){this.appCheckProvider=t,n(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then((e=>this.appCheck=e)).catch()}getToken(){return this.serverAppAppCheckToken?Promise.resolve({token:this.serverAppAppCheckToken}):this.appCheck?this.appCheck.getToken():new Promise(((e,t)=>{setTimeout((()=>{this.appCheck?this.getToken().then(e,t):e(null)}),0)}))}addTokenChangeListener(e){this.appCheckProvider?.get().then((t=>t.addTokenListener(e)))}}const f=new class Logger{constructor(e){this.name=e,this._logLevel=h,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in a))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?c[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,a.DEBUG,...e),this._logHandler(this,a.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,a.VERBOSE,...e),this._logHandler(this,a.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,a.INFO,...e),this._logHandler(this,a.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,a.WARN,...e),this._logHandler(this,a.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,a.ERROR,...e),this._logHandler(this,a.ERROR,...e)}}("@firebase/data-connect");function setLogLevel(e){f.setLogLevel(e)}function logDebug(e){f.debug(`DataConnect (${p}): ${e}`)}function logError(e){f.error(`DataConnect (${p}): ${e}`)}class FirebaseAuthProvider{constructor(e,t,s){this._appName=e,this._options=t,this._authProvider=s,this._auth=s.getImmediate({optional:!0}),this._auth||s.onInit((e=>this._auth=e))}getAuth(){return this._auth}getToken(e){return this._auth?this._auth.getToken(e).catch((e=>e&&"auth/token-not-initialized"===e.code?(logDebug("Got auth/token-not-initialized error. Treating as null token."),null):(logError("Error received when attempting to retrieve token: "+JSON.stringify(e)),Promise.reject(e)))):new Promise(((t,s)=>{setTimeout((()=>{this._auth?this.getToken(e).then(t,s):t(null)}),0)}))}addTokenChangeListener(e){this._auth?.addAuthTokenListener(e)}removeTokenChangeListener(e){this._authProvider.get().then((t=>t.removeAuthTokenListener(e))).catch((e=>logError(e)))}}const v="query",y="mutation",T="SERVER",E="CACHE";function populatePath(e,t,s){let r=t;for(const t of e)"object"!=typeof r[t]&&(r[t]={}),r=r[t];if("entityId"in s&&s.entityId)r._id=s.entityId;else if("entityIds"in s){const e=s.entityIds;for(let t=0;t<e.length;t++){const s=e[t];void 0===r[t]&&(r[t]={}),r[t]._id=s}}}let R,C;function sortKeysForObj(e){return Object.keys(e).sort().reduce(((t,s)=>(t[s]=e[s],t)),{})}function getRefSerializer(e,t,s,r){return function toJSON(){return{data:t,refInfo:{name:e.name,variables:e.variables,connectorConfig:{projectId:e.dataConnect.app.options.projectId,...e.dataConnect.getSettings()}},fetchTime:r,source:s}}}!function setEncoder(e){R=e}((e=>JSON.stringify(sortKeysForObj(e)))),function setDecoder(e){C=e}((e=>sortKeysForObj(JSON.parse(e))));class QueryManager{async preferCacheResults(e,t=!1){let s;try{s=await this.fetchCacheResults(e,t)}catch(e){}return s||this.fetchServerResults(e)}constructor(e,t,s){this.transport=e,this.dc=t,this.cache=s,this.callbacks=new Map,this.subscriptionCache=new Map,this.queue=[]}async waitForQueuedWrites(){for(const e of this.queue)await e;this.queue=[]}updateSSR(e){this.queue.push(this.updateCache(e).then((async t=>this.publishCacheResultsToSubscribers(t,e.fetchTime))))}async updateCache(e,t){if(await this.waitForQueuedWrites(),this.cache){const s=function parseEntityIds(e){const t=e.extensions?.dataConnect,s=Object.assign(e);if(!t)return s;const r={};for(const e of t){const{path:t}=e;populatePath(t,r,e)}return r}(e),r=function getMaxAgeFromExtensions(e){if(!e)return;for(const t of e)if("maxAge"in t&&void 0!==t.maxAge&&null!==t.maxAge&&t.maxAge.endsWith("s"))return Number(t.maxAge.substring(0,t.maxAge.length-1))}(t);return void 0!==r&&(this.cache.cacheSettings.maxAgeSeconds=r),this.cache.update(R({name:e.ref.name,variables:e.ref.variables,refType:v}),e.data,s)}{const t=R({name:e.ref.name,variables:e.ref.variables,refType:v});return this.subscriptionCache.set(t,e),[t]}}addSubscription(e,t,s,r,n){const i=R({name:e.name,variables:e.variables,refType:v}),unsubscribe=()=>{if(this.callbacks.has(i)){const t=this.callbacks.get(i).filter((e=>e!==o));this.callbacks.set(i,t),0===t.length&&(this.callbacks.delete(i),this.transport.invokeUnsubscribe(e.name,e.variables)),s?.()}},o={userCallback:t,errCallback:r,unsubscribe:unsubscribe};n&&this.updateSSR(n);return this.preferCacheResults(e,!0).then(void 0,(e=>{})),this.callbacks.has(i)?this.callbacks.get(i).push(o):(this.callbacks.set(i,[o]),this.transport.invokeSubscribe(this.makeSubscribeObserver(e),e.name,e.variables)),unsubscribe}async fetchServerResults(e){await this.waitForQueuedWrites();const t=R({name:e.name,variables:e.variables,refType:v});try{const s=await this.transport.invokeQuery(e.name,e.variables),r=Date.now().toString(),n=s.extensions,i={...s,ref:e,source:T,fetchTime:r,data:s.data,extensions:getDataConnectExtensionsWithoutMaxAge(n),toJSON:getRefSerializer(e,s.data,T,r)},o=await this.updateCache(i,n?.dataConnect);return this.publishDataToSubscribers(t,i),this.cache?await this.publishCacheResultsToSubscribers(o,r):this.subscriptionCache.set(t,i),i}catch(e){throw this.publishErrorToSubscribers(t,e),e}}async fetchCacheResults(e,t=!1){let s;if(await this.waitForQueuedWrites(),s=this.cache?await this.getFromResultTreeCache(e,t):await this.getFromSubscriberCache(e),!s)throw new DataConnectError(g.OTHER,"No cache entry found for query: "+e.name);const r=Date.now().toString(),n={...s,ref:e,source:E,fetchTime:r,data:s.data,extensions:s.extensions,toJSON:getRefSerializer(e,s.data,E,r)};if(this.cache){const t=R({name:e.name,variables:e.variables,refType:v});await this.publishCacheResultsToSubscribers([t],r)}else{const t=R({name:e.name,variables:e.variables,refType:v});this.subscriptionCache.set(t,n),this.publishDataToSubscribers(t,n)}return n}publishErrorToSubscribers(e,t){this.callbacks.get(e)?.forEach((e=>{e.errCallback&&e.errCallback(t)}))}async getFromResultTreeCache(e,t=!1){const s=R({name:e.name,variables:e.variables,refType:v});if(!this.cache||!await this.cache.containsResultTree(s))return null;const r=await this.cache.getResultJSON(s),n=await this.cache.getResultTree(s);if(!t&&n.isStale())return null;const i={source:E,ref:e,data:r,toJSON:getRefSerializer(e,r,E,n.cachedAt.toString()),fetchTime:n.cachedAt.toString()};return(await this.cache.getResultTree(s)).updateAccessed(),i}async getFromSubscriberCache(e){const t=R({name:e.name,variables:e.variables,refType:v});if(!this.subscriptionCache.has(t))return;const s=this.subscriptionCache.get(t);return s.source=E,s.toJSON=getRefSerializer(s.ref,s.data,E,s.fetchTime),s}publishDataToSubscribers(e,t){if(!this.callbacks.has(e))return;this.callbacks.get(e).forEach((e=>{e.userCallback(t)}))}async publishCacheResultsToSubscribers(e,t){if(this.cache)for(const s of e){if(!this.callbacks.get(s))continue;const e=(await this.cache.getResultTree(s)).getRootStub().toJSON(b.hydrated),{name:r,variables:n}=C(s),i={dataConnect:this.dc,refType:v,name:r,variables:n};this.publishDataToSubscribers(s,{data:e,fetchTime:t,ref:i,source:E,toJSON:getRefSerializer(i,e,E,t)})}}enableEmulator(e,t){this.transport.useEmulator(e,t)}makeSubscribeObserver(e){const t=R({name:e.name,variables:e.variables,refType:v});return{onData:async s=>{await this.handleStreamNotification(t,s,e)},onDisconnect:(e,s)=>{this.handleStreamDisconnect(t,e,s)},onError:e=>{this.publishErrorToSubscribers(t,e)}}}async handleStreamNotification(e,t,s){if(t.errors&&t.errors.length>0){const s=JSON.stringify(t.errors.map((e=>e&&"object"==typeof e?{message:e.message,code:e.code}:e))),r={errors:t.errors,data:t.data},n=new DataConnectOperationError("DataConnect error received from subscribe notification: "+s,r);return void this.publishErrorToSubscribers(e,n)}const r=Date.now().toString(),n={ref:s,source:T,fetchTime:r,data:t.data,extensions:getDataConnectExtensionsWithoutMaxAge(t.extensions),toJSON:getRefSerializer(s,t.data,T,r)},i=await this.updateCache(n,t.extensions?.dataConnect);this.publishDataToSubscribers(e,n),this.cache&&await this.publishCacheResultsToSubscribers(i,r)}handleStreamDisconnect(e,t,s){const r=new DataConnectError(t,s);this.publishErrorToSubscribers(e,r);const n=this.callbacks.get(e);n&&[...n].forEach((e=>e.unsubscribe()))}}function getDataConnectExtensionsWithoutMaxAge(e){return{dataConnect:e.dataConnect?.filter((e=>"entityId"in e||"entityIds"in e))}}const k={Base:"Base",Generated:"Generated",TanstackReactCore:"TanstackReactCore",GeneratedReact:"GeneratedReact",TanstackAngularCore:"TanstackAngularCore",GeneratedAngular:"GeneratedAngular"};function getGoogApiClientValue$1(e,t){let s="gl-js/ fire/"+p;return t!==k.Base&&t!==k.Generated?s+=" js/"+t.toLowerCase():(e||t===k.Generated)&&(s+=" js/gen"),s}class AbstractDataConnectTransport{constructor(e,t,s,r,n,i,o=!1,a=k.Base){this.apiKey=t,this.appId=s,this.authProvider=r,this.appCheckProvider=n,this._isUsingGen=o,this._callerSdkType=a,this._host="",this._location="l",this._connectorName="",this._secure=!0,this._project="p",this._authToken=null,this._appCheckToken=null,this._lastToken=null,this._isUsingEmulator=!1,i&&("number"==typeof i.port&&(this._port=i.port),void 0!==i.sslEnabled&&(this._secure=i.sslEnabled),this._host=i.host);const{location:c,projectId:h,connector:u,service:l}=e;if(c&&(this._location=c),h&&(this._project=h),this._serviceName=l,!u)throw new DataConnectError(g.INVALID_ARGUMENT,"Connector Name required!");this._connectorName=u,this._connectorResourcePath=`projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,this.authProvider?.addTokenChangeListener((e=>{logDebug(`New Token Available: ${e}`),this.onAuthTokenChanged(e)})),this.appCheckProvider?.addTokenChangeListener((e=>{const{token:t}=e;logDebug(`New App Check Token Available: ${t}`),this._appCheckToken=t}))}useEmulator(e,t,s){this._host=e,this._isUsingEmulator=!0,"number"==typeof t&&(this._port=t),void 0!==s&&(this._secure=s)}async getWithAuth(e=!1){let t=new Promise((e=>e(this._authToken)));if(this.appCheckProvider){const e=await this.appCheckProvider.getToken();e&&(this._appCheckToken=e.token)}return t=this.authProvider?this.authProvider.getToken(e).then((e=>e?(this._authToken=e.accessToken,this._authToken):null)):new Promise((e=>e(""))),t}async withRetry(e,t=!1){let s=!1;return this.getWithAuth(t).then((e=>(s=this._lastToken!==e,this._lastToken=e,e))).then(e).catch((r=>{if("code"in r&&r.code===g.UNAUTHORIZED&&!t&&s)return logDebug("Retrying due to unauthorized"),this.withRetry(e,!0);throw r}))}_setLastToken(e){this._lastToken=e}_setCallerSdkType(e){this._callerSdkType=e}}let S=globalThis.fetch;function getGoogApiClientValue(e,t){let s="gl-js/ fire/"+p;return t!==k.Base&&t!==k.Generated?s+=" js/"+t.toLowerCase():(e||t===k.Generated)&&(s+=" js/gen"),s}async function dcFetch(e,t,{signal:s},r,n,i,o,a,c){if(!S)throw new DataConnectError(g.OTHER,"No Fetch Implementation detected!");const h={"Content-Type":"application/json","X-Goog-Api-Client":getGoogApiClientValue(o,a)};n&&(h["X-Firebase-Auth-Token"]=n),r&&(h["x-firebase-gmpid"]=r),i&&(h["X-Firebase-AppCheck"]=i);const u={body:JSON.stringify(t),method:"POST",headers:h,signal:s};let l,d;isCloudWorkstation(e)&&c&&(u.credentials="include");try{l=await S(e,u)}catch(e){const t=e&&"object"==typeof e&&"message"in e?e.message:String(e);throw new DataConnectError(g.OTHER,"Failed to fetch: "+t)}try{d=await l.json()}catch(e){const t=e&&"object"==typeof e&&"message"in e?e.message:String(e);throw new DataConnectError(g.OTHER,"Failed to parse JSON response: "+t)}const p=function getErrorMessage(e){if("message"in e&&e.message)return e.message;return JSON.stringify(e)}(d);if(l.status>=400){if(logError("Error while performing request: "+JSON.stringify(d)),401===l.status)throw new DataConnectError(g.UNAUTHORIZED,p);throw new DataConnectError(g.OTHER,p)}if(d.errors&&d.errors.length){const e=JSON.stringify(d.errors),t={errors:d.errors,data:d.data};throw new DataConnectOperationError("DataConnect error while performing request: "+e,t)}return d.extensions||(d.extensions={dataConnect:[]}),d}const w="firebasedataconnect.googleapis.com";function addToken(e,t){if(!t)return e;const s=new URL(e);return s.searchParams.append("key",t),s.toString()}class RESTTransport extends AbstractDataConnectTransport{constructor(e,t,s,r,n,i,o=!1,a=k.Base){super(e,t,s,r,n,i,o,a),this.invokeQuery=(e,t)=>{const s=new AbortController;return this.withRetry((()=>dcFetch(addToken(`${this.endpointUrl}:executeQuery`,this.apiKey),{name:this._connectorResourcePath,operationName:e,variables:t},s,this.appId,this._authToken,this._appCheckToken,this._isUsingGen,this._callerSdkType,this._isUsingEmulator)))},this.invokeMutation=(e,t)=>{const s=new AbortController;return this.withRetry((()=>dcFetch(addToken(`${this.endpointUrl}:executeMutation`,this.apiKey),{name:this._connectorResourcePath,operationName:e,variables:t},s,this.appId,this._authToken,this._appCheckToken,this._isUsingGen,this._callerSdkType,this._isUsingEmulator)))}}get endpointUrl(){return function restUrlBuilder(e,t){const{connector:s,location:r,projectId:n,service:i}=e,{host:o,sslEnabled:a,port:c}=t;let h=`${a?"https":"http"}://${o||w}`;if("number"==typeof c)h+=`:${c}`;else if(void 0!==c)throw logError("Port type is of an invalid type"),new DataConnectError(g.INVALID_ARGUMENT,"Incorrect type for port passed in!");return`${h}/v1/projects/${n}/locations/${r}/services/${i}/connectors/${s}`}({connector:this._connectorName,location:this._location,projectId:this._project,service:this._serviceName},{host:this._host,sslEnabled:this._secure,port:this._port})}invokeSubscribe(e,t,s){throw new DataConnectError(g.NOT_SUPPORTED,"Subscriptions are not supported using REST!")}invokeUnsubscribe(e,t){throw new DataConnectError(g.NOT_SUPPORTED,"Unsubscriptions are not supported using REST!")}onAuthTokenChanged(e){this._authToken=e}}class AbstractDataConnectStreamTransport extends AbstractDataConnectTransport{get isPendingClose(){return!!this.idleTimeout}get hasActiveSubscriptions(){return this.activeInvokeSubscribeRequests.size>0}get hasActiveExecuteRequests(){return this.activeInvokeQueryRequests.size>0||this.activeInvokeMutationRequests.size>0}constructor(e,t,s,r,n,i,o=!1,a=k.Base){super(e,t,s,r,n,i,o,a),this.apiKey=t,this.appId=s,this.authProvider=r,this.appCheckProvider=n,this._isUsingGen=o,this._callerSdkType=a,this.isUnableToConnect=!1,this.requestNumber=1,this.activeInvokeQueryRequests=new Map,this.queuedInvokeQueryRequests=new Map,this.activeInvokeMutationRequests=new Map,this.activeInvokeSubscribeRequests=new Map,this.executeRequestPromises=new Map,this.resumeRequestPromises=new Map,this.subscribeObservers=new Map,this.pendingCancellations=new Map,this.idleTimeout=null,this.hasWaitedForInitialAuth=!1,this.reconnectDelayMs=1e3,this.reconnectTimer=null,this.reconnectAttempts=0,this.removeOnlineEventListener=null,this.removeVisibilityChangeEventListener=null,this.onOnlineEventListener=()=>{this.reconnectTimer&&(this.cancelReconnect(),this.attemptReconnect())},this.onVisibilityChangeEventListener=()=>{const e=globalThis.document;e&&"visible"===e.visibilityState&&this.reconnectTimer&&(this.cancelReconnect(),this.attemptReconnect())},this.isFirstStreamMessage=!0,this.lastSentAuthToken=null,this.registerBrowserEventListeners()}registerBrowserEventListeners(){if("addEventListener"in globalThis){const e=this.onOnlineEventListener;globalThis.addEventListener("online",e),this.removeOnlineEventListener=()=>globalThis.removeEventListener("online",e)}const e=globalThis.document;if(e&&"addEventListener"in e){const t=this.onVisibilityChangeEventListener;e.addEventListener("visibilitychange",t),this.removeVisibilityChangeEventListener=()=>e.removeEventListener("visibilitychange",t)}}cleanupBrowserEventListeners(){this.removeVisibilityChangeEventListener?.(),this.removeVisibilityChangeEventListener=null,this.removeOnlineEventListener?.(),this.removeOnlineEventListener=null}async cleanupAndTerminate(e,t){this.cleanupBrowserEventListeners(),this.cancelReconnect(),this.cancelClose(),this.rejectAllRequests(e??g.OTHER,t??"Stream disposed."),await this.closeConnection(),this.onCloseCallback?.()}nextRequestId(){return(this.requestNumber++).toString()}trackInvokeMutationRequest(e,t,s){let r,n;const i={responsePromise:new Promise(((e,t)=>{r=e,n=t})),resolveFn:r,rejectFn:n},o=this.activeInvokeMutationRequests.get(t)||[];return o.push(s),this.activeInvokeMutationRequests.set(t,o),this.executeRequestPromises.set(e,i),i}trackInvokeSubscribeRequest(e,t,s,r){this.activeInvokeSubscribeRequests.set(t,s),this.subscribeObservers.set(e,r)}cleanupInvokeQueryRequest(e,t){this.activeInvokeQueryRequests.delete(t),this.executeRequestPromises.delete(e),this.resumeRequestPromises.delete(e)}cleanupInvokeMutationRequest(e,t){const s=this.activeInvokeMutationRequests.get(t);if(s){const r=s.filter((t=>t.requestId!==e));r.length>0?this.activeInvokeMutationRequests.set(t,r):this.activeInvokeMutationRequests.delete(t)}this.executeRequestPromises.delete(e)}cleanupInvokeSubscribeRequest(e,t){this.activeInvokeSubscribeRequests.delete(t),this.subscribeObservers.delete(e)}cancelReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}startReconnectBackoff(){if(this.reconnectTimer)return;if(this.reconnectAttempts++>=10){const e="Stream disconnected and could not reconnect - max stream reconnection attempts reached.";return logError(e),void this.cleanupAndTerminate(g.OTHER,e)}const e=this.reconnectDelayMs;this.reconnectDelayMs=Math.min(1.3*this.reconnectDelayMs,3e4);const t=500*Math.random();this.reconnectTimer=setTimeout((()=>{this.reconnectTimer=null,this.attemptReconnect()}),e+t)}async attemptReconnect(){try{await this.ensureConnection(),this.reconnectDelayMs=1e3,this.reconnectAttempts=0,await this.retriggerActiveRequests()}catch(e){e instanceof FirebaseError?(logDebug(`Reconnect attempt #${this.reconnectAttempts} failed with Firebase error: ${e.message}. Retrying...`),this.startReconnectBackoff()):(logError(`Unexpected error during reconnect attempt #${this.reconnectAttempts}: ${e}`),this.cleanupAndTerminate(g.OTHER,`Unexpected error during reconnect attempt #${this.reconnectAttempts}: ${e}`))}}async retriggerActiveRequests(){for(const[e,t]of this.activeInvokeSubscribeRequests)await this.sendRequestMessage(t);for(const[e,t]of this.activeInvokeQueryRequests)await this.sendRequestMessage(t)}get shouldIncludeAuth(){return this.isFirstStreamMessage||!!this._authToken&&this._authToken!==this.lastSentAuthToken}onConnectionReady(){this.isFirstStreamMessage=!0,this.lastSentAuthToken=null,this.hasWaitedForInitialAuth=!1}startIdleCloseTimeout(){this.idleTimeout||(this.idleTimeout=setTimeout((()=>{this.idleTimeout=null,this.hasActiveSubscriptions||this.hasActiveExecuteRequests||this.cleanupAndTerminate(g.OTHER,"Stream closed due to idleness.")}),0))}cancelClose(){this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null)}rejectAllRequests(e,t){this.activeInvokeQueryRequests.clear(),this.activeInvokeMutationRequests.clear(),this.activeInvokeSubscribeRequests.clear();const s=new DataConnectError(e,t);for(const[e,{rejectFn:t}]of this.queuedInvokeQueryRequests)this.queuedInvokeQueryRequests.delete(e),t(s);for(const[e,{rejectFn:t}]of this.executeRequestPromises)this.executeRequestPromises.delete(e),t(s);for(const[e,{rejectFn:t}]of this.resumeRequestPromises)this.resumeRequestPromises.delete(e),t(s);for(const[s,r]of this.subscribeObservers)this.subscribeObservers.delete(s),r.onDisconnect(e,t);this.pendingCancellations.clear(),this.cancelReconnect()}rejectAllMutationsOnReconnect(){const e=new DataConnectError(g.OTHER,"Mutation aborted due to stream disconnect.");for(const[t,s]of this.activeInvokeMutationRequests)for(const t of s){const s=this.executeRequestPromises.get(t.requestId);s&&(s.rejectFn(e),this.executeRequestPromises.delete(t.requestId))}this.activeInvokeMutationRequests.clear()}onStreamClose(e,t){this.cancelClose(),this.hasActiveSubscriptions?(logDebug(`Stream disconnected with code ${e}: ${t}. Attempting reconnect...`),this.rejectAllMutationsOnReconnect(),this.startReconnectBackoff()):this.cleanupAndTerminate(g.OTHER,`Stream disconnected while idle with code ${e}: ${t}`)}prepareMessage(e){const t={...e},s={};return this.appId&&(s["x-firebase-gmpid"]=this.appId),s["X-Goog-Api-Client"]=getGoogApiClientValue$1(this._isUsingGen,this._callerSdkType),this.shouldIncludeAuth&&this._authToken&&(s["X-Firebase-Auth-Token"]=this._authToken,this.lastSentAuthToken=this._authToken),this.isFirstStreamMessage&&(this._appCheckToken&&(s["X-Firebase-App-Check"]=this._appCheckToken),t.name=this._connectorResourcePath),t.headers=s,this.isFirstStreamMessage=!1,t}async sendRequestMessage(e){if(!this.hasWaitedForInitialAuth&&this.authProvider&&(await this.getWithAuth(),this.hasWaitedForInitialAuth=!0),this.streamIsReady){const t=this.prepareMessage(e);return this.sendMessage(t)}return this.ensureConnection().then((()=>{const t=this.prepareMessage(e);return this.sendMessage(t)}))}getMapKey(e,t){const s=this.sortObjectKeys(t);return JSON.stringify({operationName:e,variables:s})}sortObjectKeys(e){if(null===e||"object"!=typeof e||Array.isArray(e))return e;const t={};return Object.keys(e).sort().forEach((s=>{t[s]=this.sortObjectKeys(e[s])})),t}invokeQuery(e,t){const s=this.getMapKey(e,t);return this.activeInvokeQueryRequests.has(s)?this.queueInvokeQueryRequest(s):this.executeOrResumeQuery(e,t,s)}queueInvokeQueryRequest(e){const t=this.queuedInvokeQueryRequests.get(e);if(t)return t.responsePromise;let s,r;const n=new Promise(((e,t)=>{s=e,r=t}));return this.queuedInvokeQueryRequests.set(e,{responsePromise:n,resolveFn:s,rejectFn:r}),n}executeOrResumeQuery(e,t,s,r){const n=this.activeInvokeSubscribeRequests.get(s);let i,o,a,c,h;return r?(i=r.resolveFn,o=r.rejectFn,a=r.responsePromise):a=new Promise(((e,t)=>{i=e,o=t})),n?(c=n.requestId,h={requestId:c,resume:{}},this.resumeRequestPromises.set(c,{responsePromise:a,resolveFn:i,rejectFn:o})):(c=this.nextRequestId(),h={requestId:c,execute:{operationName:e,variables:t}},this.executeRequestPromises.set(c,{responsePromise:a,resolveFn:i,rejectFn:o})),this.activeInvokeQueryRequests.set(s,h),a=a.finally((()=>{this.onInvokeQueryRequestFulfilled(e,t,s,c)})),this.sendRequestMessage(h).catch((e=>{o(e)})),a}onInvokeQueryRequestFulfilled(e,t,s,r){this.cleanupInvokeQueryRequest(r,s);this.pendingCancellations.get(r)&&(this.pendingCancellations.delete(r),this.cancelSubscription(r,s));const n=this.queuedInvokeQueryRequests.get(s);n?(this.queuedInvokeQueryRequests.delete(s),this.executeOrResumeQuery(e,t,s,n)):this.hasActiveSubscriptions||this.hasActiveExecuteRequests||this.startIdleCloseTimeout()}invokeMutation(e,t){const s=this.nextRequestId(),r={operationName:e,variables:t},n=this.getMapKey(e,t),i={requestId:s,execute:r};let{responsePromise:o,rejectFn:a}=this.trackInvokeMutationRequest(s,n,i);return o=o.finally((()=>{this.cleanupInvokeMutationRequest(s,n),this.hasActiveSubscriptions||this.hasActiveExecuteRequests||this.startIdleCloseTimeout()})),this.sendRequestMessage(i).catch((e=>{a(e)})),o}invokeSubscribe(e,t,s){const r=this.getMapKey(t,s),n=this.activeInvokeSubscribeRequests.get(r);if(n){const t=n.requestId;this.pendingCancellations.has(t)&&(this.pendingCancellations.delete(t),this.subscribeObservers.set(t,e))}else{const n=this.nextRequestId(),i={requestId:n,subscribe:{operationName:t,variables:s}};this.trackInvokeSubscribeRequest(n,r,i,e),this.sendRequestMessage(i).catch((t=>{e.onError(t instanceof Error?t:new Error(String(t))),this.cleanupInvokeSubscribeRequest(n,r),this.hasActiveSubscriptions||this.startIdleCloseTimeout()}))}this.cancelClose()}invokeUnsubscribe(e,t){const s=this.getMapKey(e,t),r=this.activeInvokeSubscribeRequests.get(s);if(!r)return;const n=r.requestId;this.subscribeObservers.delete(n);this.resumeRequestPromises.get(n)?this.pendingCancellations.set(n,{operationName:e,variables:t}):this.cancelSubscription(n,s)}cancelSubscription(e,t){this.cleanupInvokeSubscribeRequest(e,t);const s={requestId:e,cancel:{}};this.sendRequestMessage(s).catch((e=>{logError(`Stream Transport failed to send unsubscribe message: ${e}`)})),this.hasActiveSubscriptions||this.startIdleCloseTimeout()}onAuthTokenChanged(e){const t=this._authToken;this._authToken=e;const s=this.authUid,r=this.authProvider?.getAuth()?.getUid();this.authUid=r;void 0===s||(t&&null===e||!s&&r||s&&r!==s)&&this.cleanupAndTerminate(g.UNAUTHORIZED,"Stream disconnected due to auth change.")}async handleResponse(e,t){if(this.executeRequestPromises.has(e)){const{resolveFn:s,rejectFn:r}=this.executeRequestPromises.get(e);this.handleInvokeOperationResponse(s,r,t)}else if(this.subscribeObservers.has(e)||this.resumeRequestPromises.has(e)){const s=this.subscribeObservers.get(e),r=this.resumeRequestPromises.get(e);if(r){this.resumeRequestPromises.delete(e);const{resolveFn:s,rejectFn:n}=r;this.handleInvokeOperationResponse(s,n,t)}if(s)try{await s.onData(t)}catch(e){logError(`Error in observer callback: ${e}`)}}else logError(`Stream response contained unrecognized requestId '${e}'`)}handleInvokeOperationResponse(e,t,s){if(s.errors&&s.errors.length){const e={errors:s.errors,data:s.data},r=JSON.stringify(s.errors);t(new DataConnectOperationError("DataConnect error while performing request: "+r,e))}else e(s)}}let _=globalThis.WebSocket;class WebSocketTransport extends AbstractDataConnectStreamTransport{constructor(){super(...arguments),this.decoder=void 0,this.connection=void 0,this.connectionAttempt=null}get endpointUrl(){return function websocketUrlBuilder(e,t){const{location:s}=e,{host:r,sslEnabled:n,port:i}=t;let o=`${n?"wss":"ws"}://${r||w}`;if("number"==typeof i)o+=`:${i}`;else if(void 0!==i)throw logError("Port type is of an invalid type"),new DataConnectError(g.INVALID_ARGUMENT,"Incorrect type for port passed in!");return`${o}/ws/google.firebase.dataconnect.v1.ConnectorStreamService/Connect/locations/${s}`}({connector:this._connectorName,location:this._location,projectId:this._project,service:this._serviceName},{host:this._host,sslEnabled:this._secure,port:this._port})}decodeBinaryResponse(e){return this.decoder||(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}get streamIsReady(){return this.connection?.readyState===WebSocket.OPEN}ensureConnection(){try{return this.streamIsReady?Promise.resolve():(this.connectionAttempt||(this.connectionAttempt=new Promise(((e,t)=>{if(!_)throw new DataConnectError(g.OTHER,"No WebSocket Implementation detected!");const s=new _(this.endpointUrl);this.connection=s,this.connection.binaryType="arraybuffer",s.onopen=()=>{this.isUnableToConnect=!1,this.onConnectionReady(),e()},s.onerror=e=>{this.connectionAttempt=null,this.isUnableToConnect=!0;const s=new DataConnectError(g.OTHER,"Error using WebSocket connection, closing WebSocket");this.handleError(s),t(s)},s.onmessage=e=>this.handleWebSocketMessage(e).catch((async e=>{this.handleError(e)})),s.onclose=e=>this.handleWebsocketDisconnect(e)}))),this.connectionAttempt)}catch(e){throw this.handleError(e),e}}openConnection(){return this.ensureConnection().catch((e=>{throw new DataConnectError(g.OTHER,`Failed to open connection: ${e}`)}))}closeConnection(e,t){if(!this.connection)return this.connectionAttempt=null,Promise.resolve();let s;try{if(t){const s=123,r=new TextEncoder;if(r.encode(t).length<=s)this.connection.close(e,t);else{const n=new Uint8Array(s),{read:i}=r.encodeInto(t,n),o=t.substring(0,i);this.connection.close(e,o)}}else this.connection.close(e)}catch(e){s=e}finally{this.connection=void 0,this.connectionAttempt=null}return s?Promise.reject(s):Promise.resolve()}handleWebsocketDisconnect(e){this.connection=void 0,this.connectionAttempt=null,this.onStreamClose(e.code,e.reason)}handleError(e){logError(`DataConnect WebSocket error, closing stream: ${e}`);let t=e?String(e):"Unknown Error";e instanceof DataConnectError&&(t=e.message),this.closeConnection(1e3,t)}sendMessage(e){return this.ensureConnection().then((()=>{try{return this.connection.send(JSON.stringify(e)),Promise.resolve()}catch(e){throw this.handleError(e),new DataConnectError(g.OTHER,`Failed to send message: ${String(e)}`)}}))}async handleWebSocketMessage(e){const t=this.parseWebSocketData(e.data),s=t.requestId,r={data:t.data,errors:t.errors,extensions:t.extensions||{dataConnect:[]}};await this.handleResponse(s,r)}parseWebSocketData(e){const t="string"==typeof e;let s,r;try{s=t?JSON.parse(e):JSON.parse(this.decodeBinaryResponse(e))}catch(e){throw new DataConnectError(g.OTHER,`Could not parse WebSocket message: ${e instanceof Error?e.message:String(e)}`)}if("object"!=typeof s||null===s)throw new DataConnectError(g.OTHER,"WebSocket message is not an object");if(t){if(!("result"in s))throw new DataConnectError(g.OTHER,"WebSocket message from emulator did not include result");if("object"!=typeof s.result||null===s.result)throw new DataConnectError(g.OTHER,"WebSocket message result is not an object");r=s.result}else r=s;if(!("requestId"in r))throw new DataConnectError(g.OTHER,"WebSocket message did not include requestId");return r}}class DataConnectTransportManager{constructor(e,t,s,r,n,i,o=!1,a){this.options=e,this.apiKey=t,this.appId=s,this.authProvider=r,this.appCheckProvider=n,this.transportOptions=i,this._isUsingGen=o,this._callerSdkType=a,this.isUsingEmulator=!1,this.restTransport=new RESTTransport(e,t,s,r,n,i,o,a)}initStreamTransport(){return this.streamTransport||(this.streamTransport=new WebSocketTransport(this.options,this.apiKey,this.appId,this.authProvider,this.appCheckProvider,this.transportOptions,this._isUsingGen,this._callerSdkType),this.isUsingEmulator&&this.transportOptions&&this.streamTransport.useEmulator(this.transportOptions.host,this.transportOptions.port,this.transportOptions.sslEnabled),this.streamTransport.onCloseCallback=()=>{this.streamTransport=void 0}),this.streamTransport}executeShouldUseStream(){return!!this.streamTransport&&!this.streamTransport.isPendingClose&&this.streamTransport.streamIsReady&&this.streamTransport.hasActiveSubscriptions&&!this.streamTransport.isUnableToConnect}invokeQuery(e,t){return this.executeShouldUseStream()?this.streamTransport.invokeQuery(e,t).catch((s=>{if(this.executeShouldUseStream())throw s;return this.restTransport.invokeQuery(e,t)})):this.restTransport.invokeQuery(e,t)}invokeMutation(e,t){return this.executeShouldUseStream()?this.streamTransport.invokeMutation(e,t).catch((s=>{if(this.executeShouldUseStream())throw s;return this.restTransport.invokeMutation(e,t)})):this.restTransport.invokeMutation(e,t)}invokeSubscribe(e,t,s){const r=this.initStreamTransport();if(r.isUnableToConnect)throw new DataConnectError(g.OTHER,"Unable to connect streaming connection to server. Subscriptions are unavailable.");r.invokeSubscribe(e,t,s)}invokeUnsubscribe(e,t){this.streamTransport&&this.streamTransport.invokeUnsubscribe(e,t)}useEmulator(e,t,s){this.isUsingEmulator=!0,this.transportOptions={host:e,port:t,sslEnabled:s},this.restTransport.useEmulator(e,t,s),this.streamTransport&&this.streamTransport.useEmulator(e,t,s)}onAuthTokenChanged(e){this.restTransport.onAuthTokenChanged(e),this.streamTransport&&this.streamTransport.onAuthTokenChanged(e)}_setCallerSdkType(e){this._callerSdkType=e,this.restTransport._setCallerSdkType(e),this.streamTransport&&this.streamTransport._setCallerSdkType(e)}}function mutationRef(e,t,s){e.setInitialized();return{dataConnect:e,name:t,refType:y,variables:s}}class MutationManager{constructor(e){this._transport=e,this._inflight=[]}executeMutation(e){const t=this._transport.invokeMutation(e.name,e.variables),s=t.then((t=>({...t,source:T,ref:e,fetchTime:Date.now().toLocaleString()})));this._inflight.push(t);const removePromise=()=>this._inflight=this._inflight.filter((e=>e!==t));return t.then(removePromise,removePromise),s}}function executeMutation(e){return e.dataConnect._mutationManager.executeMutation(e)}function parseOptions(e){const[t,s]=e.split("://"),r="https"===t,[n,i]=s.split(":");return{host:n,port:Number(i),sslEnabled:r}}class DataConnect{constructor(e,t,s,r){if(this.app=e,this.dataConnectOptions=t,this._authProvider=s,this._appCheckProvider=r,this.isEmulator=!1,this._initialized=!1,this._isUsingGeneratedSdk=!1,this._callerSdkType=k.Base,"undefined"!=typeof process&&process.env){const e=process.env.FIREBASE_DATA_CONNECT_EMULATOR_HOST;e&&(logDebug("Found custom host. Using emulator"),this.isEmulator=!0,this._transportOptions=parseOptions(e))}}getCache(){return this.cache}_useGeneratedSdk(){this._isUsingGeneratedSdk||(this._isUsingGeneratedSdk=!0)}_setCallerSdkType(e){this._callerSdkType=e,this._initialized&&this._transport._setCallerSdkType(e)}_delete(){return e(this.app,"data-connect",JSON.stringify(this.getSettings())),Promise.resolve()}getSettings(){const e=JSON.parse(JSON.stringify(this.dataConnectOptions));return delete e.projectId,e}setCacheSettings(e){this._cacheSettings=e}setInitialized(){if(this._initialized)return;void 0===this._transportClass&&(logDebug("transportClass not provided. Defaulting to DataConnectTransportManager."),this._transportClass=DataConnectTransportManager),this._authTokenProvider=new FirebaseAuthProvider(this.app.name,this.app.options,this._authProvider);const e={connector:this.dataConnectOptions.connector,service:this.dataConnectOptions.service,location:this.dataConnectOptions.location};this._cacheSettings&&(this.cache=new DataConnectCache(this._authTokenProvider,this.app.options.projectId,e,this._transportOptions?.host||w,this._cacheSettings)),this._appCheckProvider&&(this._appCheckTokenProvider=new AppCheckTokenProvider(this.app,this._appCheckProvider)),this._transport=new this._transportClass(this.dataConnectOptions,this.app.options.apiKey,this.app.options.appId,this._authTokenProvider,this._appCheckTokenProvider,void 0,this._isUsingGeneratedSdk,this._callerSdkType),this._transportOptions&&this._transport.useEmulator(this._transportOptions.host,this._transportOptions.port,this._transportOptions.sslEnabled),this._queryManager=new QueryManager(this._transport,this,this.cache),this._mutationManager=new MutationManager(this._transport),this._initialized=!0}enableEmulator(e){if(this._transportOptions&&this._initialized&&!areTransportOptionsEqual(this._transportOptions,e))throw logError("enableEmulator called after initialization"),new DataConnectError(g.ALREADY_INITIALIZED,"DataConnect instance already initialized!");this._transportOptions=e,this.isEmulator=!0}}function areTransportOptionsEqual(e,t){return e.host===t.host&&e.port===t.port&&e.sslEnabled===t.sslEnabled}function connectDataConnectEmulator(e,t,s,r=!1){isCloudWorkstation(t)&&async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(`https://${t}${s?`:${s}`:""}`),e.enableEmulator({host:t,port:s,sslEnabled:r})}function getDataConnect(e,s,r){let n,i,o;"location"in e?(i=e,n=t(),o=s):(n=e,i=s,o=r),n&&0!==Object.keys(n).length||(n=t());const a={...i,projectId:n.options.projectId},c=Object.fromEntries(Object.entries(a).sort()),h=_getProvider(n,"data-connect"),u=JSON.stringify(c);if(h.isInitialized(u)){const e=h.getImmediate({identifier:u}),t=h.getOptions(u);if(Object.keys(t).length>0)return logDebug("Re-using cached instance"),e}validateDCOptions(i),logDebug("Creating new DataConnect instance");const l=h.initialize({instanceIdentifier:u,options:Object.fromEntries(Object.entries({...c}).sort())});return o?.cacheSettings&&l.setCacheSettings(o.cacheSettings),l}function validateDCOptions(e){if(!e)throw new DataConnectError(g.INVALID_ARGUMENT,"DC Option Required");return["connector","location","service"].forEach((t=>{if(null===e[t]||void 0===e[t])throw new DataConnectError(g.INVALID_ARGUMENT,`${t} Required`)})),!0}function terminate(e){return e._delete()}const I={MEMORY:"MEMORY"};function makeMemoryCacheProvider(){return new MemoryStub}const A={PREFER_CACHE:"PREFER_CACHE",CACHE_ONLY:"CACHE_ONLY",SERVER_ONLY:"SERVER_ONLY"};function executeQuery(e,t){if(e.refType!==v)return Promise.reject(new DataConnectError(g.INVALID_ARGUMENT,"ExecuteQuery can only execute query operations"));const s=e.dataConnect._queryManager,r=t?.fetchPolicy??A.PREFER_CACHE;switch(r){case A.SERVER_ONLY:return s.fetchServerResults(e);case A.CACHE_ONLY:return s.fetchCacheResults(e,!0);case A.PREFER_CACHE:return s.preferCacheResults(e,!1);default:throw new DataConnectError(g.INVALID_ARGUMENT,`Invalid fetch policy: ${r}`)}}function queryRef(e,t,s,r){return e.setInitialized(),void 0!==r&&e._queryManager.updateSSR(r),{dataConnect:e,refType:v,name:t,variables:s}}function toQueryRef(e){const{refInfo:{name:t,variables:s,connectorConfig:r}}=e;return queryRef(getDataConnect(r),t,s)}function validateArgs(e,t,s,r){let n,i;if(t&&"enableEmulator"in t?(n=t,i=s):(n=getDataConnect(e),i=t),!n||!i&&r)throw new DataConnectError(g.INVALID_ARGUMENT,"Variables required.");return{dc:n,vars:i}}function validateArgsWithOptions(e,t,s,r,n,i){let o,a,c;if(t&&"enableEmulator"in t?(o=t,n?(a=s,c=r):(a=void 0,c=s)):(o=getDataConnect(e),n?(a=t,c=s):(a=void 0,c=t)),!o||!a&&i)throw new DataConnectError(g.INVALID_ARGUMENT,"Variables required.");return{dc:o,vars:a,options:c}}function subscribe(e,t,s,r){let n,i,o;if("refInfo"in e){const t=e,{data:s,source:r,fetchTime:o}=t;n=toQueryRef(t),i={data:s,source:r,fetchTime:o,ref:n,toJSON:getRefSerializer(n,s,r,o)}}else n=e;if("function"==typeof t?o=t:(o=t.onNext,s=t.onErr,r=t.onComplete),!o)throw new DataConnectError(g.INVALID_ARGUMENT,"Must provide onNext");return n.dataConnect._queryManager.addSubscription(n,o,r,s,i)}!function registerDataConnect(e){!function setSDKVersion(e){p=e}(i),s(new Component("data-connect",((e,{instanceIdentifier:t,options:s})=>{const r=e.getProvider("app").getImmediate(),n=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");let o=s;if(t&&(o={...JSON.parse(t),...o}),!r.options.projectId)throw new DataConnectError(g.INVALID_ARGUMENT,"Project ID must be provided. Did you pass in a proper projectId to initializeApp?");return new DataConnect(r,{...o,projectId:r.options.projectId},n,i)}),"PUBLIC").setMultipleInstances(!0)),r(l,d,e),r(l,d,"esm2020")}();export{AbstractDataConnectTransport,k as CallerSdkTypeEnum,g as Code,DataConnect,DataConnectError,DataConnectOperationError,y as MUTATION_STR,MutationManager,v as QUERY_STR,A as QueryFetchPolicy,E as SOURCE_CACHE,T as SOURCE_SERVER,I as StorageType,areTransportOptionsEqual,connectDataConnectEmulator,executeMutation,executeQuery,getDataConnect,getGoogApiClientValue$1 as getGoogApiClientValue,makeMemoryCacheProvider,mutationRef,parseOptions,queryRef,setLogLevel,subscribe,terminate,toQueryRef,validateArgs,validateArgsWithOptions,validateDCOptions};
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(Co,bo){try{!(function(){function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function r(t){var n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}let q=t(Co),W={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},f=function(e,t){if(!e)throw B(t)},B=function(e){return new Error("Firebase Database ("+W.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},U={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let c=0;c<n.length;c+=3){var s=n[c],o=c+1<n.length,a=o?n[c+1]:0,l=c+2<n.length,h=l?n[c+2]:0;let e=(15&a)<<2|h>>6,t=63&h;l||(t=64,o)||(e=64),i.push(r[s>>2],r[(3&s)<<4|a>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(r(e),t)},decodeString(n,r){if(this.HAS_NATIVE_SUPPORT&&!r)return atob(n);{var i=this.decodeStringToByteArray(n,r);var s=[];let e=0,t=0;for(;e<i.length;){var o,a,l,h=i[e++];h<128?s[t++]=String.fromCharCode(h):191<h&&h<224?(o=i[e++],s[t++]=String.fromCharCode((31&h)<<6|63&o)):239<h&&h<365?(o=((7&h)<<18|(63&i[e++])<<12|(63&i[e++])<<6|63&i[e++])-65536,s[t++]=String.fromCharCode(55296+(o>>10)),s[t++]=String.fromCharCode(56320+(1023&o))):(a=i[e++],l=i[e++],s[t++]=String.fromCharCode((15&h)<<12|(63&a)<<6|63&l))}return s.join("");return}},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let l=0;l<e.length;){var i=n[e.charAt(l++)],s=l<e.length?n[e.charAt(l)]:0,o=++l<e.length?n[e.charAt(l)]:64,a=++l<e.length?n[e.charAt(l)]:64;if(++l,null==i||null==s||null==o||null==a)throw new j;r.push(i<<2|s>>4),64!==o&&(r.push(s<<4&240|o>>2),64!==a)&&r.push(o<<6&192|a)}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class j extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}let V=function(e){var t=r(e);return U.encodeByteArray(t,!0)},z=function(e){return V(e).replace(/\./g,"")},H=function(e){try{return U.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function Q(e){return function e(t,n){if(!(n instanceof Object))return n;switch(n.constructor){case Date:let e=n;return new Date(e.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return n}for(var r in n)n.hasOwnProperty(r)&&Y(r)&&(t[r]=e(t[r],n[r]));return t}(void 0,e)}function Y(e){return"__proto__"!==e}class _{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function K(){return"undefined"!=typeof window&&(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test("undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"")}function G(){return!0===W.NODE_ADMIN}function $(e){return JSON.parse(e)}function a(e){return JSON.stringify(e)}function J(e){let t={},n={},r={},i="";try{var s=e.split(".");t=$(H(s[0])||""),n=$(H(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function X(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function Z(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function ee(e,t,n){var r,i={};for(r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=t.call(n,e[r],r,e));return i}function te(e){return null!==e&&"object"==typeof e}class ne{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;var i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],o=this.chain_[2],a=this.chain_[3],l=this.chain_[4],h,c;for(let _=0;_<80;_++){c=_<40?_<20?(h=a^s&(o^a),1518500249):(h=s^o^a,1859775393):_<60?(h=s&o|a&(s|o),2400959708):(h=s^o^a,3395469782);var u=(t<<5|t>>>27)+h+l+c+i[_]&4294967295;l=a,a=o,o=4294967295&(s<<30|s>>>2),s=t,t=u}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;var s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){var t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function l(e,t,n,r){let i;var s;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i)throw s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".",new Error(s)}function h(e,t){return e+` failed: ${t} argument `}function c(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(h(e,t)+"must be a valid function.")}function re(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(h(e,t)+"must be a valid context object.")}let ie=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t};function g(e){return e&&e._delegate?e._delegate:e}function se(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class oe{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let ae="[DEFAULT]";class le{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){var n=new _;if(this.instancesDeferred.set(t,n),this.isInitialized(t)||this.shouldAutoInitialize())try{var r=this.getOrInitializeService({instanceIdentifier:t});r&&n.resolve(r)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(e?.identifier),n=e?.optional??!1;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:ae})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=ae){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){var e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=ae){return this.instances.has(e)}getOptions(e=ae){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(this.name+`(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);let r=this.onInitCallbacks.get(n)??new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(var r of n)try{r(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===ae?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch{}var r;return n||null}normalizeInstanceIdentifier(e=ae){return!this.component||this.component.multipleInstances?e:ae}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class he{constructor(e){this.name=e,this.providers=new Map}addComponent(e){var t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with `+this.name);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){var t;return this.providers.has(e)?this.providers.get(e):(t=new le(e,this),this.providers.set(e,t),t)}getProviders(){return Array.from(this.providers.values())}}var n;(e=n=n||{})[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT";let ce={debug:n.DEBUG,verbose:n.VERBOSE,info:n.INFO,warn:n.WARN,error:n.ERROR,silent:n.SILENT},ue=n.INFO,de={[n.DEBUG]:"log",[n.VERBOSE]:"log",[n.INFO]:"info",[n.WARN]:"warn",[n.ERROR]:"error"},_e=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=de[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class pe{constructor(e){this.name=e,this._logLevel=ue,this._logHandler=_e,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in n))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?ce[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,n.DEBUG,...e),this._logHandler(this,n.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,n.VERBOSE,...e),this._logHandler(this,n.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,n.INFO,...e),this._logHandler(this,n.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,n.WARN,...e),this._logHandler(this,n.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,n.ERROR,...e),this._logHandler(this,n.ERROR,...e)}}let fe="@firebase/database",ge="";function me(e){ge=e}class ve{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),a(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:$(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class ye{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return p(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}function we(e){try{var t;if("undefined"!=typeof window&&void 0!==window[e])return(t=window[e]).setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new ve(t)}catch(e){}return new ye}var d,Ce;function be(e){var t=(t=>{var n,r,i=[];let s=0;for(let o=0;o<t.length;o++){let e=t.charCodeAt(o);55296<=e&&e<=56319&&(n=e-55296,o++,f(o<t.length,"Surrogate pair missing trail surrogate."),r=t.charCodeAt(o)-56320,e=65536+(n<<10)+r),e<128?i[s++]=e:(e<2048?i[s++]=e>>6|192:(e<65536?i[s++]=e>>12|224:(i[s++]=e>>18|240,i[s++]=e>>12&63|128),i[s++]=e>>6&63|128),i[s++]=63&e|128)}return i})(e),n=new ne,t=(n.update(t),n.digest());return U.encodeByteArray(t)}function Te(t){return function(...e){u(t,...e)}}function Ie(...e){var t="FIREBASE INTERNAL ERROR: "+Ae(...e);xe.error(t)}function Ee(e,t){return e===t?0:e<t?-1:1}function Se(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+a(t))}function ke(e){if("object"!=typeof e||null===e)return a(e);var t,n=[];for(t in e)n.push(t);n.sort();let r="{";for(let i=0;i<n.length;i++)0!==i&&(r+=","),r=(r=r+a(n[i])+":")+ke(e[n[i]]);return r+="}"}function Ne(e,t){var n=e.length;if(n<=t)return[e];var r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}let Pe=we("localStorage"),Re=we("sessionStorage"),xe=new pe("@firebase/database"),De=(()=>{let e=1;return function(){return e++}})(),Ae=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=Ae.apply(null,n):t+="object"==typeof n?a(n):n,t+=" "}return t},Oe=null,Le=!0,Me=function(e,t){f(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(xe.logLevel=n.VERBOSE,Oe=xe.log.bind(xe),t&&Re.set("logging_enabled",!0)):"function"==typeof e?Oe=e:(Oe=null,Re.remove("logging_enabled"))},u=function(...e){var t;!0===Le&&(Le=!1,null===Oe)&&!0===Re.get("logging_enabled")&&Me(!0),Oe&&(t=Ae.apply(null,e),Oe(t))},Fe=function(...e){var t="FIREBASE FATAL ERROR: "+Ae(...e);throw xe.error(t),new Error(t)},m=function(...e){var t="FIREBASE WARNING: "+Ae(...e);xe.warn(t)},qe=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&m("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},We=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},Be="[MIN_NAME]",Ue="[MAX_NAME]",je=function(e,t){var n,r;return e===t?0:e===Be||t===Ue?-1:t===Be||e===Ue?1:(n=ze(e),r=ze(t),null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1)};function v(e,t){for(var n in e)e.hasOwnProperty(n)&&t(n,e[n])}function Ve(e){f(!We(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));var o=[];for(s=52;s;--s)o.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)o.push(n%2?1:0),n=Math.floor(n/2);o.push(t?1:0),o.reverse();var a=o.join("");let l="";for(s=0;s<64;s+=8){let e=parseInt(a.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),l+=e}return l.toLowerCase()}function ze(e){if(Qe.test(e)){var t=Number(e);if(t>=Ye&&t<=Ke)return t}return null}function He(e,t){var n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n}let Qe=new RegExp("^-?(0*)\\d{1,10}$"),Ye=-2147483648,Ke=2147483647,Ge=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw m("Exception was thrown by user callback.",e),t},Math.floor(0))}};class $e{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,bo._isFirebaseServerApp(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then(e=>this.appCheck=e)}getToken(n){if(this.serverAppAppCheckToken){if(n)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.appCheckProvider?.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){m(`Provided AppCheck credentials for the app named "${this.appName}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Je{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(u("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',m(e)}}class Xe{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Xe.OWNER="owner";let Ze=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,et="websocket",tt="long_polling";class nt{constructor(e,t,n,r,i=!1,s="",o=!1,a=!1,l=null){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=Pe.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost())&&Pe.set("host:"+this._host,this.internalHost)}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?"?ns="+this.namespace:"";return e+this.host+"/"+t}}function rt(e,t,n){f("string"==typeof t,"typeof type must == string"),f("object"==typeof n,"typeof params must == object");let r;if(t===et)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==tt)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);let i=[];return v(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class it{constructor(){this.counters_={}}incrementCounter(e,t=1){p(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return Q(this.counters_)}}let st={},ot={};function at(e){var t=e.toString();return st[t]||(st[t]=new it),st[t]}class lt{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){let e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&Ge(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class ht{constructor(e,t,n,r,i,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Te(e),this.stats_=at(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),rt(t,tt,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new lt(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4));var n=()=>{var e;this.isClosed_||(this.scriptTagHolder=new ct((...e)=>{var[t,n,r,,,]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn),(e={start:"t"}).ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&Ze.test(location.hostname)&&(e.r="f"),e=this.urlFn(e),this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{}))};if("complete"===document.readyState)n();else{let e=!1,t=function(){document.body?e||(e=!0,n()):setTimeout(t,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",t,!1),window.addEventListener("load",t,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&t()}),window.attachEvent("onload",t))}}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){ht.forceAllow_=!0}static forceDisallow(){ht.forceDisallow_=!0}static isAvailable(){return!!ht.forceAllow_||!(ht.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){var t=a(e),t=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),V(t)),n=Ne(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");var n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){var t=a(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class ct{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=De(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=ct.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){u("frame writing exception"),e.stack&&u(e.stack),u(e)}}}static createIFrame_(){var t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||u("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));var e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(0<this.pendingSegs.length?2:1)){this.currentSerial++;var n={},n=(n.id=this.myID,n.pw=this.myPW,n.ser=this.currentSerial,this.urlFn(n));let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);let n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(this.sendNewPolls){let t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{u("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}}catch(e){}},Math.floor(1))}}let ut=null;"undefined"!=typeof MozWebSocket?ut=MozWebSocket:"undefined"!=typeof WebSocket&&(ut=WebSocket);class y{constructor(e,t,n,r,i,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Te(this.connId),this.stats_=at(t),this.connURL=y.connectionURL_(t,s,o,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){var s={v:"5"};return"undefined"!=typeof location&&location.hostname&&Ze.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s.ac=r),i&&(s.p=i),rt(e,et,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,Pe.set("previous_websocket_failure",!0);try{G(),this.mySock=new ut(this.connURL,[],void 0)}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){y.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return!(e="undefined"!=typeof navigator&&navigator.userAgent&&(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4?!0:e)&&null!==ut&&!y.forceDisallow_}static previouslyFailed(){return Pe.isInMemoryStorage||!0===Pe.get("previous_websocket_failure")}markConnectionHealthy(){Pe.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=$(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(f(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=a(e),n=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),Ne(t,16384));1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}y.responsesRequiredToBeHealthy=2,y.healthyTimeout=3e4;class dt{static get ALL_TRANSPORTS(){return[ht,y]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){var t=y&&y.isAvailable();let n=t&&!y.previouslyFailed();if(e.webSocketOnly&&(t||m("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[y];else{var r,i=this.transports_=[];for(r of dt.ALL_TRANSPORTS)r&&r.isAvailable()&&i.push(r);dt.globalTransportInitialized_=!0}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}dt.globalTransportInitialized_=!1;class _t{constructor(e,t,n,r,i,s,o,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=a,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Te("c:"+this.id+":"),this.transportManager_=new dt(t),this.log_("Connection created"),this.start_()}start_(){var e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));e=e.healthyTimeout||0;0<e&&(this.healthyTimeout_=He(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(e)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){var t;"t"in e&&("a"===(t=e.t)?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_()))}onSecondaryMessageReceived_(e){var t=Se("t",e),n=Se("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){var t=Se("t",e),n=Se("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){var t=Se("t",e);if("d"in e){var n=e.d;if("h"===t){var r={...n};this.repoInfo_.isUsingEmulator&&(r.h=this.repoInfo_.host),this.onHandshake_(r)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?Ie("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Ie("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&m("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),He(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(6e4))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):He(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){var e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(Pe.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_)&&(this.onDisconnect_(),this.onDisconnect_=null)}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class pt{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class ft{constructor(e){this.allowedEvents_=e,this.listeners_={},f(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){var r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)r[e].callback.apply(r[e].context,n)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);var r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){f(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class gt extends ft{static getInstance(){return new gt}constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||K()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}getInitialEvent(e){return f("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}let mt=32,vt=768;class w{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function C(){return new w("")}function b(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function yt(e){return e.pieces_.length-e.pieceNum_}function T(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new w(e.pieces_,t)}function wt(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function Ct(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function bt(e){if(e.pieceNum_>=e.pieces_.length)return null;var t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new w(t,0)}function I(e,t){var n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof w)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new w(n,0)}function E(e){return e.pieceNum_>=e.pieces_.length}function S(e,t){var n=b(e),r=b(t);if(null===n)return t;if(n===r)return S(T(e),T(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function Tt(e,t){var n=Ct(e,0),r=Ct(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=je(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function It(e,t){if(yt(e)!==yt(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function k(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(yt(e)>yt(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class Et{constructor(e,t){this.errorPrefix_=t,this.parts_=Ct(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=ie(this.parts_[n]);St(this)}}function St(e){if(e.byteLength_>vt)throw new Error(e.errorPrefix_+"has a key path longer than "+vt+" bytes ("+e.byteLength_+").");if(e.parts_.length>mt)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+mt+") or object contains a cycle "+kt(e))}function kt(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class Nt extends ft{static getInstance(){return new Nt}constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}getInitialEvent(e){return f("visible"===e,"Unknown event type: "+e),[this.visible_]}}class Pt extends pt{constructor(e,t,n,r,i,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=Pt.nextPersistentConnectionId_++,this.log_=Te("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=1e3,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a&&!G())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Nt.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&>.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(a(i)),f(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();let n=new _;var t={p:e._path.toString(),q:e._queryObject},t=(this.outstandingGets_.push({action:"g",request:t,onComplete:e=>{var t=e.d;"ok"===e.s?n.resolve(t):n.reject(t)}}),this.outstandingGetCount_++,this.outstandingGets_.length-1);return this.connected_&&this.sendGet_(t),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString(),o=(this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),f(!this.listens.get(s).has(i),"listen() called twice for same path/queryId."),{onComplete:r,hashFn:t,query:e,tag:n});this.listens.get(s).set(i,o),this.connected_&&this.sendListen_(o)}sendGet_(t){let n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(i){let s=i.query,o=s._path.toString(),a=s._queryIdentifier;this.log_("Listen on "+o+" for "+a);var e={p:o};i.tag&&(e.q=s._queryObject,e.t=i.tag),e.h=i.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s,r=(Pt.warnOnListenWarnings_(t,s),this.listens.get(o)&&this.listens.get(o).get(a));r===i&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(o,a),i.onComplete)&&i.onComplete(n,t)})}static warnOnListenWarnings_(e,t){var n,r;e&&"object"==typeof e&&p(e,"w")&&(n=X(e,"w"),Array.isArray(n))&&~n.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),m("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+r+" to your security rules for better performance."))}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){var t;(e&&40===e.length||(e=e,"object"==typeof(t=J(e).claims)&&!0===t.admin))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let r=this.authToken_;n=r;var e=!!(e=J(n).claims)&&"object"==typeof e&&e.hasOwnProperty("iat")?"auth":"gauth",t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}var n,e}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier,i=(this.log_("Unlisten called for "+n+" "+r),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r));i&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);var i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},Math.floor(0))})}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();var s={p:t,d:n},s=(void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++,this.outstandingPuts_.length-1);this.connected_?this.sendPut_(s):this.log_("Buffering put: "+t)}sendPut_(t){let n=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;let r=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,e,e=>{this.log_(n+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+a(e));var t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):Ie("Unrecognized action received from server: "+a(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){f(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=Math.max(0,(new Date).getTime()-this.lastConnectionAttemptTime_),e=Math.max(0,this.reconnectDelay_-e),e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)),this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;var r=this.onDataMessage_.bind(this),i=this.onReady_.bind(this);let e=this.onRealtimeDisconnect_.bind(this);var s=this.id+":"+Pt.nextConnectionId_++,o=this.lastSessionId;let t=!1,n=null;var a=function(){n?n.close():(t=!0,e())},l=(this.realtime_={close:a,sendRequest:function(e){f(n,"sendRequest call when we're not connected not allowed."),n.sendRequest(e)}},this.forceTokenRefresh_);this.forceTokenRefresh_=!1;try{var[h,c]=await Promise.all([this.authTokenProvider_.getToken(l),this.appCheckTokenProvider_.getToken(l)]);t?u("getToken() completed but was canceled"):(u("getToken() completed. Creating connection."),this.authToken_=h&&h.accessToken,this.appCheckToken_=c&&c.token,n=new _t(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,r,i,e,e=>{m(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},o))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&m(e),a())}}}interrupt(e){u("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){u("Resuming connection for reason: "+e),delete this.interruptReasons_[e],Z(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let t=0;t<this.outstandingPuts_.length;t++){var e=this.outstandingPuts_[t];e&&"h"in e.request&&e.queued&&(e.onComplete&&e.onComplete("disconnect"),delete this.outstandingPuts_[t],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>ke(e)).join("$"):"default";var r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n,r=new w(e).toString();let i;return this.listens.has(r)?(n=this.listens.get(r),i=n.get(t),n.delete(t),0===n.size&&this.listens.delete(r)):i=void 0,i}onAuthRevoked_(e,t){u("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,3<=this.invalidAuthTokenCount_&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){u("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,3<=this.invalidAppCheckTokenCount_&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(var e of this.listens.values())for(var t of e.values())this.sendListen_(t);for(let r=0;r<this.outstandingPuts_.length;r++)this.outstandingPuts_[r]&&this.sendPut_(r);for(;this.onDisconnectRequestQueue_.length;){var n=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(n.action,n.pathString,n.data,n.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){var e={};e["sdk.js."+ge.replace(/\./g,"-")]=1,K()?e["framework.cordova"]=1:"object"==typeof navigator&&"ReactNative"===navigator.product&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=gt.getInstance().currentlyOnline();return Z(this.interruptReasons_)&&e}}Pt.nextPersistentConnectionId_=0,Pt.nextConnectionId_=0;class N{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new N(e,t)}}class Rt{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new N(Be,e),r=new N(Be,t);return 0!==this.compare(n,r)}minPost(){return N.MIN}}let xt;class Dt extends Rt{static get __EMPTY_NODE(){return xt}static set __EMPTY_NODE(e){xt=e}compare(e,t){return je(e.name,t.name)}isDefinedOn(e){throw B("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return N.MIN}maxPost(){return new N(Ue,xt)}makePost(e,t){return f("string"==typeof e,"KeyIndex indexValue must always be a string."),new N(e,xt)}toString(){return".key"}}let At=new Dt;class Ot{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,r&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else{if(0===s){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){var e;return 0===this.nodeStack_.length?null:(e=this.nodeStack_[this.nodeStack_.length-1],this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value})}}class P{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:P.RED,this.left=null!=r?r:s.EMPTY_NODE,this.right=null!=i?i:s.EMPTY_NODE}copy(e,t,n,r,i){return new P(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return(r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n))).fixUp_()}removeMin_(){if(this.left.isEmpty())return s.EMPTY_NODE;let e=this;return(e=(e=e.left.isRed_()||e.left.left.isRed_()?e:e.moveRedLeft_()).copy(null,null,null,e.left.removeMin_(),null)).fixUp_()}remove(e,t){let n,r;if(t(e,(n=this).key)<0)n=(n=n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()?n:n.moveRedLeft_()).copy(null,null,null,n.left.remove(e,t),null);else{if(0===t(e,(n=(n=n.left.isRed_()?n.rotateRight_():n).right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()?n:n.moveRedRight_()).key)){if(n.right.isEmpty())return s.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e=(e=(e=e.right.isRed_()&&!e.left.isRed_()?e.rotateLeft_():e).left.isRed_()&&e.left.left.isRed_()?e.rotateRight_():e).left.isRed_()&&e.right.isRed_()?e.colorFlip_():e}moveRedLeft_(){let e=this.colorFlip_();return e=e.right.left.isRed_()?(e=(e=e.copy(null,null,null,null,e.right.rotateRight_())).rotateLeft_()).colorFlip_():e}moveRedRight_(){let e=this.colorFlip_();return e=e.left.left.isRed_()?(e=e.rotateRight_()).colorFlip_():e}rotateLeft_(){var e=this.copy(null,null,P.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,P.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){var e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}P.RED=!0,P.BLACK=!1;class s{constructor(e,t=s.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new s(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,P.BLACK,null,null))}remove(e){return new s(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,P.BLACK,null,null))}get(e){var t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:0<t&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:0<t&&(n=(r=n).right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new Ot(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Ot(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Ot(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Ot(this.root_,null,this.comparator_,!0,e)}}function Lt(e,t){return je(e.name,t.name)}function Mt(e,t){return je(e,t)}s.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new P(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};let Ft;function qt(e){return"number"==typeof e?"number:"+Ve(e):"string:"+e}function Wt(e){var t;e.isLeafNode()?(t=e.val(),f("string"==typeof t||"number"==typeof t||"object"==typeof t&&p(t,".sv"),"Priority must be a string or number.")):f(e===Ft||e.isEmpty(),"priority of unexpected type."),f(e===Ft||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let Bt;class R{static set __childrenNodeConstructor(e){Bt=e}static get __childrenNodeConstructor(){return Bt}constructor(e,t=R.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,f(null!=this.value_,"LeafNode shouldn't be created with null/undefined value."),Wt(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new R(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:R.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return E(e)?this:".priority"===b(e)?this.priorityNode_:R.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:R.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=b(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(f(".priority"!==n||1===yt(e),".priority must be the last token in a path"),this.updateImmediateChild(n,R.__childrenNodeConstructor.EMPTY_NODE.updateChild(T(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+qt(this.priorityNode_.val())+":");var t=typeof this.value_;e=(e+=t+":")+("number"==t?Ve(this.value_):this.value_),this.lazyHash_=be(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===R.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof R.__childrenNodeConstructor?-1:(f(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=R.VALUE_TYPE_ORDER.indexOf(t),i=R.VALUE_TYPE_ORDER.indexOf(n);return f(0<=r,"Unknown leaf type: "+t),f(0<=i,"Unknown leaf type: "+n),r===i?"object"==n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_)}}R.VALUE_TYPE_ORDER=["object","boolean","number","string"];let Ut,jt;class Vt extends Rt{compare(e,t){var n=e.node.getPriority(),r=t.node.getPriority(),n=n.compareTo(r);return 0===n?je(e.name,t.name):n}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return N.MIN}maxPost(){return new N(Ue,new R("[PRIORITY-POST]",jt))}makePost(e,t){var n=Ut(e);return new N(t,new R("[PRIORITY-POST]",n))}toString(){return".priority"}}let x=new Vt,zt=Math.log(2);class Ht{constructor(e){this.count=(t=e+1,parseInt(Math.log(t)/zt,10)),this.current_=this.count-1,t=this.count;var t,n=parseInt(Array(t+1).join("1"),2);this.bits_=e+1&n}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function Qt(l,e,h,t){l.sort(e);let c=function(e,t){var n,r,i=t-e;let s,o;return 0==i?null:1==i?(s=l[e],o=h?h(s):s,new P(o,s.node,P.BLACK,null,null)):(i=parseInt(i/2,10)+e,n=c(e,i),r=c(i+1,t),s=l[i],o=h?h(s):s,new P(o,s.node,P.BLACK,n,r))};var n=(e=>{let s=null,o=null,a=l.length;function t(e,t){var n=a-e,r=a,r=(a-=e,c(1+n,r)),n=l[n],i=h?h(n):n,e=new P(i,n.node,t,null,r);s=(s?s.left=e:o=e,e)}for(let i=0;i<e.count;++i){var n=e.nextBitIsOne(),r=Math.pow(2,e.count-(i+1));n?t(r,P.BLACK):(t(r,P.BLACK),t(r,P.RED))}return o})(new Ht(l.length));return new s(t||e,n)}let Yt,Kt={};class Gt{static get Default(){return f((Kt,x),"ChildrenNode.ts has not been loaded"),Yt=Yt||new Gt({".priority":Kt},{".priority":x})}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){var t=X(this.indexes_,e);if(t)return t instanceof s?t:null;throw new Error("No index defined for "+e)}hasIndex(e){return p(this.indexSet_,e.toString())}addIndex(e,t){f(e!==At,"KeyIndex always exists and isn't meant to be added to the IndexMap.");var n=[];let r=!1;var i=t.getIterator(N.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let o;o=r?Qt(n,e.getCompare()):Kt;var a=e.toString(),l={...this.indexSet_},h=(l[a]=e,{...this.indexes_});return h[a]=o,new Gt(h,l)}addToIndexes(s,o){var e=ee(this.indexes_,(t,e)=>{var n=X(this.indexSet_,e);if(f(n,"Missing index implementation for "+e),t===Kt){if(n.isDefinedOn(s.node)){var r=[],i=o.getIterator(N.Wrap);let e=i.getNext();for(;e;)e.name!==s.name&&r.push(e),e=i.getNext();return r.push(s),Qt(r,n.getCompare())}return Kt}{n=o.get(s.name);let e=t;return(e=n?e.remove(new N(s.name,n)):e).insert(s,s.node)}});return new Gt(e,this.indexSet_)}removeFromIndexes(n,r){var e=ee(this.indexes_,e=>{var t;return e!==Kt&&(t=r.get(n.name))?e.remove(new N(n.name,t)):e});return new Gt(e,this.indexSet_)}}let $t;class D{static get EMPTY_NODE(){return $t=$t||new D(new s(Mt),null,Gt.Default)}constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Wt(this.priorityNode_),this.children_.isEmpty()&&f(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||$t}updatePriority(e){return this.children_.isEmpty()?this:new D(this.children_,e,this.indexMap_)}getImmediateChild(e){var t;return".priority"===e?this.getPriority():null===(t=this.children_.get(e))?$t:t}getChild(e){var t=b(e);return null===t?this:this.getImmediateChild(t).getChild(T(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(f(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new N(n,r);let e,t;t=r.isEmpty()?(e=this.children_.remove(n),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(n,r),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?$t:this.priorityNode_;return new D(e,i,t)}}updateChild(e,t){var n,r=b(e);return null===r?t:(f(".priority"!==b(e)||1===yt(e),".priority must be the last token in a path"),n=this.getImmediateChild(r).updateChild(T(e),t),this.updateImmediateChild(r,n))}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;let r={},i=0,s=0,o=!0;if(this.forEachChild(x,(e,t)=>{r[e]=t.val(n),i++,o&&D.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):o=!1}),!n&&o&&s<2*i){var e,t=[];for(e in r)t[e]=r[e];return t}return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(null===this.lazyHash_){let r="";this.getPriority().isEmpty()||(r+="priority:"+qt(this.getPriority().val())+":"),this.forEachChild(x,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":be(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){var r=this.resolveIndex_(n);return r?(r=r.getPredecessorKey(new N(e,t)))?r.name:null:this.children_.getPredecessorKey(e)}getFirstChildName(e){var t=this.resolveIndex_(e);return t?(t=t.minKey())&&t.name:this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new N(t,this.children_.get(t)):null}getLastChildName(e){var t=this.resolveIndex_(e);return t?(t=t.maxKey())&&t.name:this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new N(t,this.children_.get(t)):null}forEachChild(e,t){var n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(t,n){var e=this.resolveIndex_(n);if(e)return e.getIteratorFrom(t,e=>e);{var r=this.children_.getIteratorFrom(t.name,N.Wrap);let e=r.peek();for(;null!=e&&n.compare(e,t)<0;)r.getNext(),e=r.peek();return r}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,n){var e=this.resolveIndex_(n);if(e)return e.getReverseIteratorFrom(t,e=>e);{var r=this.children_.getReverseIteratorFrom(t.name,N.Wrap);let e=r.peek();for(;null!=e&&0<n.compare(e,t);)r.getNext(),e=r.peek();return r}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===Xt?-1:0}withIndex(e){var t;return e===At||this.indexMap_.hasIndex(e)?this:(t=this.indexMap_.addIndex(e,this.children_),new D(this.children_,this.priorityNode_,t))}isIndexed(e){return e===At||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(!e.isLeafNode()){var n=e;if(this.getPriority().equals(n.getPriority())){if(this.children_.count()!==n.children_.count())return!1;{var r=this.getIterator(x),i=n.getIterator(x);let e=r.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=r.getNext(),t=i.getNext()}return null===e&&null===t}}}return!1}resolveIndex_(e){return e===At?null:this.indexMap_.get(e.toString())}}D.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class Jt extends D{constructor(){super(new s(Mt),D.EMPTY_NODE,Gt.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return D.EMPTY_NODE}isEmpty(){return!1}}let Xt=new Jt,Zt=(Object.defineProperties(N,{MIN:{value:new N(Be,D.EMPTY_NODE)},MAX:{value:new N(Ue,Xt)}}),Dt.__EMPTY_NODE=D.EMPTY_NODE,R.__childrenNodeConstructor=D,e=Xt,Ft=e,e=Xt,jt=e,!0);function A(s,e=null){if(null===s)return D.EMPTY_NODE;var t,n;if("object"==typeof s&&".priority"in s&&(e=s[".priority"]),f(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(s="object"==typeof s&&".value"in s&&null!==s[".value"]?s[".value"]:s)||".sv"in s)return t=s,new R(t,A(e));if(s instanceof Array||!Zt){let r=D.EMPTY_NODE;return v(s,(e,t)=>{var n;!p(s,e)||"."===e.substring(0,1)||!(n=A(t)).isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}),r.updatePriority(A(e))}{let r=[],i=!1;return v(s,(e,t)=>{var n;"."===e.substring(0,1)||(n=A(t)).isEmpty()||(i=i||!n.getPriority().isEmpty(),r.push(new N(e,n)))}),0===r.length?D.EMPTY_NODE:(t=Qt(r,Lt,e=>e.name,Mt),i?(n=Qt(r,x.getCompare()),new D(t,A(e),new Gt({".priority":n},{".priority":x}))):new D(t,A(e),Gt.Default))}}Ut=A;class en extends Rt{constructor(e){super(),this.indexPath_=e,f(!E(e)&&".priority"!==b(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){var n=this.extractChild(e.node),r=this.extractChild(t.node),n=n.compareTo(r);return 0===n?je(e.name,t.name):n}makePost(e,t){var n=A(e),n=D.EMPTY_NODE.updateChild(this.indexPath_,n);return new N(t,n)}maxPost(){var e=D.EMPTY_NODE.updateChild(this.indexPath_,Xt);return new N(Ue,e)}toString(){return Ct(this.indexPath_,0).join("/")}}class tn extends Rt{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?je(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return N.MIN}maxPost(){return N.MAX}makePost(e,t){var n=A(e);return new N(t,n)}toString(){return".value"}}let nn=new tn;function rn(e){return{type:"value",snapshotNode:e}}function sn(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function on(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function an(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class ln{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){f(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");var o=e.getImmediateChild(t);return o.getChild(r).equals(n.getChild(r))&&o.isEmpty()===n.isEmpty()||(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(on(t,o)):f(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(sn(t,n)):s.trackChildChange(an(t,n,o))),e.isLeafNode()&&n.isEmpty())?e:e.updateImmediateChild(t,n).withIndex(this.index_)}updateFullNode(r,n,i){return null!=i&&(r.isLeafNode()||r.forEachChild(x,(e,t)=>{n.hasChild(e)||i.trackChildChange(on(e,t))}),n.isLeafNode()||n.forEachChild(x,(e,t)=>{var n;r.hasChild(e)?(n=r.getImmediateChild(e)).equals(t)||i.trackChildChange(an(e,t,n)):i.trackChildChange(sn(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?D.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class hn{constructor(e){this.indexedFilter_=new ln(e.getIndex()),this.index_=e.getIndex(),this.startPost_=hn.getStartPost_(e),this.endPost_=hn.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){var t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,s){return this.matches(new N(t,n))||(n=D.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?D.EMPTY_NODE:t).withIndex(this.index_),i=(r=r.updatePriority(D.EMPTY_NODE),this);return t.forEachChild(x,(e,t)=>{i.matches(new N(e,t))||(r=r.updateImmediateChild(e,D.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){var t;return e.hasStart()?(t=e.getIndexStartName(),e.getIndex().makePost(e.getIndexStartValue(),t)):e.getIndex().minPost()}static getEndPost_(e){var t;return e.hasEnd()?(t=e.getIndexEndName(),e.getIndex().makePost(e.getIndexEndValue(),t)):e.getIndex().maxPost()}}class cn{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{var t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{var t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new hn(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new N(t,n))||(n=D.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,n,t){let r;if(n.isLeafNode()||n.isEmpty())r=D.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<n.numChildren()&&n.isIndexed(this.index_)){r=D.EMPTY_NODE.withIndex(this.index_);let e,t=(e=this.reverse_?n.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):n.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_),0);for(;e.hasNext()&&t<this.limit_;){var i=e.getNext();if(this.withinDirectionalStart(i)){if(!this.withinDirectionalEnd(i))break;r=r.updateImmediateChild(i.name,i.node),t++}}}else{r=(r=n.withIndex(this.index_)).updatePriority(D.EMPTY_NODE);let e,t=(e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_),0);for(;e.hasNext();){var s=e.getNext();t<this.limit_&&this.withinDirectionalStart(s)&&this.withinDirectionalEnd(s)?t++:r=r.updateImmediateChild(s.name,D.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){let n=this.index_.getCompare();s=(e,t)=>n(t,e)}else s=this.index_.getCompare();var o=e,a=(f(o.numChildren()===this.limit_,""),new N(t,n)),l=this.reverse_?o.getFirstChild(this.index_):o.getLastChild(this.index_),h=this.rangedFilter_.matches(a);if(o.hasChild(t)){var c=o.getImmediateChild(t);let e=r.getChildAfterChild(this.index_,l,this.reverse_);for(;null!=e&&(e.name===t||o.hasChild(e.name));)e=r.getChildAfterChild(this.index_,e,this.reverse_);var u=null==e?1:s(e,a);return h&&!n.isEmpty()&&0<=u?(null!=i&&i.trackChildChange(an(t,n,c)),o.updateImmediateChild(t,n)):(null!=i&&i.trackChildChange(on(t,c)),u=o.updateImmediateChild(t,D.EMPTY_NODE),null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(sn(e.name,e.node)),u.updateImmediateChild(e.name,e.node)):u)}return!n.isEmpty()&&h&&0<=s(l,a)?(null!=i&&(i.trackChildChange(on(l.name,l.node)),i.trackChildChange(sn(t,n))),o.updateImmediateChild(t,n).updateImmediateChild(l.name,D.EMPTY_NODE)):e}}class un{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=x}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return f(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return f(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:Be}hasEnd(){return this.endSet_}getIndexEndValue(){return f(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return f(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Ue}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return f(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===x}copy(){var e=new un;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function dn(e,t,n){var r=e.copy();return r.startSet_=!0,r.indexStartValue_=t=void 0===t?null:t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function _n(e,t,n){var r=e.copy();return r.endSet_=!0,r.indexEndValue_=t=void 0===t?null:t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function pn(e,t){var n=e.copy();return n.index_=t,n}function fn(t){var n,r={};if(!t.isDefault()){let e;e=t.index_===x?"$priority":t.index_===nn?"$value":t.index_===At?"$key":(f(t.index_ instanceof en,"Unrecognized index type!"),t.index_.toString()),r.orderBy=a(e),t.startSet_&&(r[n=t.startAfterSet_?"startAfter":"startAt"]=a(t.indexStartValue_),t.startNameSet_)&&(r[n]+=","+a(t.indexStartName_)),t.endSet_&&(r[n=t.endBeforeSet_?"endBefore":"endAt"]=a(t.indexEndValue_),t.endNameSet_)&&(r[n]+=","+a(t.indexEndName_)),t.limitSet_&&(t.isViewFromLeft()?r.limitToFirst=t.limit_:r.limitToLast=t.limit_)}return r}function gn(t){var n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_),n.sin=!t.startAfterSet_),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_),n.ein=!t.endBeforeSet_),t.limitSet_){n.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),n.vf=e}return t.index_!==x&&(n.i=t.index_.toString()),n}class mn extends pt{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(f(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=Te("p:rest:"),this.listens_={}}listen(e,t,r,i){let s=e._path.toString(),o=(this.log_("Listen called for "+s+" "+e._queryIdentifier),mn.getListenId_(e,r)),a={};this.listens_[o]=a;var n=fn(e._queryParams);this.restRequest_(s+".json",n,(t,e)=>{let n=e;if(null===(t=404===t?n=null:t)&&this.onDataUpdate_(s,n,!1,r),X(this.listens_,o)===a){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=mn.getListenId_(e,t);delete this.listens_[n]}get(e){var t=fn(e._queryParams);let r=e._path.toString(),i=new _;return this.restRequest_(r+".json",t,(e,t)=>{let n=t;null===(e=404===e?n=null:e)?(this.onDataUpdate_(r,n,!1,null),i.resolve(n)):i.reject(new Error(n))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},o){return s.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([e,t])=>{e&&e.accessToken&&(s.auth=e.accessToken),t&&t.token&&(s.ac=t.token);let n=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+(e=>{let t=[];for(let[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""})(s),r=(this.log_("Sending REST request for "+n),new XMLHttpRequest);r.onreadystatechange=()=>{if(o&&4===r.readyState){this.log_("REST Response for "+n+" received. status:",r.status,"response:",r.responseText);let e=null;if(200<=r.status&&r.status<300){try{e=$(r.responseText)}catch(e){m("Failed to parse JSON response for "+n+": "+r.responseText)}o(null,e)}else 401!==r.status&&404!==r.status&&m("Got unsuccessful REST response for "+n+" Status: "+r.status),o(r.status);o=null}},r.open("GET",n,!0),r.send()})}}class vn{constructor(){this.rootNode_=D.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function yn(){return{value:null,children:new Map}}function wn(e,t,n){var r;E(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=b(t),e.children.has(r)||e.children.set(r,yn()),wn(e.children.get(r),t=T(t),n))}function Cn(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{Cn(t,new w(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class bn{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();let n={...e};return this.last_&&v(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class Tn{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new bn(e);var n=1e4+2e4*Math.random();He(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();let n={},r=!1;v(e,(e,t)=>{0<t&&p(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),He(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function In(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function En(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function Sn(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(e=d=d||{})[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class kn{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=d.ACK_USER_WRITE,this.source=In()}operationForChild(e){var t;return E(this.path)?null!=this.affectedTree.value?(f(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this):(t=this.affectedTree.subtree(new w(e)),new kn(C(),t,this.revert)):(f(b(this.path)===e,"operationForChild called for unrelated child."),new kn(T(this.path),this.affectedTree,this.revert))}}class Nn{constructor(e,t){this.source=e,this.path=t,this.type=d.LISTEN_COMPLETE}operationForChild(e){return E(this.path)?new Nn(this.source,C()):new Nn(this.source,T(this.path))}}class Pn{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=d.OVERWRITE}operationForChild(e){return E(this.path)?new Pn(this.source,C(),this.snap.getImmediateChild(e)):new Pn(this.source,T(this.path),this.snap)}}class Rn{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=d.MERGE}operationForChild(e){var t;return E(this.path)?(t=this.children.subtree(new w(e))).isEmpty()?null:t.value?new Pn(this.source,C(),t.value):new Rn(this.source,C(),t):(f(b(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Rn(this.source,T(this.path),this.children))}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class xn{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){var t;return E(e)?this.isFullyInitialized()&&!this.filtered_:(t=b(e),this.isCompleteForChild(t))}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Dn{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function An(n,e,t,r){var i=[];let s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&n.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),On(n,i,"child_removed",e,r,t),On(n,i,"child_added",e,r,t),On(n,i,"child_moved",s,r,t),On(n,i,"child_changed",e,r,t),On(n,i,"value",e,r,t),i}function On(s,o,t,e,a,l){var n=e.filter(e=>e.type===t);n.sort((e,t)=>{var n=s;if(null==e.childName||null==t.childName)throw B("Should only compare child_ events.");var r=new N(e.childName,e.snapshotNode),i=new N(t.childName,t.snapshotNode);return n.index_.compare(r,i)}),n.forEach(t=>{e=s,i=l,"value"!==(r=t).type&&"child_removed"!==r.type&&(r.prevName=i.getPredecessorChildName(r.childName,r.snapshotNode,e.index_));let n=r;var e,r,i;a.forEach(e=>{e.respondsTo(t.type)&&o.push(e.createEvent(n,s.query_))})})}function Ln(e,t){return{eventCache:e,serverCache:t}}function Mn(e,t,n,r){return Ln(new xn(t,n,r),e.serverCache)}function Fn(e,t,n,r){return Ln(e.eventCache,new xn(t,n,r))}function qn(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function Wn(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Bn;class O{static fromObject(e){let n=new O(null);return v(e,(e,t)=>{n=n.set(new w(e),t)}),n}constructor(e,t=Bn=Bn||new s(Ee)){this.value=e,this.children=t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){var n,r;return null!=this.value&&t(this.value)?{path:C(),value:this.value}:!E(e)&&(n=b(e),null!==(r=this.children.get(n)))&&null!=(r=r.findRootMostMatchingPathAndValue(T(e),t))?{path:I(new w(n),r.path),value:r.value}:null}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){var t;return E(e)?this:(t=b(e),null!==(t=this.children.get(t))?t.subtree(T(e)):new O(null))}set(e,t){var n,r;return E(e)?new O(t,this.children):(r=b(e),n=(this.children.get(r)||new O(null)).set(T(e),t),r=this.children.insert(r,n),new O(this.value,r))}remove(t){if(E(t))return this.children.isEmpty()?new O(null):new O(null,this.children);var n=b(t),r=this.children.get(n);if(r){r=r.remove(T(t));let e;return e=r.isEmpty()?this.children.remove(n):this.children.insert(n,r),null===this.value&&e.isEmpty()?new O(null):new O(this.value,e)}return this}get(e){var t;return E(e)?this.value:(t=b(e),(t=this.children.get(t))?t.get(T(e)):null)}setTree(t,n){if(E(t))return n;{var r=b(t),i=(this.children.get(r)||new O(null)).setTree(T(t),n);let e;return e=i.isEmpty()?this.children.remove(r):this.children.insert(r,i),new O(this.value,e)}}fold(e){return this.fold_(C(),e)}fold_(n,r){let i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(I(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,C(),t)}findOnPath_(e,t,n){var r,i=!!this.value&&n(t,this.value);return i||(!E(e)&&(i=b(e),r=this.children.get(i))?r.findOnPath_(T(e),I(t,i),n):null)}foreachOnPath(e,t){return this.foreachOnPath_(e,C(),t)}foreachOnPath_(e,t,n){var r,i;return E(e)?this:(this.value&&n(t,this.value),r=b(e),(i=this.children.get(r))?i.foreachOnPath_(T(e),I(t,r),n):new O(null))}foreach(e){this.foreach_(C(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(I(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class Un{constructor(e){this.writeTree_=e}static empty(){return new Un(new O(null))}}function jn(t,n,r){if(E(n))return new Un(new O(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null==i)return s=new O(r),s=t.writeTree_.setTree(n,s),new Un(s);{var s=i.path;let e=i.value;i=S(s,n);return e=e.updateChild(i,r),new Un(t.writeTree_.set(s,e))}}function Vn(e,n,t){let r=e;return v(t,(e,t)=>{r=jn(r,I(n,e),t)}),r}function zn(e,t){var n;return E(t)?Un.empty():(n=e.writeTree_.setTree(t,new O(null)),new Un(n))}function Hn(e,t){return null!=Qn(e,t)}function Qn(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(S(n.path,t)):null}function Yn(e){let n=[];var t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(x,(e,t)=>{n.push(new N(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new N(e,t.value))}),n}function Kn(e,t){var n;return E(t)?e:null!=(n=Qn(e,t))?new Un(new O(n)):new Un(e.writeTree_.subtree(t))}function Gn(e){return e.writeTree_.isEmpty()}function $n(e,t){return function r(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let n=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(f(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(I(i,e),t,s)}),s=s.getChild(i).isEmpty()||null===n?s:s.updateChild(I(i,".priority"),n)}}}(C(),e.writeTree_,t)}function Jn(e,t){return hr(t,e)}function Xn(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);f(0<=r,"removeWrite called with nonexistent writeId.");let i=t.allWrites[r],s=(t.allWrites.splice(r,1),i.visible),o=!1,a=t.allWrites.length-1;for(;s&&0<=a;){var l=t.allWrites[a];l.visible&&(a>=r&&((e,t)=>{if(e.snap)return k(e.path,t);for(var n in e.children)if(e.children.hasOwnProperty(n)&&k(I(e.path,n),t))return 1})(l,i.path)?s=!1:k(i.path,l.path)&&(o=!0)),a--}return!!s&&(o?((e=t).visibleWrites=er(e.allWrites,Zn,C()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=zn(t.visibleWrites,i.path):v(i.children,e=>{t.visibleWrites=zn(t.visibleWrites,I(i.path,e))}),!0)}function Zn(e){return e.visible}function er(e,t,n){let r=Un.empty();for(let o=0;o<e.length;++o){var i=e[o];if(t(i)){var s=i.path;let e;if(i.snap)k(n,s)?(e=S(n,s),r=jn(r,e,i.snap)):k(s,n)&&(e=S(s,n),r=jn(r,C(),i.snap.getChild(e)));else{if(!i.children)throw B("WriteRecord should have .snap or .children");k(n,s)?(e=S(n,s),r=Vn(r,e,i.children)):k(s,n)&&(E(e=S(s,n))?r=Vn(r,C(),i.children):(s=X(i.children,b(e)))&&(i=s.getChild(T(e)),r=jn(r,C(),i)))}}}return r}function tr(e,t,n,r,i){var s;return r||i?(s=Kn(e.visibleWrites,t),!i&&Gn(s)?n:i||null!=n||Hn(s,C())?$n(er(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(k(e.path,t)||k(t,e.path))},t),n||D.EMPTY_NODE):null):null!=(s=Qn(e.visibleWrites,t))?s:Gn(s=Kn(e.visibleWrites,t))?n:null!=n||Hn(s,C())?$n(s,n||D.EMPTY_NODE):null}function nr(e,t,n,r){return tr(e.writeTree,e.treePath,t,n,r)}function rr(e,t){{var n=e.writeTree;e=e.treePath;let i=D.EMPTY_NODE;var r=Qn(n.visibleWrites,e);if(r)r.isLeafNode()||r.forEachChild(x,(e,t)=>{i=i.updateImmediateChild(e,t)});else if(t){let r=Kn(n.visibleWrites,e);t.forEachChild(x,(e,t)=>{var n=$n(Kn(r,new w(e)),t);i=i.updateImmediateChild(e,n)}),Yn(r).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)})}else Yn(Kn(n.visibleWrites,e)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)});return i}}function ir(e,t,n,r){return i=e.writeTree,e=e.treePath,t=t,n=n,r=r,f(n||r,"Either existingEventSnap or existingServerSnap must exist"),s=I(e,t),Hn(i.visibleWrites,s)?null:Gn(s=Kn(i.visibleWrites,s))?r.getChild(t):$n(s,r.getChild(t));var i,s}function sr(e,t){return n=e.writeTree,e=I(e.treePath,t),Qn(n.visibleWrites,e);var n}function or(e,n,r,i,s,o){{var a=e.writeTree,l=(e=e.treePath,r),h=i;r=s,i=o;let t;var c=Kn(a.visibleWrites,e),u=Qn(c,C());if(null!=u)t=u;else{if(null==n)return[];t=$n(c,n)}if((t=t.withIndex(i)).isEmpty()||t.isLeafNode())return[];{var d=[],_=i.getCompare(),p=r?t.getReverseIteratorFrom(l,i):t.getIteratorFrom(l,i);let e=p.getNext();for(;e&&d.length<h;)0!==_(e,l)&&d.push(e),e=p.getNext();return d}}}function ar(e,t,n){return r=e.writeTree,n=n,i=I(e.treePath,e=t),null!=(s=Qn(r.visibleWrites,i))?s:n.isCompleteForChild(e)?$n(Kn(r.visibleWrites,i),n.getNode().getImmediateChild(e)):null;var r,i,s}function lr(e,t){return hr(I(e.treePath,t),e.writeTree)}function hr(e,t){return{treePath:e,writeTree:t}}class cr{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName,r=(f("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),f(".priority"!==n,"Only non-priority child changes can be tracked."),this.changeMap.get(n));if(r){var i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,an(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,on(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,sn(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw B("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,an(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}let ur=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class dr{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){var t=this.viewCache_.eventCache;return t.isCompleteForChild(e)?t.getNode().getImmediateChild(e):(t=null!=this.optCompleteServerCache_?new xn(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache,ar(this.writes_,e,t))}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:Wn(this.viewCache_),r=or(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function _r(e,t,n,r,i){var s=new cr;let o,a;if(n.type===d.OVERWRITE){var l=n;o=l.source.fromUser?gr(e,t,l.path,l.snap,r,i,s):(f(l.source.fromServer,"Unknown source."),a=l.source.tagged||t.serverCache.isFiltered()&&!E(l.path),fr(e,t,l.path,l.snap,r,i,a,s))}else if(n.type===d.MERGE){var l=n;o=l.source.fromUser?((r,i,s,e,o,a,l)=>{let h=i;return e.foreach((e,t)=>{var n=I(s,e);mr(i,b(n))&&(h=gr(r,h,n,t,o,a,l))}),e.foreach((e,t)=>{var n=I(s,e);mr(i,b(n))||(h=gr(r,h,n,t,o,a,l))}),h})(e,t,l.path,l.children,r,i,s):(f(l.source.fromServer,"Unknown source."),a=l.source.tagged||t.serverCache.isFiltered(),yr(e,t,l.path,l.children,r,i,a,s))}else if(n.type===d.ACK_USER_WRITE){l=n;o=l.revert?((n,r,i,s,e,o)=>{let a;if(null!=sr(s,i))return r;{var l=new dr(s,r,e),h=r.eventCache.getNode();let t;if(E(i)||".priority"===b(i)){let e;e=e=r.serverCache.isFullyInitialized()?nr(s,Wn(r)):(c=r.serverCache.getNode(),f(c instanceof D,"serverChildren would be complete if leaf node"),rr(s,c)),t=n.filter.updateFullNode(h,e,o)}else{var c=b(i);let e=ar(s,c,r.serverCache);null==e&&r.serverCache.isCompleteForChild(c)&&(e=h.getImmediateChild(c)),(t=null!=e?n.filter.updateChild(h,c,e,T(i),l,o):r.eventCache.getNode().hasChild(c)?n.filter.updateChild(h,c,D.EMPTY_NODE,T(i),l,o):h).isEmpty()&&r.serverCache.isFullyInitialized()&&(a=nr(s,Wn(r))).isLeafNode()&&(t=n.filter.updateFullNode(t,a,o))}return a=r.serverCache.isFullyInitialized()||null!=sr(s,C()),Mn(r,t,a,n.filter.filtersNodes())}})(e,t,l.path,r,i,s):((e,t,i,n,s,o,a)=>{if(null!=sr(s,i))return t;let l=t.serverCache.isFiltered(),h=t.serverCache;if(null!=n.value){if(E(i)&&h.isFullyInitialized()||h.isCompleteForPath(i))return fr(e,t,i,h.getNode().getChild(i),s,o,l,a);if(E(i)){let n=new O(null);return h.getNode().forEachChild(At,(e,t)=>{n=n.set(new w(e),t)}),yr(e,t,i,n,s,o,l,a)}return t}{let r=new O(null);return n.foreach((e,t)=>{var n=I(i,e);h.isCompleteForPath(n)&&(r=r.set(e,h.getNode().getChild(n)))}),yr(e,t,i,r,s,o,l,a)}})(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==d.LISTEN_COMPLETE)throw B("Unknown operation type: "+n.type);o=(i=e,e=n.path,n=r,r=s,l=t.serverCache,l=Fn(t,l.getNode(),l.isFullyInitialized()||E(e),l.isFiltered()),pr(i,l,e,n,ur,r))}var h,c,s=s.getChanges(),i=t,e=o,n=s,u=e.eventCache;return u.isFullyInitialized()&&(h=u.getNode().isLeafNode()||u.getNode().isEmpty(),c=qn(i),0<n.length||!i.eventCache.isFullyInitialized()||h&&!u.getNode().equals(c)||!u.getNode().getPriority().equals(c.getPriority()))&&n.push(rn(qn(e))),{viewCache:o,changes:s}}function pr(r,i,s,o,a,l){var h=i.eventCache;if(null!=sr(o,s))return i;{let t,n;if(E(s))f(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(c=rr(o,(c=Wn(i))instanceof D?c:D.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),c,l)):(c=nr(o,Wn(i)),r.filter.updateFullNode(i.eventCache.getNode(),c,l));else{var c=b(s);if(".priority"===c){f(1===yt(s),"Can't have a priority with additional path components");var u=h.getNode(),d=ir(o,s,u,n=i.serverCache.getNode());t=null!=d?r.filter.updatePriority(u,d):h.getNode()}else{u=T(s);let e;e=h.isCompleteForChild(c)?(n=i.serverCache.getNode(),null!=(d=ir(o,s,h.getNode(),n))?h.getNode().getImmediateChild(c).updateChild(u,d):h.getNode().getImmediateChild(c)):ar(o,c,i.serverCache),t=null!=e?r.filter.updateChild(h.getNode(),c,e,u,a,l):h.getNode()}}return Mn(i,t,h.isFullyInitialized()||E(s),r.filter.filtersNodes())}}function fr(e,t,n,r,i,s,o,a){var l=t.serverCache;let h;var c=o?e.filter:e.filter.getIndexedFilter();if(E(n))h=c.updateFullNode(l.getNode(),r,null);else if(c.filtersNodes()&&!l.isFiltered()){var u=l.getNode().updateChild(n,r);h=c.updateFullNode(l.getNode(),u,null)}else{u=b(n);if(!l.isCompleteForPath(n)&&1<yt(n))return t;var d=T(n),_=l.getNode().getImmediateChild(u).updateChild(d,r);h=".priority"===u?c.updatePriority(l.getNode(),_):c.updateChild(l.getNode(),u,_,d,ur,null)}u=Fn(t,h,l.isFullyInitialized()||E(n),c.filtersNodes());return pr(e,u,n,i,new dr(i,u,s),a)}function gr(t,n,r,i,e,s,o){var a=n.eventCache;let l,h;var c=new dr(e,n,s);if(E(r))h=t.filter.updateFullNode(n.eventCache.getNode(),i,o),l=Mn(n,h,!0,t.filter.filtersNodes());else{var u=b(r);if(".priority"===u)h=t.filter.updatePriority(n.eventCache.getNode(),i),l=Mn(n,h,a.isFullyInitialized(),a.isFiltered());else{var d,_=T(r),p=a.getNode().getImmediateChild(u);let e;e=E(_)?i:null!=(d=c.getCompleteChild(u))?".priority"===wt(_)&&d.getChild(bt(_)).isEmpty()?d:d.updateChild(_,i):D.EMPTY_NODE,l=p.equals(e)?n:Mn(n,t.filter.updateChild(a.getNode(),u,e,_,c,o),a.isFullyInitialized(),t.filter.filtersNodes())}}return l}function mr(e,t){return e.eventCache.isCompleteForChild(t)}function vr(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function yr(r,i,e,t,s,o,a,l){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let h=i,n,c=(n=E(e)?t:new O(null).setTree(e,t),i.serverCache.getNode());return n.children.inorderTraversal((e,t)=>{var n;c.hasChild(e)&&(n=vr(0,i.serverCache.getNode().getImmediateChild(e),t),h=fr(r,h,new w(e),n,s,o,a,l))}),n.children.inorderTraversal((e,t)=>{var n=!i.serverCache.isCompleteForChild(e)&&null===t.value;c.hasChild(e)||n||(n=vr(0,i.serverCache.getNode().getImmediateChild(e),t),h=fr(r,h,new w(e),n,s,o,a,l))}),h}class wr{constructor(e,t){this.query_=e,this.eventRegistrations_=[];var n=this.query_._queryParams,r=new ln(n.getIndex()),n=(e=n).loadsAllData()?new ln(e.getIndex()):new(e.hasLimit()?cn:hn)(e),i=(this.processor_={filter:n},t.serverCache),s=t.eventCache,o=r.updateFullNode(D.EMPTY_NODE,i.getNode(),null),a=n.updateFullNode(D.EMPTY_NODE,s.getNode(),null),o=new xn(o,i.isFullyInitialized(),r.filtersNodes()),i=new xn(a,s.isFullyInitialized(),n.filtersNodes());this.viewCache_=Ln(i,o),this.eventGenerator_=new Dn(this.query_)}get query(){return this.query_}}function Cr(e){return 0===e.eventRegistrations_.length}function br(r,i,s){let o=[];if(s){f(null==i,"A cancel should cancel all event registrations.");let n=r.query._path;r.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(s,n);t&&o.push(t)})}if(i){let e=[];for(let t=0;t<r.eventRegistrations_.length;++t){var n=r.eventRegistrations_[t];if(n.matches(i)){if(i.hasAnyCallback()){e=e.concat(r.eventRegistrations_.slice(t+1));break}}else e.push(n)}r.eventRegistrations_=e}else r.eventRegistrations_=[];return o}function Tr(e,t,n,r){t.type===d.MERGE&&null!==t.source.queryId&&(f(Wn(e.viewCache_),"We should always have a full cache before handling merges"),f(qn(e.viewCache_),"Missing event cache, even though we have a server cache"));var i=e.viewCache_,s=_r(e.processor_,i,t,n,r);return t=e.processor_,n=s.viewCache,f(n.eventCache.getNode().isIndexed(t.filter.getIndex()),"Event snap not indexed"),f(n.serverCache.getNode().isIndexed(t.filter.getIndex()),"Server snap not indexed"),f(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,Ir(e,s.changes,s.viewCache.eventCache.getNode(),null)}function Ir(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return An(e.eventGenerator_,t,n,i)}let Er;class Sr{constructor(){this.views=new Map}}function kr(t,n,r,i){var e=n.source.queryId;if(null!==e)return e=t.views.get(e),f(null!=e,"SyncTree gave us an op for an invalid query."),Tr(e,n,r,i);{let e=[];for(var s of t.views.values())e=e.concat(Tr(s,n,r,i));return e}}function Nr(e,n,r,i,s){var o=n._queryIdentifier,o=e.views.get(o);if(o)return o;{let e=nr(r,s?i:null),t=!1;t=!!e||(e=i instanceof D?rr(r,i):D.EMPTY_NODE,!1);o=Ln(new xn(e,t,!1),new xn(i,s,!1));return new wr(n,o)}}function Pr(e,t,r,i,s,n){var o=Nr(e,t,i,s,n);e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),o.eventRegistrations_.push(r);{s=r,o=(i=o).viewCache_.eventCache;let n=[];return o.getNode().isLeafNode()||o.getNode().forEachChild(x,(e,t)=>{n.push(sn(e,t))}),o.isFullyInitialized()&&n.push(rn(o.getNode())),Ir(i,n,o.getNode(),s)}}function Rr(e,t,n,r){var i=t._queryIdentifier,s=[];let o=[];var a=Lr(e);if("default"===i)for(var[l,h]of e.views.entries())o=o.concat(br(h,n,r)),Cr(h)&&(e.views.delete(l),h.query._queryParams.loadsAllData()||s.push(h.query));else{var c=e.views.get(i);c&&(o=o.concat(br(c,n,r)),Cr(c))&&(e.views.delete(i),c.query._queryParams.loadsAllData()||s.push(c.query))}return a&&!Lr(e)&&s.push((f(Er,"Reference.ts has not been loaded"),new Er(t._repo,t._path))),{removed:s,events:o}}function xr(e){var t,n=[];for(t of e.views.values())t.query._queryParams.loadsAllData()||n.push(t);return n}function Dr(e,t){let n=null;for(var r of e.views.values())n=n||(i=r,s=t,r=void 0,(r=Wn(i.viewCache_))&&(i.query._queryParams.loadsAllData()||!E(s)&&!r.getImmediateChild(b(s)).isEmpty())?r.getChild(s):null);var i,s;return n}function Ar(e,t){var n;return t._queryParams.loadsAllData()?Mr(e):(n=t._queryIdentifier,e.views.get(n))}function Or(e,t){return null!=Ar(e,t)}function Lr(e){return null!=Mr(e)}function Mr(e){for(var t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Fr;let qr=1;class Wr{constructor(e){this.listenProvider_=e,this.syncPointTree_=new O(null),this.pendingWriteTree_={visibleWrites:Un.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Br(e,t,n,r,i){var s,o,a,l;return s=e.pendingWriteTree_,o=t,a=n,r=r,l=i,f(r>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:o,snap:a,writeId:r,visible:l=void 0===l?!0:l}),l&&(s.visibleWrites=jn(s.visibleWrites,o,a)),s.lastWriteId=r,i?Gr(e,new Pn(In(),t,n)):[]}function Ur(e,t,n,r){i=e.pendingWriteTree_,s=t,o=n,r=r,f(r>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:o,writeId:r,visible:!0}),i.visibleWrites=Vn(i.visibleWrites,s,o),i.lastWriteId=r;var i,s,o,a=O.fromObject(n);return Gr(e,new Rn(In(),t,a))}function jr(e,t,n=!1){var r=((e,t)=>{for(let r=0;r<e.allWrites.length;r++){var n=e.allWrites[r];if(n.writeId===t)return n}return null})(e.pendingWriteTree_,t);if(Xn(e.pendingWriteTree_,t)){let t=new O(null);return null!=r.snap?t=t.set(C(),!0):v(r.children,e=>{t=t.set(new w(e),!0)}),Gr(e,new kn(r.path,t,n))}return[]}function Vr(e,t,n){return Gr(e,new Pn(En(),t,n))}function zr(n,t,r,i,s=!1){var o=t._path,a=n.syncPointTree_.get(o);let l=[];if(a&&("default"===t._queryIdentifier||Or(a,t))){var h=Rr(a,t,r,i),a=(0===a.views.size&&(n.syncPointTree_=n.syncPointTree_.remove(o)),h.removed);if(l=h.events,!s){var h=-1!==a.findIndex(e=>e._queryParams.loadsAllData()),c=n.syncPointTree_.findOnPath(o,(e,t)=>Lr(t));if(h&&!c){o=n.syncPointTree_.subtree(o);if(!o.isEmpty()){var u=o.fold((e,t,r)=>{if(t&&Lr(t))return[Mr(t)];{let n=[];return t&&(n=xr(t)),v(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<u.length;++e){var d=u[e],_=d.query,d=Jr(n,d);n.listenProvider_.startListening(ri(_),Xr(n,_),d.hashFn,d.onComplete)}}}!c&&0<a.length&&!i&&(h?n.listenProvider_.stopListening(ri(t),null):a.forEach(e=>{var t=n.queryToTagMap.get(Zr(e));n.listenProvider_.stopListening(ri(e),t)}))}var p=n,f=a;for(let e=0;e<f.length;++e){var g,m=f[e];m._queryParams.loadsAllData()||(m=Zr(m),g=p.queryToTagMap.get(m),p.queryToTagMap.delete(m),p.tagToQueryMap.delete(g))}}return l}function Hr(e,t,n,r){var i,s,o=ei(e,r);return null!=o?(i=(o=ti(o)).path,o=o.queryId,s=S(i,t),ni(e,i,new Pn(Sn(o),s,n))):[]}function Qr(e,t,n,r=!1){let i=t._path,s=null,o=!1,a=(e.syncPointTree_.foreachOnPath(i,(e,t)=>{var n=S(e,i);s=s||Dr(t,n),o=o||Lr(t)}),e.syncPointTree_.get(i));a?(o=o||Lr(a),s=s||Dr(a,C())):(a=new Sr,e.syncPointTree_=e.syncPointTree_.set(i,a));let l;null!=s?l=!0:(l=!1,s=D.EMPTY_NODE,e.syncPointTree_.subtree(i).foreachChild((e,t)=>{var n=Dr(t,C());n&&(s=s.updateImmediateChild(e,n))}));var h,c=Or(a,t),u=(c||t._queryParams.loadsAllData()||(h=Zr(t),f(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),u=qr++,e.queryToTagMap.set(h,u),e.tagToQueryMap.set(u,h)),Jn(e.pendingWriteTree_,i));let d=Pr(a,t,n,u,s,l);return c||o||r||(h=Ar(a,t),d=d.concat(((t,e,n)=>{var r=e._path,i=Xr(t,e),s=Jr(t,n),s=t.listenProvider_.startListening(ri(e),i,s.hashFn,s.onComplete),r=t.syncPointTree_.subtree(r);if(i)f(!Lr(r.value),"If we're adding a query, it shouldn't be shadowed");else{var o=r.fold((e,t,r)=>{if(!E(e)&&t&&Lr(t))return[Mr(t).query];{let n=[];return t&&(n=n.concat(xr(t).map(e=>e.query))),v(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<o.length;++e){var a=o[e];t.listenProvider_.stopListening(ri(a),Xr(t,a))}}return s})(e,t,h))),d}function Yr(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=Dr(t,S(e,r));if(n)return n});return tr(n,r,i,t,!0)}function Kr(e,t){let r=t._path,i=null,n=(e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=S(e,r);i=i||Dr(t,n)}),e.syncPointTree_.get(r));n?i=i||Dr(n,C()):(n=new Sr,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i,o=s?new xn(i,!0,!1):null,a=Jn(e.pendingWriteTree_,t._path);return qn(Nr(n,t,a,s?o.getNode():D.EMPTY_NODE,s).viewCache_)}function Gr(e,t){return function o(t,a,l,h){{if(E(t.path))return $r(t,a,l,h);{let e=a.get(C()),n=(null==l&&null!=e&&(l=Dr(e,C())),[]),r=b(t.path),i=t.operationForChild(r),s=a.children.get(r);if(s&&i){let e=l?l.getImmediateChild(r):null,t=lr(h,r);n=n.concat(o(i,s,e,t))}return n=e?n.concat(kr(e,t,h,l)):n}}}(t,e.syncPointTree_,null,Jn(e.pendingWriteTree_,C()))}function $r(s,e,o,a){var t=e.get(C());null==o&&null!=t&&(o=Dr(t,C()));let l=[];return e.children.inorderTraversal((e,t)=>{var n=o?o.getImmediateChild(e):null,r=lr(a,e),i=s.operationForChild(e);i&&(l=l.concat($r(i,t,n,r)))}),l=t?l.concat(kr(t,s,a,o)):l}function Jr(a,e){let l=e.query,h=Xr(a,l);return{hashFn:()=>(e.viewCache_.serverCache.getNode()||D.EMPTY_NODE).hash(),onComplete:e=>{var t,n,r,i,s,o;return"ok"===e?h?(t=a,n=l._path,r=h,(o=ei(t,r))?(i=(o=ti(o)).path,o=o.queryId,s=S(i,n),ni(t,i,new Nn(Sn(o),s))):[]):(r=a,n=l._path,Gr(r,new Nn(En(),n))):(i=((e,t)=>{let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");var r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r})(e,l),zr(a,l,null,i))}}}function Xr(e,t){var n=Zr(t);return e.queryToTagMap.get(n)}function Zr(e){return e._path.toString()+"$"+e._queryIdentifier}function ei(e,t){return e.tagToQueryMap.get(t)}function ti(e){var t=e.indexOf("$");return f(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new w(e.substr(0,t))}}function ni(e,t,n){var r=e.syncPointTree_.get(t),i=(f(r,"Missing sync point for query tag that we're tracking"),Jn(e.pendingWriteTree_,t));return kr(r,n,i,null)}function ri(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(f(Fr,"Reference.ts has not been loaded"),new Fr(e._repo,e._path)):e}class ii{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new ii(t)}node(){return this.node_}}class si{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=I(this.path_,e);return new si(this.syncTree_,t)}node(){return Yr(this.syncTree_,this.path_)}}let oi=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},ai=function(e,t,n){return e&&"object"==typeof e?(f(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?li(e[".sv"],t,n):"object"==typeof e[".sv"]?hi(e[".sv"],t):void f(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},li=function(e,t,n){if("timestamp"===e)return n.timestamp;f(!1,"Unexpected server value: "+e)},hi=function(e,t,n){e.hasOwnProperty("increment")||f(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment,i=("number"!=typeof r&&f(!1,"Unexpected increment value: "+r),t.node());return f(null!=i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode()||"number"!=typeof(i=i.getValue())?r:i+r},ci=function(e,t,n,r){return di(t,new si(n,e),r)},ui=function(e,t,n){return di(e,new ii(t),n)};function di(e,r,i){var t,n,s=e.getPriority().val(),s=ai(s,r.getImmediateChild(".priority"),i);let o;return e.isLeafNode()?(n=e,(t=ai(n.getValue(),r,i))!==n.getValue()||s!==n.getPriority().val()?new R(t,A(s)):e):(n=e,s!==(o=n).getPriority().val()&&(o=o.updatePriority(new R(s))),n.forEachChild(x,(e,t)=>{var n=di(t,r.getImmediateChild(e),i);n!==t&&(o=o.updateImmediateChild(e,n))}),o)}class _i{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function pi(e,t){let n=t instanceof w?t:new w(t),r=e,i=b(n);for(;null!==i;){var s=X(r.node.children,i)||{children:{},childCount:0};r=new _i(i,r,s),n=T(n),i=b(n)}return r}function fi(e){return e.node.value}function gi(e,t){e.node.value=t,wi(e)}function mi(e){return 0<e.node.childCount}function vi(n,r){v(n.node.children,(e,t)=>{r(new _i(e,n,t))})}function yi(e){return new w(null===e.parent?e.name:yi(e.parent)+"/"+e.name)}function wi(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=(e=>void 0===fi(e)&&!mi(e))(e=e),i=p(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,wi(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,wi(t)))}function Ci(e,t,n,r){r&&void 0===t||Ai(h(e,"value"),t,n)}function bi(e,t,s,n){if(!n||void 0!==t){let r=h(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(r+" must be an object containing the children to replace.");let i=[];v(t,(e,t)=>{var n=new w(e);if(Ai(r,t,I(s,n)),".priority"===wt(n)&&!Di(t))throw new Error(r+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");i.push(n)});{var o=r;var a=i;let t,n;for(t=0;t<a.length;t++){var l=Ct(n=a[t]);for(let e=0;e<l.length;e++)if((".priority"!==l[e]||e!==l.length-1)&&!Pi(l[e]))throw new Error(o+"contains an invalid key ("+l[e]+") in path "+n.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}a.sort(Tt);let e=null;for(t=0;t<a.length;t++){if(n=a[t],null!==e&&k(e,n))throw new Error(o+"contains a path "+e.toString()+" that is ancestor of another path "+n.toString());e=n}}}}function Ti(e,t,n){if(!n||void 0!==t){if(We(t))throw new Error(h(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Di(t))throw new Error(h(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function Ii(e,t,n,r){if(!(r&&void 0===n||Pi(n)))throw new Error(h(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function Ei(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),Oi(e,t,n,r)}function L(e,t){if(".info"===b(t))throw new Error(e+" failed = Can't modify data under /.info/")}let Si=/[\[\].#$\/\u0000-\u001F\u007F]/,ki=/[\[\].#$\u0000-\u001F\u007F]/,Ni=10485760,Pi=function(e){return"string"==typeof e&&0!==e.length&&!Si.test(e)},Ri=function(e){return"string"==typeof e&&0!==e.length&&!ki.test(e)},xi=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),Ri(e)},Di=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!We(e)||e&&"object"==typeof e&&p(e,".sv")},Ai=function(o,e,t){let a=t instanceof w?new Et(t,o):t;if(void 0===e)throw new Error(o+"contains undefined "+kt(a));if("function"==typeof e)throw new Error(o+"contains a function "+kt(a)+" with contents = "+e.toString());if(We(e))throw new Error(o+"contains "+e.toString()+" "+kt(a));if("string"==typeof e&&e.length>Ni/3&&ie(e)>Ni)throw new Error(o+"contains a string greater than "+Ni+" utf8 bytes "+kt(a)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(v(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!Pi(e)))throw new Error(o+" contains an invalid key ("+e+") "+kt(a)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n,r;n=a,e=e,0<n.parts_.length&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=ie(e),St(n),Ai(o,t,a),e=a,r=e.parts_.pop(),e.byteLength_-=ie(r),0<e.parts_.length&&--e.byteLength_}),i&&s)throw new Error(o+' contains ".value" child '+kt(a)+" in addition to actual children.")}},Oi=function(e,t,n,r){if(!(r&&void 0===n||Ri(n)))throw new Error(h(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},Li=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!Pi(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!xi(n))throw new Error(h(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class Mi{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Fi(e,t){let n=null;for(let s=0;s<t.length;s++){var r=t[s],i=r.getPath();null===n||It(i,n.path)||(e.eventLists_.push(n),n=null),(n=null===n?{events:[],path:i}:n).events.push(r)}n&&e.eventLists_.push(n)}function qi(e,t,n){Fi(e,n),Wi(e,e=>It(e,t))}function M(e,t,n){Fi(e,n),Wi(e,e=>k(e,t)||k(t,e))}function Wi(t,e){t.recursionDepth_++;let n=!0;for(let a=0;a<t.eventLists_.length;a++){var r=t.eventLists_[a];if(r)if(e(r.path)){s=o=i=void 0;var i=t.eventLists_[a];for(let e=0;e<i.events.length;e++){var s,o=i.events[e];null!==o&&(i.events[e]=null,s=o.getEventRunner(),Oe&&u("event: "+o.toString()),Ge(s))}t.eventLists_[a]=null}else n=!1}n&&(t.eventLists_=[]),t.recursionDepth_--}let Bi="repo_interrupt",Ui=25;class ji{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Mi,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=yn(),this.transactionQueueTree_=new _i,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function Vi(o,e,t){if(o.stats_=at(o.repoInfo_),o.forceRestClient_||0<=("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i))o.server_=new mn(o.repoInfo_,(e,t,n,r)=>{Qi(o,e,t,n,r)},o.authTokenProvider_,o.appCheckProvider_),setTimeout(()=>Yi(o,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{a(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}o.persistentConnection_=new Pt(o.repoInfo_,e,(e,t,n,r)=>{Qi(o,e,t,n,r)},e=>{Yi(o,e)},e=>{var n;n=o,v(e,(e,t)=>{Ki(n,e,t)})},o.authTokenProvider_,o.appCheckProvider_,t),o.server_=o.persistentConnection_}var n;o.authTokenProvider_.addTokenChangeListener(e=>{o.server_.refreshAuthToken(e)}),o.appCheckProvider_.addTokenChangeListener(e=>{o.server_.refreshAppCheckToken(e.token)}),o.statsReporter_=(e=()=>new Tn(o.stats_,o.server_),n=o.repoInfo_.toString(),ot[n]||(ot[n]=e()),ot[n]),o.infoData_=new vn,o.infoSyncTree_=new Wr({startListening:(e,t,n,r)=>{let i=[];var s=o.infoData_.getNode(e._path);return s.isEmpty()||(i=Vr(o.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),Ki(o,"connected",!1),o.serverSyncTree_=new Wr({startListening:(r,e,t,i)=>(o.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);M(o.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{o.server_.unlisten(e,t)}})}function zi(e){var t=e.infoData_.getNode(new w(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function Hi(e){return oi({timestamp:zi(e)})}function Qi(e,t,n,r,i){e.dataUpdateCount++;var s,o,a,l,h,c,u=new w(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let d=[],_=u;0<(d=i?r?(c=ee(n,e=>A(e)),t=e.serverSyncTree_,s=u,o=c,(c=ei(t,i))?(a=(c=ti(c)).path,c=c.queryId,l=S(a,s),h=O.fromObject(o),ni(t,a,new Rn(Sn(c),l,h))):[]):(a=A(n),Hr(e.serverSyncTree_,u,a,i)):r?(c=ee(n,e=>A(e)),s=e.serverSyncTree_,o=u,t=c,l=O.fromObject(t),Gr(s,new Rn(En(),o,l))):(h=A(n),Vr(e.serverSyncTree_,u,h))).length&&(_=ss(e,u)),M(e.eventQueue_,_,d)}function Yi(e,t){if(Ki(e,"connected",t),!1===t){var o=e;ts(o,"onDisconnectEvents");let r=Hi(o),i=yn(),s=(Cn(o.onDisconnect_,C(),(e,t)=>{var n=ci(e,t,o.serverSyncTree_,r);wn(i,e,n)}),[]);Cn(i,C(),(e,t)=>{s=s.concat(Vr(o.serverSyncTree_,e,t));var n=hs(o,e);ss(o,n)}),o.onDisconnect_=yn(),M(o.eventQueue_,C(),s)}}function Ki(e,t,n){var r=new w("/.info/"+t),i=A(n),i=(e.infoData_.updateSnapshot(r,i),Vr(e.infoSyncTree_,r,i));M(e.eventQueue_,r,i)}function Gi(e){return e.nextWriteId_++}function $i(r,i,e,t,s){ts(r,"set",{path:i.toString(),value:e,priority:t});var n=Hi(r),o=A(e,t),a=Yr(r.serverSyncTree_,i),a=ui(o,a,n);let l=Gi(r);n=Br(r.serverSyncTree_,i,a,l,!0),Fi(r.eventQueue_,n),r.server_.put(i.toString(),o.val(!0),(e,t)=>{var n="ok"===e,n=(n||m("set at "+i+" failed: "+e),jr(r.serverSyncTree_,l,!n));M(r.eventQueue_,i,n),ns(0,s,e,t)}),a=hs(r,i);ss(r,a),M(r.eventQueue_,a,[])}function Ji(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){var r;return E(t)?(n.value=null,n.children.clear(),!0):null!==n.value?!n.value.isLeafNode()&&(r=n.value,n.value=null,r.forEachChild(x,(e,t)=>{wn(n,new w(e),t)}),e(n,t)):!(0<n.children.size)||(r=b(t),t=T(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size)}(n.onDisconnect_,r),ns(0,i,e,t)})}function Xi(n,r,e,i){let s=A(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&wn(n.onDisconnect_,r,s),ns(0,i,e,t)})}function Zi(e,t,n){let r;r=".info"===b(t._path)?zr(e.infoSyncTree_,t,n):zr(e.serverSyncTree_,t,n),qi(e.eventQueue_,t._path,r)}function es(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Bi)}function ts(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),u(n,...t)}function ns(e,r,i,s){r&&Ge(()=>{if("ok"===i)r(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);var n=new Error(e);n.code=t,r(n)}})}function rs(e,t,n){return Yr(e.serverSyncTree_,t,n)||D.EMPTY_NODE}function is(a,l=a.transactionQueueTree_){if(l||ls(a,l),fi(l)){var h=as(a,l),e=(f(0<h.length,"Sending zero length transaction queue"),h.every(e=>0===e.status));if(e){var c=a;var u=yi(l);var d=h;let e=d.map(e=>e.currentWriteId),t=rs(c,u,e),n=t,r=t.hash();for(let o=0;o<d.length;o++){var _=d[o],p=(f(0===_.status,"tryToSendTransactionQueue_: items in queue should all be run."),_.status=1,_.retryCount++,S(u,_.path));n=n.updateChild(p,_.currentOutputSnapshotRaw)}let i=n.val(!0),s=u;c.server_.put(s.toString(),i,t=>{ts(c,"transaction put response",{path:s.toString(),status:t});let n=[];if("ok"===t){var r=[];for(let e=0;e<d.length;e++)d[e].status=2,n=n.concat(jr(c.serverSyncTree_,d[e].currentWriteId)),d[e].onComplete&&r.push(()=>d[e].onComplete(null,!0,d[e].currentOutputSnapshotResolved)),d[e].unwatcher();ls(c,pi(c.transactionQueueTree_,u)),is(c,c.transactionQueueTree_),M(c.eventQueue_,u,n);for(let t=0;t<r.length;t++)Ge(r[t])}else{if("datastale"===t)for(let e=0;e<d.length;e++)3===d[e].status?d[e].status=4:d[e].status=0;else{m("transaction at "+s.toString()+" failed: "+t);for(let e=0;e<d.length;e++)d[e].status=4,d[e].abortReason=t}ss(c,u)}},r)}}else mi(l)&&vi(l,e=>{is(a,e)})}function ss(e,t){var n=os(e,t),r=yi(n),n=as(e,n),i=e,s=n,o=r;if(0!==s.length){var a=[];let n=[];var l=s.filter(e=>0===e.status).map(e=>e.currentWriteId);for(let r=0;r<s.length;r++){var h=s[r],c=S(o,h.path);let e=!1,t;if(f(null!==c,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(jr(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=Ui)e=!0,t="maxretry",n=n.concat(jr(i.serverSyncTree_,h.currentWriteId,!0));else{var c=rs(i,h.path,l),u=(h.currentInputSnapshot=c,s[r].update(c.val()));if(void 0!==u){Ai("transaction failed: Data returned ",u,h.path);let e=A(u);"object"==typeof u&&null!=u&&p(u,".priority")||(e=e.updatePriority(c.getPriority()));var u=h.currentWriteId,d=Hi(i),c=ui(e,c,d);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=Gi(i),l.splice(l.indexOf(u),1),n=(n=n.concat(Br(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally))).concat(jr(i.serverSyncTree_,u,!0))}else e=!0,t="nodata",n=n.concat(jr(i.serverSyncTree_,h.currentWriteId,!0))}M(i.eventQueue_,o,n),n=[],e&&(s[r].status=2,(e=>{setTimeout(e,Math.floor(0))})(s[r].unwatcher),s[r].onComplete)&&("nodata"===t?a.push(()=>s[r].onComplete(null,!1,s[r].currentInputSnapshot)):a.push(()=>s[r].onComplete(new Error(t),!1,null)))}ls(i,i.transactionQueueTree_);for(let e=0;e<a.length;e++)Ge(a[e]);is(i,i.transactionQueueTree_)}return r}function os(e,t){let n,r=e.transactionQueueTree_;for(n=b(t);null!==n&&void 0===fi(r);)r=pi(r,n),t=T(t),n=b(t);return r}function as(e,t){var n=[];return function t(n,e,r){let i=fi(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);vi(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function ls(t,n){var r=fi(n);if(r){let e=0;for(let t=0;t<r.length;t++)2!==r[t].status&&(r[e]=r[t],e++);r.length=e,gi(n,0<r.length?r:void 0)}vi(n,e=>{ls(t,e)})}function hs(t,e){var n=yi(os(t,e)),r=pi(t.transactionQueueTree_,e);return((e,t,n)=>{let r=n?e:e.parent;for(;null!==r;){if(t(r))return;r=r.parent}})(r,e=>{cs(t,e)}),cs(t,r),function t(e,n,r,i){r&&!i&&n(e),vi(e,e=>{t(e,n,!0,i)}),r&&i&&n(e)}(r,e=>{cs(t,e)}),n}function cs(i,s){var o=fi(s);if(o){var a=[];let e=[],t=-1;for(let n=0;n<o.length;n++)3!==o[n].status&&(1===o[n].status?(f(t===n-1,"All SENT items should be at beginning of queue."),o[t=n].status=3,o[n].abortReason="set"):(f(0===o[n].status,"Unexpected transaction status in abort"),o[n].unwatcher(),e=e.concat(jr(i.serverSyncTree_,o[n].currentWriteId,!0)),o[n].onComplete&&a.push(o[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?gi(s,void 0):o.length=t+1,M(i.eventQueue_,yi(s),e);for(let r=0;r<a.length;r++)Ge(a[r])}}let us=function(e,t){var n=ds(e),r=n.namespace,i=("firebase.com"===n.domain&&Fe(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||Fe("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||qe(),"ws"===n.scheme||"wss"===n.scheme);return{repoInfo:new nt(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new w(n.pathString)}},ds=function(r){let i="",s="",o="",a="",l="",h=!0,c="https",u=443;if("string"==typeof r){let e=r.indexOf("//"),t=(0<=e&&(c=r.substring(0,e-1),r=r.substring(e+2)),r.indexOf("/")),n=(-1===t&&(t=r.length),r.indexOf("?"));-1===n&&(n=r.length),i=r.substring(0,Math.min(t,n)),t<n&&(a=(e=>{let t="";var n=e.split("/");for(let r=0;r<n.length;r++)if(0<n[r].length){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t})(r.substring(t,n)));var d=(e=>{var t,n,r={};for(t of(e="?"===e.charAt(0)?e.substring(1):e).split("&"))0!==t.length&&(2===(n=t.split("=")).length?r[decodeURIComponent(n[0])]=decodeURIComponent(n[1]):m(`Invalid query segment '${t}' in query '${e}'`));return r})(r.substring(Math.min(r.length,n))),_=(0<=(e=i.indexOf(":"))?(h="https"===c||"wss"===c,u=parseInt(i.substring(e+1),10)):e=i.length,i.slice(0,e));"localhost"===_.toLowerCase()?s="localhost":_.split(".").length<=2?s=_:(_=i.indexOf("."),o=i.substring(0,_).toLowerCase(),s=i.substring(_+1),l=o),"ns"in d&&(l=d.ns)}return{host:i,port:u,domain:s,subdomain:o,secure:h,scheme:c,pathString:a,namespace:l}},_s="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ps=(()=>{let s=0,o=[];return function(e){var t=e===s;s=e;let n;var r=new Array(8);for(n=7;0<=n;n--)r[n]=_s.charAt(e%64),e=Math.floor(e/64);f(0===e,"Cannot push at time == 0");let i=r.join("");if(t){for(n=11;0<=n&&63===o[n];n--)o[n]=0;o[n]++}else for(n=0;n<12;n++)o[n]=Math.floor(64*Math.random());for(n=0;n<12;n++)i+=_s.charAt(o[n]);return f(20===i.length,"nextPushId: Length should be 20."),i}})();class fs{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+a(this.snapshot.exportVal())}}class gs{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class ms{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return f(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class vs{constructor(e,t){this._repo=e,this._path=t}cancel(){var e=new _;return Ji(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){L("OnDisconnect.remove",this._path);var e=new _;return Xi(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){L("OnDisconnect.set",this._path),Ci("OnDisconnect.set",e,this._path,!1);var t=new _;return Xi(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){L("OnDisconnect.setWithPriority",this._path),Ci("OnDisconnect.setWithPriority",e,this._path,!1),Ti("OnDisconnect.setWithPriority",t,!1);var r=new _;{var i=this._repo,s=this._path,o=r.wrapCallback(()=>{});let n=A(e,t);i.server_.onDisconnectPut(s.toString(),n.val(!0),(e,t)=>{"ok"===e&&wn(i.onDisconnect_,s,n),ns(0,o,e,t)})}return r.promise}update(e){L("OnDisconnect.update",this._path),bi("OnDisconnect.update",e,this._path,!1);var r,i,n,s,t=new _;return r=this._repo,i=this._path,n=e,s=t.wrapCallback(()=>{}),Z(n)?(u("onDisconnect().update() called with empty data. Don't do anything."),ns(0,s,"ok",void 0)):r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&v(n,(e,t)=>{var n=A(t);wn(r.onDisconnect_,I(i,e),n)}),ns(0,s,e,t)}),t.promise}}class i{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return E(this._path)?null:wt(this._path)}get ref(){return new bs(this._repo,this._path)}get _queryIdentifier(){var e=gn(this._queryParams),e=ke(e);return"{}"===e?"default":e}get _queryObject(){return gn(this._queryParams)}isEqual(e){var t,n,r;return(e=g(e))instanceof i&&(t=this._repo===e._repo,n=It(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier,t)&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+(e=>{let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"})(this._path)}}function ys(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function ws(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===At){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==Be)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==Ue)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===x){if(null!=t&&!Di(t)||null!=n&&!Di(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(f(e.getIndex()instanceof en||e.getIndex()===nn,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function Cs(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class bs extends i{constructor(e,t){super(e,t,new un,!1)}get parent(){var e=bt(this._path);return null===e?null:new bs(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class Ts{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){var t=new w(e),n=Ss(this.ref,e);return new Ts(this._node.getChild(t),n,x)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){return!this._node.isLeafNode()&&!!this._node.forEachChild(this._index,(e,t)=>n(new Ts(t,Ss(this.ref,e),x)))}hasChild(e){var t=new w(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function Is(e,t){return(e=g(e))._checkNotDeleted("ref"),void 0!==t?Ss(e._root,t):e._root}function Es(e,t){(e=g(e))._checkNotDeleted("refFromURL");var n=us(t,e._repo.repoInfo_.nodeAdmin),r=(Li("refFromURL",n),n.repoInfo);return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||Fe("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),Is(e,n.path.toString())}function Ss(e,t){return(null===b((e=g(e))._path)?Ei:Oi)("child","path",t,!1),new bs(e._repo,I(e._path,t))}function ks(e,t){e=g(e),L("set",e._path),Ci("set",t,e._path,!1);var n=new _;return $i(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function Ns(e,t){bi("update",t,e._path,!1);var i=new _;{var o=e._repo,a=e._path,l=(e=t,i.wrapCallback(()=>{}));ts(o,"update",{path:a.toString(),value:e});let n=!0,r=Hi(o),s={};if(v(e,(e,t)=>{n=!1,s[e]=ci(I(a,e),A(t),o.serverSyncTree_,r)}),n)u("update() called with empty data. Don't do anything."),ns(0,l,"ok",void 0);else{let i=Gi(o);var h=Ur(o.serverSyncTree_,a,s,i);Fi(o.eventQueue_,h),o.server_.merge(a.toString(),e,(e,t)=>{var n="ok"===e,n=(n||m("update at "+a+" failed: "+e),jr(o.serverSyncTree_,i,!n)),r=0<n.length?ss(o,a):a;M(o.eventQueue_,r,n),ns(0,l,e,t)}),v(e,e=>{var t=hs(o,I(a,e));ss(o,t)}),M(o.eventQueue_,a,[])}}return i.promise}function Ps(t){t=g(t);var i,s,o,e=new ms(()=>{}),e=new Rs(e);return i=t._repo,s=t,o=e,(null!=(e=Kr(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,n=A(e).withIndex(s._queryParams.getIndex());Qr(i.serverSyncTree_,s,o,!0);let r;return r=s._queryParams.loadsAllData()?Vr(i.serverSyncTree_,s._path,n):(t=Xr(i.serverSyncTree_,s),Hr(i.serverSyncTree_,s._path,n,t)),M(i.eventQueue_,s._path,r),zr(i.serverSyncTree_,s,o,null,!0),n},e=>(ts(i,"get for query "+a(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new Ts(e,new bs(t._repo,t._path),t._queryParams.getIndex()))}class Rs{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new fs("value",this,new Ts(e.snapshotNode,new bs(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new gs(this,e,t):null}matches(e){return e instanceof Rs&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class xs{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){var t="children_added"===e?"child_added":e;return this.eventType===("children_removed"===t?"child_removed":t)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new gs(this,e,t):null}createEvent(e,t){f(null!=e.childName,"Child events should have a childName.");var n=Ss(new bs(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new fs(e.type,this,new Ts(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof xs&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function Ds(r,e,t,n,i){let s;if("object"==typeof n&&(s=void 0,i=n),"function"==typeof n&&(s=n),i&&i.onlyOnce){let n=t;var o=(e,t)=>{Zi(r._repo,r,a),n(e,t)};o.userCallback=t.userCallback,o.context=t.context,t=o}o=new ms(t,s||void 0);let a="value"===e?new Rs(o):new xs(e,o);{n=r._repo,i=r,t=a;let e;e=".info"===b(i._path)?Qr(n.infoSyncTree_,i,t):Qr(n.serverSyncTree_,i,t),qi(n.eventQueue_,i._path,e)}return()=>Zi(r._repo,r,a)}function As(e,t,n,r){return Ds(e,"value",t,n,r)}function Os(e,t,n,r){Ds(e,"child_added",t,n,r)}function Ls(e,t,n,r){Ds(e,"child_changed",t,n,r)}function Ms(e,t,n,r){Ds(e,"child_moved",t,n,r)}function Fs(e,t,n,r){Ds(e,"child_removed",t,n,r)}function qs(e,t,n){let r=null;var i=n?new ms(n):null;"value"===t?r=new Rs(i):t&&(r=new xs(t,i)),Zi(e._repo,e,r)}class Ws{}class Bs extends Ws{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){Ci("endAt",this._value,e._path,!0);var t=_n(e._queryParams,this._value,this._key);if(Cs(t),ws(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class Us extends Ws{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){Ci("endBefore",this._value,e._path,!1);var t=((e,t,n)=>{let r;return(r=e.index_===At||n?_n(e,t,n):_n(e,t,Be)).endBeforeSet_=!0,r})(e._queryParams,this._value,this._key);if(Cs(t),ws(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class js extends Ws{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){Ci("startAt",this._value,e._path,!0);var t=dn(e._queryParams,this._value,this._key);if(Cs(t),ws(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class Vs extends Ws{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){Ci("startAfter",this._value,e._path,!1);var t=((e,t,n)=>{let r;return(r=e.index_===At||n?dn(e,t,n):dn(e,t,Ue)).startAfterSet_=!0,r})(e._queryParams,this._value,this._key);if(Cs(t),ws(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class zs extends Ws{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new i(e._repo,e._path,(t=e._queryParams,n=this._limit,(r=t.copy()).limitSet_=!0,r.limit_=n,r.viewFrom_="l",r),e._orderByCalled);var t,n,r}}class Hs extends Ws{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new i(e._repo,e._path,(t=e._queryParams,n=this._limit,(r=t.copy()).limitSet_=!0,r.limit_=n,r.viewFrom_="r",r),e._orderByCalled);var t,n,r}}class Qs extends Ws{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){ys(e,"orderByChild");var t=new w(this._path);if(E(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new en(t),t=pn(e._queryParams,t);return ws(t),new i(e._repo,e._path,t,!0)}}class Ys extends Ws{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){ys(e,"orderByKey");var t=pn(e._queryParams,At);return ws(t),new i(e._repo,e._path,t,!0)}}class Ks extends Ws{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){ys(e,"orderByPriority");var t=pn(e._queryParams,x);return ws(t),new i(e._repo,e._path,t,!0)}}class Gs extends Ws{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){ys(e,"orderByValue");var t=pn(e._queryParams,nn);return ws(t),new i(e._repo,e._path,t,!0)}}class $s extends Ws{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(Ci("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new Bs(this._value,this._key)._apply(new js(this._value,this._key)._apply(e))}}function Js(e,...t){let n=g(e);for(var r of t)n=r._apply(n);return n}e=bs,f(!Er,"__referenceConstructor has already been defined"),Er=e,e=bs,f(!Fr,"__referenceConstructor has already been defined"),Fr=e;let Xs="FIREBASE_DATABASE_EMULATOR_HOST",Zs={},eo=!1;function to(e,t,n,r,i){let s=r||e.options.databaseURL,o=(void 0===s&&(e.options.projectId||Fe("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),u("Using default host for project ",e.options.projectId),s=e.options.projectId+"-default-rtdb.firebaseio.com"),us(s,i)),a=o.repoInfo,l,h=void 0;(h="undefined"!=typeof process&&process.env?process.env[Xs]:h)?(l=!0,s=`http://${h}?ns=`+a.namespace,o=us(s,i),a=o.repoInfo):l=!o.repoInfo.secure;var c=i&&l?new Xe(Xe.OWNER):new Je(e.name,e.options,t),c=(Li("Invalid Firebase Database URL",o),E(o.path)||Fe("Database URL must point to the root of a Firebase Database (not including a child path)."),((e,t,n,r)=>{let i=Zs[t.name];var s;return i||(i={},Zs[t.name]=i),(s=i[e.toURLString()])&&Fe("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new ji(e,eo,n,r),i[e.toURLString()]=s})(a,e,c,new $e(e,n)));return new no(c,e)}class no{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Vi(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new bs(this._repo,C())),this._rootInternal}_delete(){var e,t,n;return null!==this._rootInternal&&(e=this._repo,t=this.app.name,(n=Zs[t])&&n[e.key]===e||Fe(`Database ${t}(${e.repoInfo_}) has already been deleted.`),es(e),delete n[e.key],this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&Fe("Cannot call "+e+" on a deleted database.")}}function ro(){dt.IS_TRANSPORT_INITIALIZED&&m("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function io(){ro(),ht.forceDisallow()}function so(){ro(),y.forceDisallow(),ht.forceAllow()}function oo(e,t,n,r={}){(e=g(e))._checkNotDeleted("useEmulator");var i,s=t+":"+n,o=e._repoInternal;if(e._instanceStarted){if(s===e._repoInternal.repoInfo_.host&&function e(t,n){if(t!==n){var r,i,s=Object.keys(t),o=Object.keys(n);for(r of s){if(!o.includes(r))return;var a=t[r],l=n[r];if(te(a)&&te(l)){if(!e(a,l))return}else if(a!==l)return}for(i of o)if(!s.includes(i))return}return 1}(r,o.repoInfo_.emulatorOptions))return;Fe("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let a=void 0;o.repoInfo_.nodeAdmin?(r.mockUserToken&&Fe('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),a=new Xe(Xe.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:((e,t)=>{if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(i)return n={iss:"https://securetoken.google.com/"+n,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}},...e},[z(JSON.stringify({alg:"none",type:"JWT"})),z(JSON.stringify(n)),""].join(".");throw new Error("mockUserToken must contain 'sub' or 'user_id' field!")})(r.mockUserToken,e.app.options.projectId),a=new Xe(i)),se(t)&&(async e=>(await fetch(e,{credentials:"include"})).ok)(t),n=o,e=s,t=r,r=a,i=e.lastIndexOf(":"),i=se(e.substring(0,i)),n.repoInfo_=new nt(e,i,n.repoInfo_.namespace,n.repoInfo_.webSocketOnly,n.repoInfo_.nodeAdmin,n.repoInfo_.persistenceKey,n.repoInfo_.includeNamespaceInQueryParams,!0,t),r&&(n.authTokenProvider_=r)}function ao(e){(e=g(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(Bi)}function lo(e,t){Me(e,t)}let ho={".sv":"timestamp"};class co{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function uo(i,e,t){if(i=g(i),L("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var n=t?.applyLocally??!0;let s=new _;var r=As(i,()=>{}),t=i._repo,o=i._path,a=(e,t,n)=>{var r;e?s.reject(e):(r=new Ts(n,new bs(i._repo,i._path),x),s.resolve(new co(t,r)))},l=r,h=n;ts(t,"transaction on "+o);var c,r={path:o,update:e,onComplete:a,status:null,order:De(),applyLocally:h,retryCount:0,unwatcher:l,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},n=rs(t,o,void 0);if(r.currentInputSnapshot=n,void 0===(c=r.update(n.val())))r.unwatcher(),r.currentOutputSnapshotRaw=null,r.currentOutputSnapshotResolved=null,r.onComplete&&r.onComplete(null,!1,r.currentInputSnapshot);else{Ai("transaction failed: Data returned ",c,r.path),r.status=0;var u=pi(t.transactionQueueTree_,o),d=fi(u)||[];d.push(r),gi(u,d);let e;"object"==typeof c&&null!==c&&p(c,".priority")?(e=X(c,".priority"),f(Di(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):(u=Yr(t.serverSyncTree_,o)||D.EMPTY_NODE,e=u.getPriority().val());d=Hi(t),u=A(c,e),c=ui(u,n,d),n=(r.currentOutputSnapshotRaw=u,r.currentOutputSnapshotResolved=c,r.currentWriteId=Gi(t),Br(t.serverSyncTree_,o,c,r.currentWriteId,r.applyLocally));M(t.eventQueue_,o,n),is(t,t.transactionQueueTree_)}return s.promise}Pt.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},Pt.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},me(bo.SDK_VERSION),bo._registerComponent(new oe("database",(e,{instanceIdentifier:t})=>to(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t),"PUBLIC").setMultipleInstances(!0)),bo.registerVersion(fe,"1.1.3",Ce),bo.registerVersion(fe,"1.1.3","esm2020");function _o(e){var t="FIREBASE WARNING: "+e;po.warn(t)}let po=new pe("@firebase/database-compat");class fo{constructor(e){this._delegate=e}cancel(t){l("OnDisconnect.cancel",0,1,arguments.length),c("OnDisconnect.cancel","onComplete",t,!0);var e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){l("OnDisconnect.remove",0,1,arguments.length),c("OnDisconnect.remove","onComplete",t,!0);var e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){l("OnDisconnect.set",1,2,arguments.length),c("OnDisconnect.set","onComplete",t,!0);var n=this._delegate.set(e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){l("OnDisconnect.setWithPriority",2,3,arguments.length),c("OnDisconnect.setWithPriority","onComplete",n,!0);var r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(t,n){if(l("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){var r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,_o("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}c("OnDisconnect.update","onComplete",n,!0);var e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class go{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return l("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class mo{constructor(e,t){this._database=e,this._delegate=t}val(){return l("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return l("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return l("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return l("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return l("DataSnapshot.child",0,1,arguments.length),e=String(e),Oi("DataSnapshot.child","path",e,!1),new mo(this._database,this._delegate.child(e))}hasChild(e){return l("DataSnapshot.hasChild",1,1,arguments.length),Oi("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return l("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return l("DataSnapshot.forEach",1,1,arguments.length),c("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new mo(this._database,e)))}hasChildren(){return l("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return l("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return l("DataSnapshot.ref",0,0,arguments.length),new o(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class F{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){l("Query.on",2,4,arguments.length),c("Query.on","callback",n,!1);let i=F.getCancelAndContextArgs_("Query.on",t,r);var s=(e,t)=>{n.call(i.context,new mo(this.database,e),t)},o=(s.userCallback=n,s.context=i.context,i.cancel?.bind(i.context));switch(e){case"value":return As(this._delegate,s,o),n;case"child_added":return Os(this._delegate,s,o),n;case"child_removed":return Fs(this._delegate,s,o),n;case"child_changed":return Ls(this._delegate,s,o),n;case"child_moved":return Ms(this._delegate,s,o),n;default:throw new Error(h("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){l("Query.off",0,3,arguments.length);var r,i="Query.off",s=e,o=!0;if(!o||void 0!==s)switch(s){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(h(i,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}c("Query.off","callback",t,!0),re("Query.off","context",n,!0),t?((r=()=>{}).userCallback=t,r.context=n,qs(this._delegate,e,r)):qs(this._delegate,e)}get(){return Ps(this._delegate).then(e=>new mo(this.database,e))}once(e,r,t,n){l("Query.once",1,4,arguments.length),c("Query.once","callback",r,!0);let i=F.getCancelAndContextArgs_("Query.once",t,n),s=new _;var o=(e,t)=>{var n=new mo(this.database,e);r&&r.call(i.context,n,t),s.resolve(n)},a=(o.userCallback=r,o.context=i.context,e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)});switch(e){case"value":As(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":Os(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":Fs(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":Ls(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":Ms(this._delegate,o,a,{onlyOnce:!0});break;default:throw new Error(h("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return l("Query.limitToFirst",1,1,arguments.length),new F(this.database,Js(this._delegate,(e=>{if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new zs(e)})(e)))}limitToLast(e){return l("Query.limitToLast",1,1,arguments.length),new F(this.database,Js(this._delegate,(e=>{if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Hs(e)})(e)))}orderByChild(e){return l("Query.orderByChild",1,1,arguments.length),new F(this.database,Js(this._delegate,(e=>{if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return Oi("orderByChild","path",e,!1),new Qs(e)})(e)))}orderByKey(){return l("Query.orderByKey",0,0,arguments.length),new F(this.database,Js(this._delegate,new Ys))}orderByPriority(){return l("Query.orderByPriority",0,0,arguments.length),new F(this.database,Js(this._delegate,new Ks))}orderByValue(){return l("Query.orderByValue",0,0,arguments.length),new F(this.database,Js(this._delegate,new Gs))}startAt(e=null,t){return l("Query.startAt",0,2,arguments.length),new F(this.database,Js(this._delegate,([e=null,t]=[e,t],Ii("startAt","key",t,!0),new js(e,t))))}startAfter(e=null,t){return l("Query.startAfter",0,2,arguments.length),new F(this.database,Js(this._delegate,(e=e,t=t,Ii("startAfter","key",t,!0),new Vs(e,t))))}endAt(e=null,t){return l("Query.endAt",0,2,arguments.length),new F(this.database,Js(this._delegate,(e=e,t=t,Ii("endAt","key",t,!0),new Bs(e,t))))}endBefore(e=null,t){return l("Query.endBefore",0,2,arguments.length),new F(this.database,Js(this._delegate,(e=e,t=t,Ii("endBefore","key",t,!0),new Us(e,t))))}equalTo(e,t){return l("Query.equalTo",1,2,arguments.length),new F(this.database,Js(this._delegate,(e=e,t=t,Ii("equalTo","key",t,!0),new $s(e,t))))}toString(){return l("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return l("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(l("Query.isEqual",1,1,arguments.length),e instanceof F)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,n){var r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,c(e,"cancel",r.cancel,!0),r.context=n,re(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(h(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new o(this.database,new bs(this._delegate._repo,this._delegate._path))}}class o extends F{constructor(e,t){super(e,new i(t._repo,t._path,new un,!1)),this.database=e,this._delegate=t}getKey(){return l("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return l("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new o(this.database,Ss(this._delegate,e))}getParent(){l("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new o(this.database,e):null}getRoot(){return l("Reference.root",0,0,arguments.length),new o(this.database,this._delegate.root)}set(e,t){l("Reference.set",1,2,arguments.length),c("Reference.set","onComplete",t,!0);var n=ks(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(l("Reference.update",1,2,arguments.length),Array.isArray(t)){var r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,_o("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}L("Reference.update",this._delegate._path),c("Reference.update","onComplete",n,!0);var e=Ns(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){l("Reference.setWithPriority",2,3,arguments.length),c("Reference.setWithPriority","onComplete",n,!0);var r=((e,t,n)=>{if(L("setWithPriority",e._path),Ci("setWithPriority",t,e._path,!1),Ti("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";var r=new _;return $i(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise})(this._delegate,e,t);return n&&r.then(()=>n(null),e=>n(e)),r}remove(t){l("Reference.remove",0,1,arguments.length),c("Reference.remove","onComplete",t,!0);e=this._delegate,L("remove",e._path);var e,n=ks(e,null);return t&&n.then(()=>t(null),e=>t(e)),n}transaction(e,t,n){l("Reference.transaction",1,3,arguments.length),c("Reference.transaction","transactionUpdate",e,!1),c("Reference.transaction","onComplete",t,!0);var r,i="Reference.transaction",s="applyLocally",o=n,a=!0;if(a&&void 0===o||"boolean"==typeof o)return r=uo(this._delegate,e,{applyLocally:n}).then(e=>new go(e.committed,new mo(this.database,e.snapshot))),t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r;throw new Error(h(i,s)+"must be a boolean.")}setPriority(e,t){l("Reference.setPriority",1,2,arguments.length),c("Reference.setPriority","onComplete",t,!0);n=this._delegate,e=e,n=g(n),L("setPriority",n._path),Ti("setPriority",e,!1),r=new _,$i(n._repo,I(n._path,".priority"),e,null,r.wrapCallback(()=>{}));var n,r=r.promise;return t&&r.then(()=>t(null),e=>t(e)),r}push(e,t){l("Reference.push",0,2,arguments.length),c("Reference.push","onComplete",t,!0);var n=((e,t)=>{e=g(e),L("push",e._path),Ci("push",t,e._path,!0);var n=zi(e._repo),n=ps(n),r=Ss(e,n);let i=Ss(e,n),s;return s=null!=t?ks(i,t).then(()=>i):Promise.resolve(i),r.then=s.then.bind(s),r.catch=s.then.bind(s,void 0),r})(this._delegate,e),r=n.then(e=>new o(this.database,e)),n=(t&&r.then(()=>t(null),e=>t(e)),new o(this.database,n));return n.then=r.then.bind(r),n.catch=r.catch.bind(r,void 0),n}onDisconnect(){return L("Reference.onDisconnect",this._delegate._path),new fo(new vs(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class vo{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:io,forceLongPolling:so}}useEmulator(e,t,n={}){oo(this._delegate,e,t,n)}ref(e){var t;return l("database.ref",0,1,arguments.length),e instanceof o?(t=Es(this._delegate,e.toString()),new o(this,t)):(t=Is(this._delegate,e),new o(this,t))}refFromURL(e){l("database.refFromURL",1,1,arguments.length);var t=Es(this._delegate,e);return new o(this,t)}goOffline(){var e;l("database.goOffline",0,0,arguments.length),(e=g(e=this._delegate))._checkNotDeleted("goOffline"),es(e._repo)}goOnline(){return l("database.goOnline",0,0,arguments.length),ao(this._delegate)}}vo.ServerValue={TIMESTAMP:ho,increment:e=>({".sv":{increment:e}})};var e,yo=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,customAppCheckImpl:i,namespace:s,nodeAdmin:o=!1}){me(n);var a=new he("database-standalone"),l=new le("auth-internal",a);l.setComponent(new oe("auth-internal",()=>r,"PRIVATE"));let h=void 0;return i&&(h=new le("app-check-internal",a)).setComponent(new oe("app-check-internal",()=>i,"PRIVATE")),{instance:new vo(to(e,l,h,t,o),e),namespace:s}}});let wo=vo.ServerValue;(e=q.default).INTERNAL.registerComponent(new oe("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new vo(r,n)},"PUBLIC").setServiceProps({Reference:o,Query:F,Database:vo,DataSnapshot:mo,enableLogging:lo,INTERNAL:yo,ServerValue:wo}).setMultipleInstances(!0)),e.registerVersion("@firebase/database-compat","2.1.4")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-database-compat.js - be sure to load firebase-app.js first.")}});
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as n,_isFirebaseServerApp as r,SDK_VERSION as i}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";const o=!1,s="${JSCORE_VERSION}",assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+s+") INTERNAL ASSERT FAILED: "+e)},stringToByteArray$1=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++r)),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t},a={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const i=e[t],o=t+1<e.length,s=o?e[t+1]:0,a=t+2<e.length,l=a?e[t+2]:0,h=i>>2,c=(3&i)<<4|s>>4;let d=(15&s)<<2|l>>6,u=63&l;a||(u=64,o||(d=64)),r.push(n[h],n[c],n[d],n[u])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(stringToByteArray$1(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const i=e[n++];if(i<128)t[r++]=String.fromCharCode(i);else if(i>191&&i<224){const o=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&o)}else if(i>239&&i<365){const o=((7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(o>>10)),t[r++]=String.fromCharCode(56320+(1023&o))}else{const o=e[n++],s=e[n++];t[r++]=String.fromCharCode((15&i)<<12|(63&o)<<6|63&s)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const i=n[e.charAt(t++)],o=t<e.length?n[e.charAt(t)]:0;++t;const s=t<e.length?n[e.charAt(t)]:64;++t;const a=t<e.length?n[e.charAt(t)]:64;if(++t,null==i||null==o||null==s||null==a)throw new DecodeBase64StringError;const l=i<<2|o>>4;if(r.push(l),64!==s){const e=o<<4&240|s>>2;if(r.push(e),64!==a){const e=s<<6&192|a;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64Encode=function(e){const t=stringToByteArray$1(e);return a.encodeByteArray(t,!0)},base64urlEncodeWithoutPadding=function(e){return base64Encode(e).replace(/\./g,"")},base64Decode=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function deepCopy(e){return deepExtend(void 0,e)}function deepExtend(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=deepExtend(e[n],t[n]));return e}const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&base64Decode(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>getDefaults()?.emulatorHosts?.[e])(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]};class Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}function isMobileCordova(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(function getUA(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}())}function isNodeSdk(){return!0===o}function jsonEval(e){return JSON.parse(e)}function stringify(e){return JSON.stringify(e)}const decode=function(e){let t={},n={},r={},i="";try{const o=e.split(".");t=jsonEval(base64Decode(o[0])||""),n=jsonEval(base64Decode(o[1])||""),i=o[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}};function contains(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function safeGet(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function isEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function map(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const i of n){if(!r.includes(i))return!1;const n=e[i],o=t[i];if(isObject(n)&&isObject(o)){if(!deepEqual(n,o))return!1}else if(n!==o)return!1}for(const e of r)if(!n.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}class Sha1{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(e,t){t||(t=0);const n=this.W_;if("string"==typeof e)for(let r=0;r<16;r++)n[r]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let r=0;r<16;r++)n[r]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let e=16;e<80;e++){const t=n[e-3]^n[e-8]^n[e-14]^n[e-16];n[e]=4294967295&(t<<1|t>>>31)}let r,i,o=this.chain_[0],s=this.chain_[1],a=this.chain_[2],l=this.chain_[3],h=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(r=l^s&(a^l),i=1518500249):(r=s^a^l,i=1859775393):e<60?(r=s&a|l&(s|a),i=2400959708):(r=s^a^l,i=3395469782);const t=(o<<5|o>>>27)+r+h+i+n[e]&4294967295;h=l,l=a,a=4294967295&(s<<30|s>>>2),s=o,o=t}this.chain_[0]=this.chain_[0]+o&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+l&4294967295,this.chain_[4]=this.chain_[4]+h&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let r=0;const i=this.buf_;let o=this.inbuf_;for(;r<t;){if(0===o)for(;r<=n;)this.compress_(e,r),r+=this.blockSize;if("string"==typeof e){for(;r<t;)if(i[o]=e.charCodeAt(r),++o,++r,o===this.blockSize){this.compress_(i),o=0;break}}else for(;r<t;)if(i[o]=e[r],++o,++r,o===this.blockSize){this.compress_(i),o=0;break}}this.inbuf_=o,this.total_+=t}digest(){const e=[];let t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let e=this.blockSize-1;e>=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let r=24;r>=0;r-=8)e[n]=this.chain_[t]>>r&255,++n;return e}}function errorPrefix(e,t){return`${e} failed: ${t} argument `}const stringLength=function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);r<128?t++:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t};function getModularInstance(e){return e&&e._delegate?e._delegate:e}function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const l="[DEFAULT]";class Provider{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new Deferred;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){const t=this.normalizeInstanceIdentifier(e?.identifier),n=e?.optional??!1;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function isComponentEager(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:l})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=l){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return null!=this.component}isInitialized(e=l){return this.instances.has(e)}getOptions(e=l){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries()){n===this.normalizeInstanceIdentifier(e)&&t.resolve(r)}return r}onInit(e,t){const n=this.normalizeInstanceIdentifier(t),r=this.onInitCallbacks.get(n)??new Set;r.add(e),this.onInitCallbacks.set(n,r);const i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e,r===l?void 0:r),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch{}var r;return n||null}normalizeInstanceIdentifier(e=l){return this.component?this.component.multipleInstances?e:l:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class ComponentContainer{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new Provider(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}var h;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(h||(h={}));const c={debug:h.DEBUG,verbose:h.VERBOSE,info:h.INFO,warn:h.WARN,error:h.ERROR,silent:h.SILENT},d=h.INFO,u={[h.DEBUG]:"log",[h.VERBOSE]:"log",[h.INFO]:"info",[h.WARN]:"warn",[h.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),i=u[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)};const p="@firebase/database",_="1.1.3";let m="";function setSDKVersion(e){m=e}class DOMStorageWrapper{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),stringify(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:jsonEval(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class MemoryStorage{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return contains(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const createStoragefor=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new DOMStorageWrapper(t)}}catch(e){}return new MemoryStorage},f=createStoragefor("localStorage"),y=createStoragefor("sessionStorage"),g=new class Logger{constructor(e){this.name=e,this._logLevel=d,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in h))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?c[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,h.DEBUG,...e),this._logHandler(this,h.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,h.VERBOSE,...e),this._logHandler(this,h.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,h.INFO,...e),this._logHandler(this,h.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,h.WARN,...e),this._logHandler(this,h.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,h.ERROR,...e),this._logHandler(this,h.ERROR,...e)}}("@firebase/database"),v=function(){let e=1;return function(){return e++}}(),sha1=function(e){const t=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){const t=i-55296;r++,assert(r<e.length,"Surrogate pair missing trail surrogate."),i=65536+(t<<10)+(e.charCodeAt(r)-56320)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):i<65536?(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t}(e),n=new Sha1;n.update(t);const r=n.digest();return a.encodeByteArray(r)},buildLogMessage_=function(...e){let t="";for(let n=0;n<e.length;n++){const r=e[n];Array.isArray(r)||r&&"object"==typeof r&&"number"==typeof r.length?t+=buildLogMessage_.apply(null,r):t+="object"==typeof r?stringify(r):r,t+=" "}return t};let C=null,w=!0;const enableLogging$1=function(e,t){assert(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(g.logLevel=h.VERBOSE,C=g.log.bind(g),t&&y.set("logging_enabled",!0)):"function"==typeof e?C=e:(C=null,y.remove("logging_enabled"))},log=function(...e){if(!0===w&&(w=!1,null===C&&!0===y.get("logging_enabled")&&enableLogging$1(!0)),C){const t=buildLogMessage_.apply(null,e);C(t)}},logWrapper=function(e){return function(...t){log(e,...t)}},error=function(...e){const t="FIREBASE INTERNAL ERROR: "+buildLogMessage_(...e);g.error(t)},fatal=function(...e){const t=`FIREBASE FATAL ERROR: ${buildLogMessage_(...e)}`;throw g.error(t),new Error(t)},warn=function(...e){const t="FIREBASE WARNING: "+buildLogMessage_(...e);g.warn(t)},isInvalidJSONNumber=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},T="[MIN_NAME]",E="[MAX_NAME]",nameCompare=function(e,t){if(e===t)return 0;if(e===T||t===E)return-1;if(t===T||e===E)return 1;{const n=tryParseInt(e),r=tryParseInt(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null!==r?1:e<t?-1:1}},stringCompare=function(e,t){return e===t?0:e<t?-1:1},requireKey=function(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+stringify(t))},ObjectToUniqueKey=function(e){if("object"!=typeof e||null===e)return stringify(e);const t=[];for(const n in e)t.push(n);t.sort();let n="{";for(let r=0;r<t.length;r++)0!==r&&(n+=","),n+=stringify(t[r]),n+=":",n+=ObjectToUniqueKey(e[t[r]]);return n+="}",n},splitStringBySize=function(e,t){const n=e.length;if(n<=t)return[e];const r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r};function each(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const doubleToIEEE754String=function(e){assert(!isInvalidJSONNumber(e),"Invalid JSON number");const t=1023;let n,r,i,o,s;0===e?(r=0,i=0,n=1/e==-1/0?1:0):(n=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(o=Math.min(Math.floor(Math.log(e)/Math.LN2),t),r=o+t,i=Math.round(e*Math.pow(2,52-o)-Math.pow(2,52))):(r=0,i=Math.round(e/Math.pow(2,-1074))));const a=[];for(s=52;s;s-=1)a.push(i%2?1:0),i=Math.floor(i/2);for(s=11;s;s-=1)a.push(r%2?1:0),r=Math.floor(r/2);a.push(n?1:0),a.reverse();const l=a.join("");let h="";for(s=0;s<64;s+=8){let e=parseInt(l.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),h+=e}return h.toLowerCase()};const S=new RegExp("^-?(0*)\\d{1,10}$"),tryParseInt=function(e){if(S.test(e)){const t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},exceptionGuard=function(e){try{e()}catch(e){setTimeout((()=>{const t=e.stack||"";throw warn("Exception was thrown by user callback.",t),e}),Math.floor(0))}},setTimeoutNonBlocking=function(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n};class AppCheckTokenProvider{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,r(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then((e=>this.appCheck=e))}getToken(e){if(this.serverAppAppCheckToken){if(e)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(e):new Promise(((t,n)=>{setTimeout((()=>{this.appCheck?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){this.appCheckProvider?.get().then((t=>t.addTokenListener(e)))}notifyForInvalidToken(){warn(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}}class FirebaseAuthTokenProvider{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit((e=>this.auth_=e))}getToken(e){return this.auth_?this.auth_.getToken(e).catch((e=>e&&"auth/token-not-initialized"===e.code?(log("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e))):new Promise(((t,n)=>{setTimeout((()=>{this.auth_?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then((t=>t.addAuthTokenListener(e)))}removeTokenChangeListener(e){this.authProvider_.get().then((t=>t.removeAuthTokenListener(e)))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',warn(e)}}class EmulatorTokenProvider{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}EmulatorTokenProvider.OWNER="owner";const P=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,I="ac",b="websocket",N="long_polling";class RepoInfo{constructor(e,t,n,r,i=!1,o="",s=!1,a=!1,l=null){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=o,this.includeNamespaceInQueryParams=s,this.isUsingEmulator=a,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=f.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&f.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function repoInfoConnectionURL(e,t,n){let r;if(assert("string"==typeof t,"typeof type must == string"),assert("object"==typeof n,"typeof params must == object"),t===b)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==N)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}(function repoInfoNeedsQueryParam(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams})(e)&&(n.ns=e.namespace);const i=[];return each(n,((e,t)=>{i.push(e+"="+t)})),r+i.join("&")}class StatsCollection{constructor(){this.counters_={}}incrementCounter(e,t=1){contains(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return deepCopy(this.counters_)}}const R={},k={};function statsManagerGetCollection(e){const t=e.toString();return R[t]||(R[t]=new StatsCollection),R[t]}class PacketReceiver{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&exceptionGuard((()=>{this.onMessage_(e[t])}));if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const A="start";class BrowserPollConnection{constructor(e,t,n,r,i,o,s){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=o,this.lastSessionId=s,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=logWrapper(e),this.stats_=statsManagerGetCollection(t),this.urlFn=e=>(this.appCheckToken&&(e[I]=this.appCheckToken),repoInfoConnectionURL(t,N,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new PacketReceiver(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout((()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null}),Math.floor(3e4)),function(e){if("complete"===document.readyState)e();else{let t=!1;const wrappedFn=function(){document.body?t||(t=!0,e()):setTimeout(wrappedFn,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",wrappedFn,!1),window.addEventListener("load",wrappedFn,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",(()=>{"complete"===document.readyState&&wrappedFn()})),window.attachEvent("onload",wrappedFn))}}((()=>{if(this.isClosed_)return;this.scriptTagHolder=new FirebaseIFrameScriptHolder(((...e)=>{const[t,n,r,i,o]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===A)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,(()=>{this.onClosed_()}))):this.onClosed_()}}),((...e)=>{const[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)}),(()=>{this.onClosed_()}),this.urlFn);const e={};e[A]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e[I]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&P.test(location.hostname)&&(e.r="f");const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,(()=>{}))}))}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){BrowserPollConnection.forceAllow_=!0}static forceDisallow(){BrowserPollConnection.forceDisallow_=!0}static isAvailable(){return!!BrowserPollConnection.forceAllow_||!(BrowserPollConnection.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){const t=stringify(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=base64Encode(t),r=splitStringBySize(n,1840);for(let e=0;e<r.length;e++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,r.length,r[e]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const t=stringify(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class FirebaseIFrameScriptHolder{constructor(e,t,n,r){this.onDisconnect=n,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=v(),window["pLPCommand"+this.uniqueCallbackIdentifier]=e,window["pRTLPCB"+this.uniqueCallbackIdentifier]=t,this.myIFrame=FirebaseIFrameScriptHolder.createIFrame_();let n="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,11)){n='<script>document.domain="'+document.domain+'";<\/script>'}const r="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(r),this.myIFrame.doc.close()}catch(e){log("frame writing exception"),e.stack&&log(e.stack),log(e)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||log("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout((()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)}),Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",r=0;for(;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+30+n.length<=1870))break;{const e=this.pendingSegs.shift();n=n+"&seg"+r+"="+e.seg+"&ts"+r+"="+e.ts+"&d"+r+"="+e.d,r++}}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const doNewRequest=()=>{this.outstandingRequests.delete(t),this.newRequest_()},n=setTimeout(doNewRequest,Math.floor(25e3));this.addTag(e,(()=>{clearTimeout(n),doNewRequest()}))}addTag(e,t){setTimeout((()=>{try{if(!this.sendNewPolls)return;const n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){const e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{log("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(e){}}),Math.floor(1))}}let x=null;"undefined"!=typeof MozWebSocket?x=MozWebSocket:"undefined"!=typeof WebSocket&&(x=WebSocket);class WebSocketConnection{constructor(e,t,n,r,i,o,s){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=logWrapper(this.connId),this.stats_=statsManagerGetCollection(t),this.connURL=WebSocketConnection.connectionURL_(t,o,s,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){const o={v:"5"};return"undefined"!=typeof location&&location.hostname&&P.test(location.hostname)&&(o.r="f"),t&&(o.s=t),n&&(o.ls=n),r&&(o[I]=r),i&&(o.p=i),repoInfoConnectionURL(e,b,o)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,f.set("previous_websocket_failure",!0);try{let e;isNodeSdk(),this.mySock=new x(this.connURL,[],e)}catch(e){this.log_("Error instantiating WebSocket.");const t=e.message||e.data;return t&&this.log_(t),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){WebSocketConnection.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==x&&!WebSocketConnection.forceDisallow_}static previouslyFailed(){return f.isInMemoryStorage||!0===f.get("previous_websocket_failure")}markConnectionHealthy(){f.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=jsonEval(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(assert(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=stringify(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=splitStringBySize(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e<n.length;e++)this.sendString_(n[e])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval((()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()}),Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}WebSocketConnection.responsesRequiredToBeHealthy=2,WebSocketConnection.healthyTimeout=3e4;class TransportManager{static get ALL_TRANSPORTS(){return[BrowserPollConnection,WebSocketConnection]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){const t=WebSocketConnection&&WebSocketConnection.isAvailable();let n=t&&!WebSocketConnection.previouslyFailed();if(e.webSocketOnly&&(t||warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[WebSocketConnection];else{const e=this.transports_=[];for(const t of TransportManager.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);TransportManager.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}TransportManager.globalTransportInitialized_=!1;class Connection{constructor(e,t,n,r,i,o,s,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=o,this.onReady_=s,this.onDisconnect_=a,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=logWrapper("c:"+this.id+":"),this.transportManager_=new TransportManager(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout((()=>{this.conn_&&this.conn_.open(t,n)}),Math.floor(0));const r=e.healthyTimeout||0;r>0&&(this.healthyTimeout_=setTimeoutNonBlocking((()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))}),Math.floor(r)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if("t"in e){const t=e.t;"a"===t?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=requireKey("t",e),n=requireKey("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const t=requireKey("t",e),n=requireKey("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){const t=requireKey("t",e);if("d"in e){const n=e.d;if("h"===t){const e={...n};this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?error("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):error("Unknown control packet command: "+t)}}onHandshake_(e){const t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&warn("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),setTimeoutNonBlocking((()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())}),Math.floor(6e4))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):setTimeoutNonBlocking((()=>{this.sendPingOnPrimaryIfNecessary_()}),Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(f.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class ServerActions{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class EventEmitter{constructor(e){this.allowedEvents_=e,this.listeners_={},assert(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});const r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let e=0;e<r.length;e++)if(r[e].callback===t&&(!n||n===r[e].context))return void r.splice(e,1)}validateEventType_(e){assert(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}class OnlineMonitor extends EventEmitter{static getInstance(){return new OnlineMonitor}constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||isMobileCordova()||(window.addEventListener("online",(()=>{this.online_||(this.online_=!0,this.trigger("online",!0))}),!1),window.addEventListener("offline",(()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))}),!1))}getInitialEvent(e){return assert("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class Path{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++)this.pieces_[e].length>0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function newEmptyPath(){return new Path("")}function pathGetFront(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function pathGetLength(e){return e.pieces_.length-e.pieceNum_}function pathPopFront(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new Path(e.pieces_,t)}function pathGetBack(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function pathSlice(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function pathParent(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new Path(t,0)}function pathChild(e,t){const n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++)n.push(e.pieces_[t]);if(t instanceof Path)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{const e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new Path(n,0)}function pathIsEmpty(e){return e.pieceNum_>=e.pieces_.length}function newRelativePath(e,t){const n=pathGetFront(e),r=pathGetFront(t);if(null===n)return t;if(n===r)return newRelativePath(pathPopFront(e),pathPopFront(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function pathCompare(e,t){const n=pathSlice(e,0),r=pathSlice(t,0);for(let e=0;e<n.length&&e<r.length;e++){const t=nameCompare(n[e],r[e]);if(0!==t)return t}return n.length===r.length?0:n.length<r.length?-1:1}function pathEquals(e,t){if(pathGetLength(e)!==pathGetLength(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function pathContains(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(pathGetLength(e)>pathGetLength(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class ValidationPath{constructor(e,t){this.errorPrefix_=t,this.parts_=pathSlice(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++)this.byteLength_+=stringLength(this.parts_[e]);validationPathCheckValid(this)}}function validationPathCheckValid(e){if(e.byteLength_>768)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(e.parts_.length>32)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+validationPathToErrorString(e))}function validationPathToErrorString(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class VisibilityMonitor extends EventEmitter{static getInstance(){return new VisibilityMonitor}constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}getInitialEvent(e){return assert("visible"===e,"Unknown event type: "+e),[this.visible_]}}const F=1e3;class PersistentConnection extends ServerActions{constructor(e,t,n,r,i,o,s,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=o,this.appCheckTokenProvider_=s,this.authOverride_=a,this.id=PersistentConnection.nextPersistentConnectionId_++,this.log_=logWrapper("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=F,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a&&!isNodeSdk())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");VisibilityMonitor.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&OnlineMonitor.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){const r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(stringify(i)),assert(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();const t=new Deferred,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{const n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;const r=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(r),t.promise}listen(e,t,n,r){this.initConnection_();const i=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+i),this.listens.has(o)||this.listens.set(o,new Map),assert(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),assert(!this.listens.get(o).has(i),"listen() called twice for same path/queryId.");const s={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(o).set(i,s),this.connected_&&this.sendListen_(s)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,(n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)}))}sendListen_(e){const t=e.query,n=t._path.toString(),r=t._queryIdentifier;this.log_("Listen on "+n+" for "+r);const i={p:n};e.tag&&(i.q=t._queryObject,i.t=e.tag),i.h=e.hashFn(),this.sendRequest("q",i,(i=>{const o=i.d,s=i.s;PersistentConnection.warnOnListenWarnings_(o,t);(this.listens.get(n)&&this.listens.get(n).get(r))===e&&(this.log_("listen response",i),"ok"!==s&&this.removeListen_(n,r),e.onComplete&&e.onComplete(s,o))}))}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&contains(e,"w")){const n=safeGet(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();warn(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${e} at ${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},(()=>{})),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||function(e){const t=decode(e).claims;return"object"==typeof t&&!0===t.admin}(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},(()=>{}))}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,t=function(e){const t=decode(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")}(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,(t=>{const n=t.s,r=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,r))}))}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},(e=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)}))}unlisten(e,t){const n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),assert(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query");this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,r){const i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,(e=>{r&&setTimeout((()=>{r(e.s,e.d)}),Math.floor(0))}))}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const o={p:t,d:n};void 0!==i&&(o.h=i),this.outstandingPuts_.push({action:e,request:o,onComplete:r}),this.outstandingPutCount_++;const s=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(s):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,r=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,(n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(n.s,n.d)}))}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,(e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}}))}}onDataMessage_(e){if("r"in e){this.log_("from server: "+stringify(e));const t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):error("Unrecognized action received from server: "+stringify(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){assert(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout((()=>{this.establishConnectionTimer_=null,this.establishConnection_()}),Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=F,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=F,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){if(this.visible_){if(this.lastConnectionEstablishedTime_){(new Date).getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=F),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();const e=Math.max(0,(new Date).getTime()-this.lastConnectionAttemptTime_);let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),n=this.onRealtimeDisconnect_.bind(this),r=this.id+":"+PersistentConnection.nextConnectionId_++,i=this.lastSessionId;let o=!1,s=null;const closeFn=function(){s?s.close():(o=!0,n())},sendRequestFn=function(e){assert(s,"sendRequest call when we're not connected not allowed."),s.sendRequest(e)};this.realtime_={close:closeFn,sendRequest:sendRequestFn};const a=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[l,h]=await Promise.all([this.authTokenProvider_.getToken(a),this.appCheckTokenProvider_.getToken(a)]);o?log("getToken() completed but was canceled"):(log("getToken() completed. Creating connection."),this.authToken_=l&&l.accessToken,this.appCheckToken_=h&&h.token,s=new Connection(r,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,(e=>{warn(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")}),i))}catch(e){this.log_("Failed to get token: "+e),o||(this.repoInfo_.nodeAdmin&&warn(e),closeFn())}}}interrupt(e){log("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){log("Resuming connection for reason: "+e),delete this.interruptReasons_[e],isEmpty(this.interruptReasons_)&&(this.reconnectDelay_=F,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map((e=>ObjectToUniqueKey(e))).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){const n=new Path(e).toString();let r;if(this.listens.has(n)){const e=this.listens.get(n);r=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){log("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){log("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){const e={};e["sdk.js."+m.replace(/\./g,"-")]=1,isMobileCordova()?e["framework.cordova"]=1:function isReactNative(){return"object"==typeof navigator&&"ReactNative"===navigator.product}()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=OnlineMonitor.getInstance().currentlyOnline();return isEmpty(this.interruptReasons_)&&e}}PersistentConnection.nextPersistentConnectionId_=0,PersistentConnection.nextConnectionId_=0;class NamedNode{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new NamedNode(e,t)}}class Index{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const n=new NamedNode(T,e),r=new NamedNode(T,t);return 0!==this.compare(n,r)}minPost(){return NamedNode.MIN}}let O;class KeyIndex extends Index{static get __EMPTY_NODE(){return O}static set __EMPTY_NODE(e){O=e}compare(e,t){return nameCompare(e.name,t.name)}isDefinedOn(e){throw assertionError("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return NamedNode.MIN}maxPost(){return new NamedNode(E,O)}makePost(e,t){return assert("string"==typeof e,"KeyIndex indexValue must always be a string."),new NamedNode(e,O)}toString(){return".key"}}const D=new KeyIndex;class SortedMapIterator{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let o=1;for(;!e.isEmpty();)if(o=t?n(e.key,t):1,r&&(o*=-1),o<0)e=this.isReverse_?e.left:e.right;else{if(0===o){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e,t=this.nodeStack_.pop();if(e=this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value},this.isReverse_)for(t=t.left;!t.isEmpty();)this.nodeStack_.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack_.push(t),t=t.left;return e}hasNext(){return this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class LLRBNode{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:LLRBNode.RED,this.left=null!=r?r:SortedMap.EMPTY_NODE,this.right=null!=i?i:SortedMap.EMPTY_NODE}copy(e,t,n,r,i){return new LLRBNode(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;const i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return SortedMap.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let n,r;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return SortedMap.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){const e=this.copy(null,null,LLRBNode.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,LLRBNode.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}LLRBNode.RED=!0,LLRBNode.BLACK=!1;class SortedMap{constructor(e,t=SortedMap.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new SortedMap(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,LLRBNode.BLACK,null,null))}remove(e){return new SortedMap(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,LLRBNode.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t)return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new SortedMapIterator(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new SortedMapIterator(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new SortedMapIterator(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new SortedMapIterator(this.root_,null,this.comparator_,!0,e)}}function NAME_ONLY_COMPARATOR(e,t){return nameCompare(e.name,t.name)}function NAME_COMPARATOR(e,t){return nameCompare(e,t)}let L;SortedMap.EMPTY_NODE=new class LLRBEmptyNode{copy(e,t,n,r,i){return this}insert(e,t,n){return new LLRBNode(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};const priorityHashText=function(e){return"number"==typeof e?"number:"+doubleToIEEE754String(e):"string:"+e},validatePriorityNode=function(e){if(e.isLeafNode()){const t=e.val();assert("string"==typeof t||"number"==typeof t||"object"==typeof t&&contains(t,".sv"),"Priority must be a string or number.")}else assert(e===L||e.isEmpty(),"priority of unexpected type.");assert(e===L||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let M,W,q;class LeafNode{static set __childrenNodeConstructor(e){M=e}static get __childrenNodeConstructor(){return M}constructor(e,t=LeafNode.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,assert(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),validatePriorityNode(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new LeafNode(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:LeafNode.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return pathIsEmpty(e)?this:".priority"===pathGetFront(e)?this.priorityNode_:LeafNode.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const n=pathGetFront(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(assert(".priority"!==n||1===pathGetLength(e),".priority must be the last token in a path"),this.updateImmediateChild(n,LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+priorityHashText(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?doubleToIEEE754String(this.value_):this.value_,this.lazyHash_=sha1(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===LeafNode.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof LeafNode.__childrenNodeConstructor?-1:(assert(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,n=typeof this.value_,r=LeafNode.VALUE_TYPE_ORDER.indexOf(t),i=LeafNode.VALUE_TYPE_ORDER.indexOf(n);return assert(r>=0,"Unknown leaf type: "+t),assert(i>=0,"Unknown leaf type: "+n),r===i?"object"===n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){const t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}return!1}}LeafNode.VALUE_TYPE_ORDER=["object","boolean","number","string"];const G=new class PriorityIndex extends Index{compare(e,t){const n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return 0===i?nameCompare(e.name,t.name):i}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return NamedNode.MIN}maxPost(){return new NamedNode(E,new LeafNode("[PRIORITY-POST]",q))}makePost(e,t){const n=W(e);return new NamedNode(t,new LeafNode("[PRIORITY-POST]",n))}toString(){return".priority"}},Q=Math.log(2);class Base12Num{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/Q,10)),this.current_=this.count-1;const n=(r=this.count,parseInt(Array(r+1).join("1"),2));var r;this.bits_=e+1&n}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const buildChildSet=function(e,t,n,r){e.sort(t);const buildBalancedTree=function(t,r){const i=r-t;let o,s;if(0===i)return null;if(1===i)return o=e[t],s=n?n(o):o,new LLRBNode(s,o.node,LLRBNode.BLACK,null,null);{const a=parseInt(i/2,10)+t,l=buildBalancedTree(t,a),h=buildBalancedTree(a+1,r);return o=e[a],s=n?n(o):o,new LLRBNode(s,o.node,LLRBNode.BLACK,l,h)}},i=function(t){let r=null,i=null,o=e.length;const buildPennant=function(t,r){const i=o-t,s=o;o-=t;const a=buildBalancedTree(i+1,s),l=e[i],h=n?n(l):l;attachPennant(new LLRBNode(h,l.node,r,null,a))},attachPennant=function(e){r?(r.left=e,r=e):(i=e,r=e)};for(let e=0;e<t.count;++e){const n=t.nextBitIsOne(),r=Math.pow(2,t.count-(e+1));n?buildPennant(r,LLRBNode.BLACK):(buildPennant(r,LLRBNode.BLACK),buildPennant(r,LLRBNode.RED))}return i}(new Base12Num(e.length));return new SortedMap(r||t,i)};let B;const U={};class IndexMap{static get Default(){return assert(U&&G,"ChildrenNode.ts has not been loaded"),B=B||new IndexMap({".priority":U},{".priority":G}),B}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){const t=safeGet(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof SortedMap?t:null}hasIndex(e){return contains(this.indexSet_,e.toString())}addIndex(e,t){assert(e!==D,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(NamedNode.Wrap);let o,s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();o=r?buildChildSet(n,e.getCompare()):U;const a=e.toString(),l={...this.indexSet_};l[a]=e;const h={...this.indexes_};return h[a]=o,new IndexMap(h,l)}addToIndexes(e,t){const n=map(this.indexes_,((n,r)=>{const i=safeGet(this.indexSet_,r);if(assert(i,"Missing index implementation for "+r),n===U){if(i.isDefinedOn(e.node)){const n=[],r=t.getIterator(NamedNode.Wrap);let o=r.getNext();for(;o;)o.name!==e.name&&n.push(o),o=r.getNext();return n.push(e),buildChildSet(n,i.getCompare())}return U}{const r=t.get(e.name);let i=n;return r&&(i=i.remove(new NamedNode(e.name,r))),i.insert(e,e.node)}}));return new IndexMap(n,this.indexSet_)}removeFromIndexes(e,t){const n=map(this.indexes_,(n=>{if(n===U)return n;{const r=t.get(e.name);return r?n.remove(new NamedNode(e.name,r)):n}}));return new IndexMap(n,this.indexSet_)}}let V;class ChildrenNode{static get EMPTY_NODE(){return V||(V=new ChildrenNode(new SortedMap(NAME_COMPARATOR),null,IndexMap.Default))}constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&validatePriorityNode(this.priorityNode_),this.children_.isEmpty()&&assert(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||V}updatePriority(e){return this.children_.isEmpty()?this:new ChildrenNode(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?V:t}}getChild(e){const t=pathGetFront(e);return null===t?this:this.getImmediateChild(t).getChild(pathPopFront(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if(assert(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{const n=new NamedNode(e,t);let r,i;t.isEmpty()?(r=this.children_.remove(e),i=this.indexMap_.removeFromIndexes(n,this.children_)):(r=this.children_.insert(e,t),i=this.indexMap_.addToIndexes(n,this.children_));const o=r.isEmpty()?V:this.priorityNode_;return new ChildrenNode(r,o,i)}}updateChild(e,t){const n=pathGetFront(e);if(null===n)return t;{assert(".priority"!==pathGetFront(e)||1===pathGetLength(e),".priority must be the last token in a path");const r=this.getImmediateChild(n).updateChild(pathPopFront(e),t);return this.updateImmediateChild(n,r)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,r=0,i=!0;if(this.forEachChild(G,((o,s)=>{t[o]=s.val(e),n++,i&&ChildrenNode.INTEGER_REGEXP_.test(o)?r=Math.max(r,Number(o)):i=!1})),!e&&i&&r<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+priorityHashText(this.getPriority().val())+":"),this.forEachChild(G,((t,n)=>{const r=n.hash();""!==r&&(e+=":"+t+":"+r)})),this.lazyHash_=""===e?"":sha1(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){const n=r.getPredecessorKey(new NamedNode(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new NamedNode(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new NamedNode(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal((e=>t(e.name,e.node))):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,(e=>e));{const n=this.children_.getIteratorFrom(e.name,NamedNode.Wrap);let r=n.peek();for(;null!=r&&t.compare(r,e)<0;)n.getNext(),r=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,(e=>e));{const n=this.children_.getReverseIteratorFrom(e.name,NamedNode.Wrap);let r=n.peek();for(;null!=r&&t.compare(r,e)>0;)n.getNext(),r=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===H?-1:0}withIndex(e){if(e===D||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new ChildrenNode(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===D||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(G),n=t.getIterator(G);let r=e.getNext(),i=n.getNext();for(;r&&i;){if(r.name!==i.name||!r.node.equals(i.node))return!1;r=e.getNext(),i=n.getNext()}return null===r&&null===i}return!1}return!1}}resolveIndex_(e){return e===D?null:this.indexMap_.get(e.toString())}}ChildrenNode.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;const H=new class MaxNode extends ChildrenNode{constructor(){super(new SortedMap(NAME_COMPARATOR),ChildrenNode.EMPTY_NODE,IndexMap.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ChildrenNode.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(NamedNode,{MIN:{value:new NamedNode(T,ChildrenNode.EMPTY_NODE)},MAX:{value:new NamedNode(E,H)}}),KeyIndex.__EMPTY_NODE=ChildrenNode.EMPTY_NODE,LeafNode.__childrenNodeConstructor=ChildrenNode,function setMaxNode$1(e){L=e}(H),function setMaxNode(e){q=e}(H);function nodeFromJSON(e,t=null){if(null===e)return ChildrenNode.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),assert(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e){return new LeafNode(e,nodeFromJSON(t))}if(e instanceof Array){let n=ChildrenNode.EMPTY_NODE;return each(e,((t,r)=>{if(contains(e,t)&&"."!==t.substring(0,1)){const e=nodeFromJSON(r);!e.isLeafNode()&&e.isEmpty()||(n=n.updateImmediateChild(t,e))}})),n.updatePriority(nodeFromJSON(t))}{const n=[];let r=!1;if(each(e,((e,t)=>{if("."!==e.substring(0,1)){const i=nodeFromJSON(t);i.isEmpty()||(r=r||!i.getPriority().isEmpty(),n.push(new NamedNode(e,i)))}})),0===n.length)return ChildrenNode.EMPTY_NODE;const i=buildChildSet(n,NAME_ONLY_COMPARATOR,(e=>e.name),NAME_COMPARATOR);if(r){const e=buildChildSet(n,G.getCompare());return new ChildrenNode(i,nodeFromJSON(t),new IndexMap({".priority":e},{".priority":G}))}return new ChildrenNode(i,nodeFromJSON(t),IndexMap.Default)}}!function setNodeFromJSON(e){W=e}(nodeFromJSON);class PathIndex extends Index{constructor(e){super(),this.indexPath_=e,assert(!pathIsEmpty(e)&&".priority"!==pathGetFront(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node),r=this.extractChild(t.node),i=n.compareTo(r);return 0===i?nameCompare(e.name,t.name):i}makePost(e,t){const n=nodeFromJSON(e),r=ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_,n);return new NamedNode(t,r)}maxPost(){const e=ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_,H);return new NamedNode(E,e)}toString(){return pathSlice(this.indexPath_,0).join("/")}}const j=new class ValueIndex extends Index{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?nameCompare(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return NamedNode.MIN}maxPost(){return NamedNode.MAX}makePost(e,t){const n=nodeFromJSON(e);return new NamedNode(t,n)}toString(){return".value"}};function changeValue(e){return{type:"value",snapshotNode:e}}function changeChildAdded(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function changeChildRemoved(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function changeChildChanged(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class IndexedFilter{constructor(e){this.index_=e}updateChild(e,t,n,r,i,o){assert(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const s=e.getImmediateChild(t);return s.getChild(r).equals(n.getChild(r))&&s.isEmpty()===n.isEmpty()?e:(null!=o&&(n.isEmpty()?e.hasChild(t)?o.trackChildChange(changeChildRemoved(t,s)):assert(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):s.isEmpty()?o.trackChildChange(changeChildAdded(t,n)):o.trackChildChange(changeChildChanged(t,n,s))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(G,((e,r)=>{t.hasChild(e)||n.trackChildChange(changeChildRemoved(e,r))})),t.isLeafNode()||t.forEachChild(G,((t,r)=>{if(e.hasChild(t)){const i=e.getImmediateChild(t);i.equals(r)||n.trackChildChange(changeChildChanged(t,r,i))}else n.trackChildChange(changeChildAdded(t,r))}))),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?ChildrenNode.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class RangedFilter{constructor(e){this.indexedFilter_=new IndexedFilter(e.getIndex()),this.index_=e.getIndex(),this.startPost_=RangedFilter.getStartPost_(e),this.endPost_=RangedFilter.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,o){return this.matches(new NamedNode(t,n))||(n=ChildrenNode.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,o)}updateFullNode(e,t,n){t.isLeafNode()&&(t=ChildrenNode.EMPTY_NODE);let r=t.withIndex(this.index_);r=r.updatePriority(ChildrenNode.EMPTY_NODE);const i=this;return t.forEachChild(G,((e,t)=>{i.matches(new NamedNode(e,t))||(r=r.updateImmediateChild(e,ChildrenNode.EMPTY_NODE))})),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class LimitedFilter{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{const t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{const t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new RangedFilter(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,o){return this.rangedFilter_.matches(new NamedNode(t,n))||(n=ChildrenNode.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,o):this.fullLimitUpdateChild_(e,t,n,i,o)}updateFullNode(e,t,n){let r;if(t.isLeafNode()||t.isEmpty())r=ChildrenNode.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;r=ChildrenNode.EMPTY_NODE.withIndex(this.index_),e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){const t=e.getNext();if(this.withinDirectionalStart(t)){if(!this.withinDirectionalEnd(t))break;r=r.updateImmediateChild(t.name,t.node),n++}}}else{let e;r=t.withIndex(this.index_),r=r.updatePriority(ChildrenNode.EMPTY_NODE),e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_);let n=0;for(;e.hasNext();){const t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:r=r.updateImmediateChild(t.name,ChildrenNode.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let o;if(this.reverse_){const e=this.index_.getCompare();o=(t,n)=>e(n,t)}else o=this.index_.getCompare();const s=e;assert(s.numChildren()===this.limit_,"");const a=new NamedNode(t,n),l=this.reverse_?s.getFirstChild(this.index_):s.getLastChild(this.index_),h=this.rangedFilter_.matches(a);if(s.hasChild(t)){const e=s.getImmediateChild(t);let c=r.getChildAfterChild(this.index_,l,this.reverse_);for(;null!=c&&(c.name===t||s.hasChild(c.name));)c=r.getChildAfterChild(this.index_,c,this.reverse_);const d=null==c?1:o(c,a);if(h&&!n.isEmpty()&&d>=0)return null!=i&&i.trackChildChange(changeChildChanged(t,n,e)),s.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(changeChildRemoved(t,e));const n=s.updateImmediateChild(t,ChildrenNode.EMPTY_NODE);return null!=c&&this.rangedFilter_.matches(c)?(null!=i&&i.trackChildChange(changeChildAdded(c.name,c.node)),n.updateImmediateChild(c.name,c.node)):n}}return n.isEmpty()?e:h&&o(l,a)>=0?(null!=i&&(i.trackChildChange(changeChildRemoved(l.name,l.node)),i.trackChildChange(changeChildAdded(t,n))),s.updateImmediateChild(t,n).updateImmediateChild(l.name,ChildrenNode.EMPTY_NODE)):e}}class QueryParams{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=G}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return assert(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return assert(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:T}hasEnd(){return this.endSet_}getIndexEndValue(){return assert(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return assert(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:E}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return assert(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===G}copy(){const e=new QueryParams;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function queryParamsStartAt(e,t,n){const r=e.copy();return r.startSet_=!0,void 0===t&&(t=null),r.indexStartValue_=t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function queryParamsEndAt(e,t,n){const r=e.copy();return r.endSet_=!0,void 0===t&&(t=null),r.indexEndValue_=t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function queryParamsOrderBy(e,t){const n=e.copy();return n.index_=t,n}function queryParamsToRestQueryStringParameters(e){const t={};if(e.isDefault())return t;let n;if(e.index_===G?n="$priority":e.index_===j?n="$value":e.index_===D?n="$key":(assert(e.index_ instanceof PathIndex,"Unrecognized index type!"),n=e.index_.toString()),t.orderBy=stringify(n),e.startSet_){const n=e.startAfterSet_?"startAfter":"startAt";t[n]=stringify(e.indexStartValue_),e.startNameSet_&&(t[n]+=","+stringify(e.indexStartName_))}if(e.endSet_){const n=e.endBeforeSet_?"endBefore":"endAt";t[n]=stringify(e.indexEndValue_),e.endNameSet_&&(t[n]+=","+stringify(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function queryParamsGetQueryObject(e){const t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==G&&(t.i=e.index_.toString()),t}class ReadonlyRestClient extends ServerActions{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(assert(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=logWrapper("p:rest:"),this.listens_={}}listen(e,t,n,r){const i=e._path.toString();this.log_("Listen called for "+i+" "+e._queryIdentifier);const o=ReadonlyRestClient.getListenId_(e,n),s={};this.listens_[o]=s;const a=queryParamsToRestQueryStringParameters(e._queryParams);this.restRequest_(i+".json",a,((e,t)=>{let a=t;if(404===e&&(a=null,e=null),null===e&&this.onDataUpdate_(i,a,!1,n),safeGet(this.listens_,o)===s){let t;t=e?401===e?"permission_denied":"rest_error:"+e:"ok",r(t,null)}}))}unlisten(e,t){const n=ReadonlyRestClient.getListenId_(e,t);delete this.listens_[n]}get(e){const t=queryParamsToRestQueryStringParameters(e._queryParams),n=e._path.toString(),r=new Deferred;return this.restRequest_(n+".json",t,((e,t)=>{let i=t;404===e&&(i=null,e=null),null===e?(this.onDataUpdate_(n,i,!1,null),r.resolve(i)):r.reject(new Error(i))})),r.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then((([r,i])=>{r&&r.accessToken&&(t.auth=r.accessToken),i&&i.token&&(t.ac=i.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+function querystring(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}(t);this.log_("Sending REST request for "+o);const s=new XMLHttpRequest;s.onreadystatechange=()=>{if(n&&4===s.readyState){this.log_("REST Response for "+o+" received. status:",s.status,"response:",s.responseText);let e=null;if(s.status>=200&&s.status<300){try{e=jsonEval(s.responseText)}catch(e){warn("Failed to parse JSON response for "+o+": "+s.responseText)}n(null,e)}else 401!==s.status&&404!==s.status&&warn("Got unsuccessful REST response for "+o+" Status: "+s.status),n(s.status);n=null}},s.open("GET",o,!0),s.send()}))}}class SnapshotHolder{constructor(){this.rootNode_=ChildrenNode.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function newSparseSnapshotTree(){return{value:null,children:new Map}}function sparseSnapshotTreeRemember(e,t,n){if(pathIsEmpty(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const r=pathGetFront(t);e.children.has(r)||e.children.set(r,newSparseSnapshotTree());sparseSnapshotTreeRemember(e.children.get(r),t=pathPopFront(t),n)}}function sparseSnapshotTreeForget(e,t){if(pathIsEmpty(t))return e.value=null,e.children.clear(),!0;if(null!==e.value){if(e.value.isLeafNode())return!1;{const n=e.value;return e.value=null,n.forEachChild(G,((t,n)=>{sparseSnapshotTreeRemember(e,new Path(t),n)})),sparseSnapshotTreeForget(e,t)}}if(e.children.size>0){const n=pathGetFront(t);if(t=pathPopFront(t),e.children.has(n)){sparseSnapshotTreeForget(e.children.get(n),t)&&e.children.delete(n)}return 0===e.children.size}return!0}function sparseSnapshotTreeForEachTree(e,t,n){null!==e.value?n(t,e.value):function sparseSnapshotTreeForEachChild(e,t){e.children.forEach(((e,n)=>{t(n,e)}))}(e,((e,r)=>{sparseSnapshotTreeForEachTree(r,new Path(t.toString()+"/"+e),n)}))}class StatsListener{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t={...e};return this.last_&&each(this.last_,((e,n)=>{t[e]=t[e]-n})),this.last_=e,t}}class StatsReporter{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new StatsListener(e);const n=1e4+2e4*Math.random();setTimeoutNonBlocking(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;each(e,((e,r)=>{r>0&&contains(this.statsToReport_,e)&&(t[e]=r,n=!0)})),n&&this.server_.reportStats(t),setTimeoutNonBlocking(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}var z;function newOperationSourceServerTaggedQuery(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}!function(e){e[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(z||(z={}));class AckUserWrite{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=z.ACK_USER_WRITE,this.source={fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}operationForChild(e){if(pathIsEmpty(this.path)){if(null!=this.affectedTree.value)return assert(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new Path(e));return new AckUserWrite(newEmptyPath(),t,this.revert)}}return assert(pathGetFront(this.path)===e,"operationForChild called for unrelated child."),new AckUserWrite(pathPopFront(this.path),this.affectedTree,this.revert)}}class ListenComplete{constructor(e,t){this.source=e,this.path=t,this.type=z.LISTEN_COMPLETE}operationForChild(e){return pathIsEmpty(this.path)?new ListenComplete(this.source,newEmptyPath()):new ListenComplete(this.source,pathPopFront(this.path))}}class Overwrite{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=z.OVERWRITE}operationForChild(e){return pathIsEmpty(this.path)?new Overwrite(this.source,newEmptyPath(),this.snap.getImmediateChild(e)):new Overwrite(this.source,pathPopFront(this.path),this.snap)}}class Merge{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=z.MERGE}operationForChild(e){if(pathIsEmpty(this.path)){const t=this.children.subtree(new Path(e));return t.isEmpty()?null:t.value?new Overwrite(this.source,newEmptyPath(),t.value):new Merge(this.source,newEmptyPath(),t)}return assert(pathGetFront(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Merge(this.source,pathPopFront(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class CacheNode{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(pathIsEmpty(e))return this.isFullyInitialized()&&!this.filtered_;const t=pathGetFront(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class EventGenerator{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function eventGeneratorGenerateEventsForType(e,t,n,r,i,o){const s=r.filter((e=>e.type===n));s.sort(((t,n)=>function eventGeneratorCompareChanges(e,t,n){if(null==t.childName||null==n.childName)throw assertionError("Should only compare child_ events.");const r=new NamedNode(t.childName,t.snapshotNode),i=new NamedNode(n.childName,n.snapshotNode);return e.index_.compare(r,i)}(e,t,n))),s.forEach((n=>{const r=function eventGeneratorMaterializeSingleChange(e,t,n){return"value"===t.type||"child_removed"===t.type||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}(e,n,o);i.forEach((i=>{i.respondsTo(n.type)&&t.push(i.createEvent(r,e.query_))}))}))}function newViewCache(e,t){return{eventCache:e,serverCache:t}}function viewCacheUpdateEventSnap(e,t,n,r){return newViewCache(new CacheNode(t,n,r),e.serverCache)}function viewCacheUpdateServerSnap(e,t,n,r){return newViewCache(e.eventCache,new CacheNode(t,n,r))}function viewCacheGetCompleteEventSnap(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function viewCacheGetCompleteServerSnap(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let K;class ImmutableTree{static fromObject(e){let t=new ImmutableTree(null);return each(e,((e,n)=>{t=t.set(new Path(e),n)})),t}constructor(e,t=(()=>(K||(K=new SortedMap(stringCompare)),K))()){this.value=e,this.children=t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:newEmptyPath(),value:this.value};if(pathIsEmpty(e))return null;{const n=pathGetFront(e),r=this.children.get(n);if(null!==r){const i=r.findRootMostMatchingPathAndValue(pathPopFront(e),t);if(null!=i){return{path:pathChild(new Path(n),i.path),value:i.value}}return null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,(()=>!0))}subtree(e){if(pathIsEmpty(e))return this;{const t=pathGetFront(e),n=this.children.get(t);return null!==n?n.subtree(pathPopFront(e)):new ImmutableTree(null)}}set(e,t){if(pathIsEmpty(e))return new ImmutableTree(t,this.children);{const n=pathGetFront(e),r=(this.children.get(n)||new ImmutableTree(null)).set(pathPopFront(e),t),i=this.children.insert(n,r);return new ImmutableTree(this.value,i)}}remove(e){if(pathIsEmpty(e))return this.children.isEmpty()?new ImmutableTree(null):new ImmutableTree(null,this.children);{const t=pathGetFront(e),n=this.children.get(t);if(n){const r=n.remove(pathPopFront(e));let i;return i=r.isEmpty()?this.children.remove(t):this.children.insert(t,r),null===this.value&&i.isEmpty()?new ImmutableTree(null):new ImmutableTree(this.value,i)}return this}}get(e){if(pathIsEmpty(e))return this.value;{const t=pathGetFront(e),n=this.children.get(t);return n?n.get(pathPopFront(e)):null}}setTree(e,t){if(pathIsEmpty(e))return t;{const n=pathGetFront(e),r=(this.children.get(n)||new ImmutableTree(null)).setTree(pathPopFront(e),t);let i;return i=r.isEmpty()?this.children.remove(n):this.children.insert(n,r),new ImmutableTree(this.value,i)}}fold(e){return this.fold_(newEmptyPath(),e)}fold_(e,t){const n={};return this.children.inorderTraversal(((r,i)=>{n[r]=i.fold_(pathChild(e,r),t)})),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,newEmptyPath(),t)}findOnPath_(e,t,n){const r=!!this.value&&n(t,this.value);if(r)return r;if(pathIsEmpty(e))return null;{const r=pathGetFront(e),i=this.children.get(r);return i?i.findOnPath_(pathPopFront(e),pathChild(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,newEmptyPath(),t)}foreachOnPath_(e,t,n){if(pathIsEmpty(e))return this;{this.value&&n(t,this.value);const r=pathGetFront(e),i=this.children.get(r);return i?i.foreachOnPath_(pathPopFront(e),pathChild(t,r),n):new ImmutableTree(null)}}foreach(e){this.foreach_(newEmptyPath(),e)}foreach_(e,t){this.children.inorderTraversal(((n,r)=>{r.foreach_(pathChild(e,n),t)})),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal(((t,n)=>{n.value&&e(t,n.value)}))}}class CompoundWrite{constructor(e){this.writeTree_=e}static empty(){return new CompoundWrite(new ImmutableTree(null))}}function compoundWriteAddWrite(e,t,n){if(pathIsEmpty(t))return new CompoundWrite(new ImmutableTree(n));{const r=e.writeTree_.findRootMostValueAndPath(t);if(null!=r){const i=r.path;let o=r.value;const s=newRelativePath(i,t);return o=o.updateChild(s,n),new CompoundWrite(e.writeTree_.set(i,o))}{const r=new ImmutableTree(n),i=e.writeTree_.setTree(t,r);return new CompoundWrite(i)}}}function compoundWriteAddWrites(e,t,n){let r=e;return each(n,((e,n)=>{r=compoundWriteAddWrite(r,pathChild(t,e),n)})),r}function compoundWriteRemoveWrite(e,t){if(pathIsEmpty(t))return CompoundWrite.empty();{const n=e.writeTree_.setTree(t,new ImmutableTree(null));return new CompoundWrite(n)}}function compoundWriteHasCompleteWrite(e,t){return null!=compoundWriteGetCompleteNode(e,t)}function compoundWriteGetCompleteNode(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(newRelativePath(n.path,t)):null}function compoundWriteGetCompleteChildren(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(G,((e,n)=>{t.push(new NamedNode(e,n))})):e.writeTree_.children.inorderTraversal(((e,n)=>{null!=n.value&&t.push(new NamedNode(e,n.value))})),t}function compoundWriteChildCompoundWrite(e,t){if(pathIsEmpty(t))return e;{const n=compoundWriteGetCompleteNode(e,t);return new CompoundWrite(null!=n?new ImmutableTree(n):e.writeTree_.subtree(t))}}function compoundWriteIsEmpty(e){return e.writeTree_.isEmpty()}function compoundWriteApply(e,t){return applySubtreeWrite(newEmptyPath(),e.writeTree_,t)}function applySubtreeWrite(e,t,n){if(null!=t.value)return n.updateChild(e,t.value);{let r=null;return t.children.inorderTraversal(((t,i)=>{".priority"===t?(assert(null!==i.value,"Priority writes must always be leaf nodes"),r=i.value):n=applySubtreeWrite(pathChild(e,t),i,n)})),n.getChild(e).isEmpty()||null===r||(n=n.updateChild(pathChild(e,".priority"),r)),n}}function writeTreeChildWrites(e,t){return newWriteTreeRef(t,e)}function writeTreeRemoveWrite(e,t){const n=e.allWrites.findIndex((e=>e.writeId===t));assert(n>=0,"removeWrite called with nonexistent writeId.");const r=e.allWrites[n];e.allWrites.splice(n,1);let i=r.visible,o=!1,s=e.allWrites.length-1;for(;i&&s>=0;){const t=e.allWrites[s];t.visible&&(s>=n&&writeTreeRecordContainsPath_(t,r.path)?i=!1:pathContains(r.path,t.path)&&(o=!0)),s--}if(i){if(o)return function writeTreeResetTree_(e){e.visibleWrites=writeTreeLayerTree_(e.allWrites,writeTreeDefaultFilter_,newEmptyPath()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}(e),!0;if(r.snap)e.visibleWrites=compoundWriteRemoveWrite(e.visibleWrites,r.path);else{each(r.children,(t=>{e.visibleWrites=compoundWriteRemoveWrite(e.visibleWrites,pathChild(r.path,t))}))}return!0}return!1}function writeTreeRecordContainsPath_(e,t){if(e.snap)return pathContains(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&pathContains(pathChild(e.path,n),t))return!0;return!1}function writeTreeDefaultFilter_(e){return e.visible}function writeTreeLayerTree_(e,t,n){let r=CompoundWrite.empty();for(let i=0;i<e.length;++i){const o=e[i];if(t(o)){const e=o.path;let t;if(o.snap)pathContains(n,e)?(t=newRelativePath(n,e),r=compoundWriteAddWrite(r,t,o.snap)):pathContains(e,n)&&(t=newRelativePath(e,n),r=compoundWriteAddWrite(r,newEmptyPath(),o.snap.getChild(t)));else{if(!o.children)throw assertionError("WriteRecord should have .snap or .children");if(pathContains(n,e))t=newRelativePath(n,e),r=compoundWriteAddWrites(r,t,o.children);else if(pathContains(e,n))if(t=newRelativePath(e,n),pathIsEmpty(t))r=compoundWriteAddWrites(r,newEmptyPath(),o.children);else{const e=safeGet(o.children,pathGetFront(t));if(e){const n=e.getChild(pathPopFront(t));r=compoundWriteAddWrite(r,newEmptyPath(),n)}}}}}return r}function writeTreeCalcCompleteEventCache(e,t,n,r,i){if(r||i){const o=compoundWriteChildCompoundWrite(e.visibleWrites,t);if(!i&&compoundWriteIsEmpty(o))return n;if(i||null!=n||compoundWriteHasCompleteWrite(o,newEmptyPath())){const filter=function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(pathContains(e.path,t)||pathContains(t,e.path))};return compoundWriteApply(writeTreeLayerTree_(e.allWrites,filter,t),n||ChildrenNode.EMPTY_NODE)}return null}{const r=compoundWriteGetCompleteNode(e.visibleWrites,t);if(null!=r)return r;{const r=compoundWriteChildCompoundWrite(e.visibleWrites,t);if(compoundWriteIsEmpty(r))return n;if(null!=n||compoundWriteHasCompleteWrite(r,newEmptyPath())){return compoundWriteApply(r,n||ChildrenNode.EMPTY_NODE)}return null}}}function writeTreeRefCalcCompleteEventCache(e,t,n,r){return writeTreeCalcCompleteEventCache(e.writeTree,e.treePath,t,n,r)}function writeTreeRefCalcCompleteEventChildren(e,t){return function writeTreeCalcCompleteEventChildren(e,t,n){let r=ChildrenNode.EMPTY_NODE;const i=compoundWriteGetCompleteNode(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(G,((e,t)=>{r=r.updateImmediateChild(e,t)})),r;if(n){const i=compoundWriteChildCompoundWrite(e.visibleWrites,t);return n.forEachChild(G,((e,t)=>{const n=compoundWriteApply(compoundWriteChildCompoundWrite(i,new Path(e)),t);r=r.updateImmediateChild(e,n)})),compoundWriteGetCompleteChildren(i).forEach((e=>{r=r.updateImmediateChild(e.name,e.node)})),r}return compoundWriteGetCompleteChildren(compoundWriteChildCompoundWrite(e.visibleWrites,t)).forEach((e=>{r=r.updateImmediateChild(e.name,e.node)})),r}(e.writeTree,e.treePath,t)}function writeTreeRefCalcEventCacheAfterServerOverwrite(e,t,n,r){return function writeTreeCalcEventCacheAfterServerOverwrite(e,t,n,r,i){assert(r||i,"Either existingEventSnap or existingServerSnap must exist");const o=pathChild(t,n);if(compoundWriteHasCompleteWrite(e.visibleWrites,o))return null;{const t=compoundWriteChildCompoundWrite(e.visibleWrites,o);return compoundWriteIsEmpty(t)?i.getChild(n):compoundWriteApply(t,i.getChild(n))}}(e.writeTree,e.treePath,t,n,r)}function writeTreeRefShadowingWrite(e,t){return function writeTreeShadowingWrite(e,t){return compoundWriteGetCompleteNode(e.visibleWrites,t)}(e.writeTree,pathChild(e.treePath,t))}function writeTreeRefCalcIndexedSlice(e,t,n,r,i,o){return function writeTreeCalcIndexedSlice(e,t,n,r,i,o,s){let a;const l=compoundWriteChildCompoundWrite(e.visibleWrites,t),h=compoundWriteGetCompleteNode(l,newEmptyPath());if(null!=h)a=h;else{if(null==n)return[];a=compoundWriteApply(l,n)}if(a=a.withIndex(s),a.isEmpty()||a.isLeafNode())return[];{const e=[],t=s.getCompare(),n=o?a.getReverseIteratorFrom(r,s):a.getIteratorFrom(r,s);let l=n.getNext();for(;l&&e.length<i;)0!==t(l,r)&&e.push(l),l=n.getNext();return e}}(e.writeTree,e.treePath,t,n,r,i,o)}function writeTreeRefCalcCompleteChild(e,t,n){return function writeTreeCalcCompleteChild(e,t,n,r){const i=pathChild(t,n),o=compoundWriteGetCompleteNode(e.visibleWrites,i);if(null!=o)return o;if(r.isCompleteForChild(n))return compoundWriteApply(compoundWriteChildCompoundWrite(e.visibleWrites,i),r.getNode().getImmediateChild(n));return null}(e.writeTree,e.treePath,t,n)}function writeTreeRefChild(e,t){return newWriteTreeRef(pathChild(e.treePath,t),e.writeTree)}function newWriteTreeRef(e,t){return{treePath:e,writeTree:t}}class ChildChangeAccumulator{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,n=e.childName;assert("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),assert(".priority"!==n,"Only non-priority child changes can be tracked.");const r=this.changeMap.get(n);if(r){const i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,changeChildChanged(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,changeChildRemoved(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,changeChildAdded(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw assertionError("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,changeChildChanged(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const Y=new class NoCompleteChildSource_{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class WriteTreeCompleteChildSource{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{const t=null!=this.optCompleteServerCache_?new CacheNode(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return writeTreeRefCalcCompleteChild(this.writes_,e,t)}}getChildAfterChild(e,t,n){const r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:viewCacheGetCompleteServerSnap(this.viewCache_),i=writeTreeRefCalcIndexedSlice(this.writes_,r,t,1,n,e);return 0===i.length?null:i[0]}}function viewProcessorApplyOperation(e,t,n,r,i){const o=new ChildChangeAccumulator;let s,a;if(n.type===z.OVERWRITE){const l=n;l.source.fromUser?s=viewProcessorApplyUserOverwrite(e,t,l.path,l.snap,r,i,o):(assert(l.source.fromServer,"Unknown source."),a=l.source.tagged||t.serverCache.isFiltered()&&!pathIsEmpty(l.path),s=viewProcessorApplyServerOverwrite(e,t,l.path,l.snap,r,i,a,o))}else if(n.type===z.MERGE){const l=n;l.source.fromUser?s=function viewProcessorApplyUserMerge(e,t,n,r,i,o,s){let a=t;return r.foreach(((r,l)=>{const h=pathChild(n,r);viewProcessorCacheHasChild(t,pathGetFront(h))&&(a=viewProcessorApplyUserOverwrite(e,a,h,l,i,o,s))})),r.foreach(((r,l)=>{const h=pathChild(n,r);viewProcessorCacheHasChild(t,pathGetFront(h))||(a=viewProcessorApplyUserOverwrite(e,a,h,l,i,o,s))})),a}(e,t,l.path,l.children,r,i,o):(assert(l.source.fromServer,"Unknown source."),a=l.source.tagged||t.serverCache.isFiltered(),s=viewProcessorApplyServerMerge(e,t,l.path,l.children,r,i,a,o))}else if(n.type===z.ACK_USER_WRITE){const a=n;s=a.revert?function viewProcessorRevertUserWrite(e,t,n,r,i,o){let s;if(null!=writeTreeRefShadowingWrite(r,n))return t;{const a=new WriteTreeCompleteChildSource(r,t,i),l=t.eventCache.getNode();let h;if(pathIsEmpty(n)||".priority"===pathGetFront(n)){let n;if(t.serverCache.isFullyInitialized())n=writeTreeRefCalcCompleteEventCache(r,viewCacheGetCompleteServerSnap(t));else{const e=t.serverCache.getNode();assert(e instanceof ChildrenNode,"serverChildren would be complete if leaf node"),n=writeTreeRefCalcCompleteEventChildren(r,e)}h=e.filter.updateFullNode(l,n,o)}else{const i=pathGetFront(n);let c=writeTreeRefCalcCompleteChild(r,i,t.serverCache);null==c&&t.serverCache.isCompleteForChild(i)&&(c=l.getImmediateChild(i)),h=null!=c?e.filter.updateChild(l,i,c,pathPopFront(n),a,o):t.eventCache.getNode().hasChild(i)?e.filter.updateChild(l,i,ChildrenNode.EMPTY_NODE,pathPopFront(n),a,o):l,h.isEmpty()&&t.serverCache.isFullyInitialized()&&(s=writeTreeRefCalcCompleteEventCache(r,viewCacheGetCompleteServerSnap(t)),s.isLeafNode()&&(h=e.filter.updateFullNode(h,s,o)))}return s=t.serverCache.isFullyInitialized()||null!=writeTreeRefShadowingWrite(r,newEmptyPath()),viewCacheUpdateEventSnap(t,h,s,e.filter.filtersNodes())}}(e,t,a.path,r,i,o):function viewProcessorAckUserWrite(e,t,n,r,i,o,s){if(null!=writeTreeRefShadowingWrite(i,n))return t;const a=t.serverCache.isFiltered(),l=t.serverCache;if(null!=r.value){if(pathIsEmpty(n)&&l.isFullyInitialized()||l.isCompleteForPath(n))return viewProcessorApplyServerOverwrite(e,t,n,l.getNode().getChild(n),i,o,a,s);if(pathIsEmpty(n)){let r=new ImmutableTree(null);return l.getNode().forEachChild(D,((e,t)=>{r=r.set(new Path(e),t)})),viewProcessorApplyServerMerge(e,t,n,r,i,o,a,s)}return t}{let h=new ImmutableTree(null);return r.foreach(((e,t)=>{const r=pathChild(n,e);l.isCompleteForPath(r)&&(h=h.set(e,l.getNode().getChild(r)))})),viewProcessorApplyServerMerge(e,t,n,h,i,o,a,s)}}(e,t,a.path,a.affectedTree,r,i,o)}else{if(n.type!==z.LISTEN_COMPLETE)throw assertionError("Unknown operation type: "+n.type);s=function viewProcessorListenComplete(e,t,n,r,i){const o=t.serverCache,s=viewCacheUpdateServerSnap(t,o.getNode(),o.isFullyInitialized()||pathIsEmpty(n),o.isFiltered());return viewProcessorGenerateEventCacheAfterServerEvent(e,s,n,r,Y,i)}(e,t,n.path,r,o)}const l=o.getChanges();return function viewProcessorMaybeAddValueEvent(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){const i=r.getNode().isLeafNode()||r.getNode().isEmpty(),o=viewCacheGetCompleteEventSnap(e);(n.length>0||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(o)||!r.getNode().getPriority().equals(o.getPriority()))&&n.push(changeValue(viewCacheGetCompleteEventSnap(t)))}}(t,s,l),{viewCache:s,changes:l}}function viewProcessorGenerateEventCacheAfterServerEvent(e,t,n,r,i,o){const s=t.eventCache;if(null!=writeTreeRefShadowingWrite(r,n))return t;{let a,l;if(pathIsEmpty(n))if(assert(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t.serverCache.isFiltered()){const n=viewCacheGetCompleteServerSnap(t),i=writeTreeRefCalcCompleteEventChildren(r,n instanceof ChildrenNode?n:ChildrenNode.EMPTY_NODE);a=e.filter.updateFullNode(t.eventCache.getNode(),i,o)}else{const n=writeTreeRefCalcCompleteEventCache(r,viewCacheGetCompleteServerSnap(t));a=e.filter.updateFullNode(t.eventCache.getNode(),n,o)}else{const h=pathGetFront(n);if(".priority"===h){assert(1===pathGetLength(n),"Can't have a priority with additional path components");const i=s.getNode();l=t.serverCache.getNode();const o=writeTreeRefCalcEventCacheAfterServerOverwrite(r,n,i,l);a=null!=o?e.filter.updatePriority(i,o):s.getNode()}else{const c=pathPopFront(n);let d;if(s.isCompleteForChild(h)){l=t.serverCache.getNode();const e=writeTreeRefCalcEventCacheAfterServerOverwrite(r,n,s.getNode(),l);d=null!=e?s.getNode().getImmediateChild(h).updateChild(c,e):s.getNode().getImmediateChild(h)}else d=writeTreeRefCalcCompleteChild(r,h,t.serverCache);a=null!=d?e.filter.updateChild(s.getNode(),h,d,c,i,o):s.getNode()}}return viewCacheUpdateEventSnap(t,a,s.isFullyInitialized()||pathIsEmpty(n),e.filter.filtersNodes())}}function viewProcessorApplyServerOverwrite(e,t,n,r,i,o,s,a){const l=t.serverCache;let h;const c=s?e.filter:e.filter.getIndexedFilter();if(pathIsEmpty(n))h=c.updateFullNode(l.getNode(),r,null);else if(c.filtersNodes()&&!l.isFiltered()){const e=l.getNode().updateChild(n,r);h=c.updateFullNode(l.getNode(),e,null)}else{const e=pathGetFront(n);if(!l.isCompleteForPath(n)&&pathGetLength(n)>1)return t;const i=pathPopFront(n),o=l.getNode().getImmediateChild(e).updateChild(i,r);h=".priority"===e?c.updatePriority(l.getNode(),o):c.updateChild(l.getNode(),e,o,i,Y,null)}const d=viewCacheUpdateServerSnap(t,h,l.isFullyInitialized()||pathIsEmpty(n),c.filtersNodes());return viewProcessorGenerateEventCacheAfterServerEvent(e,d,n,i,new WriteTreeCompleteChildSource(i,d,o),a)}function viewProcessorApplyUserOverwrite(e,t,n,r,i,o,s){const a=t.eventCache;let l,h;const c=new WriteTreeCompleteChildSource(i,t,o);if(pathIsEmpty(n))h=e.filter.updateFullNode(t.eventCache.getNode(),r,s),l=viewCacheUpdateEventSnap(t,h,!0,e.filter.filtersNodes());else{const i=pathGetFront(n);if(".priority"===i)h=e.filter.updatePriority(t.eventCache.getNode(),r),l=viewCacheUpdateEventSnap(t,h,a.isFullyInitialized(),a.isFiltered());else{const o=pathPopFront(n),h=a.getNode().getImmediateChild(i);let d;if(pathIsEmpty(o))d=r;else{const e=c.getCompleteChild(i);d=null!=e?".priority"===pathGetBack(o)&&e.getChild(pathParent(o)).isEmpty()?e:e.updateChild(o,r):ChildrenNode.EMPTY_NODE}if(h.equals(d))l=t;else{l=viewCacheUpdateEventSnap(t,e.filter.updateChild(a.getNode(),i,d,o,c,s),a.isFullyInitialized(),e.filter.filtersNodes())}}}return l}function viewProcessorCacheHasChild(e,t){return e.eventCache.isCompleteForChild(t)}function viewProcessorApplyMerge(e,t,n){return n.foreach(((e,n)=>{t=t.updateChild(e,n)})),t}function viewProcessorApplyServerMerge(e,t,n,r,i,o,s,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let l,h=t;l=pathIsEmpty(n)?r:new ImmutableTree(null).setTree(n,r);const c=t.serverCache.getNode();return l.children.inorderTraversal(((n,r)=>{if(c.hasChild(n)){const l=viewProcessorApplyMerge(0,t.serverCache.getNode().getImmediateChild(n),r);h=viewProcessorApplyServerOverwrite(e,h,new Path(n),l,i,o,s,a)}})),l.children.inorderTraversal(((n,r)=>{const l=!t.serverCache.isCompleteForChild(n)&&null===r.value;if(!c.hasChild(n)&&!l){const l=viewProcessorApplyMerge(0,t.serverCache.getNode().getImmediateChild(n),r);h=viewProcessorApplyServerOverwrite(e,h,new Path(n),l,i,o,s,a)}})),h}class View{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new IndexedFilter(n.getIndex()),i=function queryParamsGetNodeFilter(e){return e.loadsAllData()?new IndexedFilter(e.getIndex()):e.hasLimit()?new LimitedFilter(e):new RangedFilter(e)}(n);this.processor_=function newViewProcessor(e){return{filter:e}}(i);const o=t.serverCache,s=t.eventCache,a=r.updateFullNode(ChildrenNode.EMPTY_NODE,o.getNode(),null),l=i.updateFullNode(ChildrenNode.EMPTY_NODE,s.getNode(),null),h=new CacheNode(a,o.isFullyInitialized(),r.filtersNodes()),c=new CacheNode(l,s.isFullyInitialized(),i.filtersNodes());this.viewCache_=newViewCache(c,h),this.eventGenerator_=new EventGenerator(this.query_)}get query(){return this.query_}}function viewGetCompleteServerCache(e,t){const n=viewCacheGetCompleteServerSnap(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!pathIsEmpty(t)&&!n.getImmediateChild(pathGetFront(t)).isEmpty())?n.getChild(t):null}function viewIsEmpty(e){return 0===e.eventRegistrations_.length}function viewRemoveEventRegistration(e,t,n){const r=[];if(n){assert(null==t,"A cancel should cancel all event registrations.");const i=e.query._path;e.eventRegistrations_.forEach((e=>{const t=e.createCancelEvent(n,i);t&&r.push(t)}))}if(t){let n=[];for(let r=0;r<e.eventRegistrations_.length;++r){const i=e.eventRegistrations_[r];if(i.matches(t)){if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(r+1));break}}else n.push(i)}e.eventRegistrations_=n}else e.eventRegistrations_=[];return r}function viewApplyOperation(e,t,n,r){t.type===z.MERGE&&null!==t.source.queryId&&(assert(viewCacheGetCompleteServerSnap(e.viewCache_),"We should always have a full cache before handling merges"),assert(viewCacheGetCompleteEventSnap(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,o=viewProcessorApplyOperation(e.processor_,i,t,n,r);return function viewProcessorAssertIndexed(e,t){assert(t.eventCache.getNode().isIndexed(e.filter.getIndex()),"Event snap not indexed"),assert(t.serverCache.getNode().isIndexed(e.filter.getIndex()),"Server snap not indexed")}(e.processor_,o.viewCache),assert(o.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=o.viewCache,viewGenerateEventsForChanges_(e,o.changes,o.viewCache.eventCache.getNode(),null)}function viewGenerateEventsForChanges_(e,t,n,r){const i=r?[r]:e.eventRegistrations_;return function eventGeneratorGenerateEventsForChanges(e,t,n,r){const i=[],o=[];return t.forEach((t=>{"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&o.push(function changeChildMoved(e,t){return{type:"child_moved",snapshotNode:t,childName:e}}(t.childName,t.snapshotNode))})),eventGeneratorGenerateEventsForType(e,i,"child_removed",t,r,n),eventGeneratorGenerateEventsForType(e,i,"child_added",t,r,n),eventGeneratorGenerateEventsForType(e,i,"child_moved",o,r,n),eventGeneratorGenerateEventsForType(e,i,"child_changed",t,r,n),eventGeneratorGenerateEventsForType(e,i,"value",t,r,n),i}(e.eventGenerator_,t,n,i)}let $,J;class SyncPoint{constructor(){this.views=new Map}}function syncPointApplyOperation(e,t,n,r){const i=t.source.queryId;if(null!==i){const o=e.views.get(i);return assert(null!=o,"SyncTree gave us an op for an invalid query."),viewApplyOperation(o,t,n,r)}{let i=[];for(const o of e.views.values())i=i.concat(viewApplyOperation(o,t,n,r));return i}}function syncPointGetView(e,t,n,r,i){const o=t._queryIdentifier,s=e.views.get(o);if(!s){let e=writeTreeRefCalcCompleteEventCache(n,i?r:null),o=!1;e?o=!0:r instanceof ChildrenNode?(e=writeTreeRefCalcCompleteEventChildren(n,r),o=!1):(e=ChildrenNode.EMPTY_NODE,o=!1);const s=newViewCache(new CacheNode(e,o,!1),new CacheNode(r,i,!1));return new View(t,s)}return s}function syncPointAddEventRegistration(e,t,n,r,i,o){const s=syncPointGetView(e,t,r,i,o);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,s),function viewAddEventRegistration(e,t){e.eventRegistrations_.push(t)}(s,n),function viewGetInitialEvents(e,t){const n=e.viewCache_.eventCache,r=[];n.getNode().isLeafNode()||n.getNode().forEachChild(G,((e,t)=>{r.push(changeChildAdded(e,t))}));return n.isFullyInitialized()&&r.push(changeValue(n.getNode())),viewGenerateEventsForChanges_(e,r,n.getNode(),t)}(s,n)}function syncPointRemoveEventRegistration(e,t,n,r){const i=t._queryIdentifier,o=[];let s=[];const a=syncPointHasCompleteView(e);if("default"===i)for(const[t,i]of e.views.entries())s=s.concat(viewRemoveEventRegistration(i,n,r)),viewIsEmpty(i)&&(e.views.delete(t),i.query._queryParams.loadsAllData()||o.push(i.query));else{const t=e.views.get(i);t&&(s=s.concat(viewRemoveEventRegistration(t,n,r)),viewIsEmpty(t)&&(e.views.delete(i),t.query._queryParams.loadsAllData()||o.push(t.query)))}return a&&!syncPointHasCompleteView(e)&&o.push(new(function syncPointGetReferenceConstructor(){return assert($,"Reference.ts has not been loaded"),$}())(t._repo,t._path)),{removed:o,events:s}}function syncPointGetQueryViews(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function syncPointGetCompleteServerCache(e,t){let n=null;for(const r of e.views.values())n=n||viewGetCompleteServerCache(r,t);return n}function syncPointViewForQuery(e,t){if(t._queryParams.loadsAllData())return syncPointGetCompleteView(e);{const n=t._queryIdentifier;return e.views.get(n)}}function syncPointViewExistsForQuery(e,t){return null!=syncPointViewForQuery(e,t)}function syncPointHasCompleteView(e){return null!=syncPointGetCompleteView(e)}function syncPointGetCompleteView(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let X=1;class SyncTree{constructor(e){this.listenProvider_=e,this.syncPointTree_=new ImmutableTree(null),this.pendingWriteTree_=function newWriteTree(){return{visibleWrites:CompoundWrite.empty(),allWrites:[],lastWriteId:-1}}(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function syncTreeApplyUserOverwrite(e,t,n,r,i){return function writeTreeAddOverwrite(e,t,n,r,i){assert(r>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===i&&(i=!0),e.allWrites.push({path:t,snap:n,writeId:r,visible:i}),i&&(e.visibleWrites=compoundWriteAddWrite(e.visibleWrites,t,n)),e.lastWriteId=r}(e.pendingWriteTree_,t,n,r,i),i?syncTreeApplyOperationToSyncPoints_(e,new Overwrite({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,n)):[]}function syncTreeApplyUserMerge(e,t,n,r){!function writeTreeAddMerge(e,t,n,r){assert(r>e.lastWriteId,"Stacking an older merge on top of newer ones"),e.allWrites.push({path:t,children:n,writeId:r,visible:!0}),e.visibleWrites=compoundWriteAddWrites(e.visibleWrites,t,n),e.lastWriteId=r}(e.pendingWriteTree_,t,n,r);const i=ImmutableTree.fromObject(n);return syncTreeApplyOperationToSyncPoints_(e,new Merge({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,i))}function syncTreeAckUserWrite(e,t,n=!1){const r=function writeTreeGetWrite(e,t){for(let n=0;n<e.allWrites.length;n++){const r=e.allWrites[n];if(r.writeId===t)return r}return null}(e.pendingWriteTree_,t);if(writeTreeRemoveWrite(e.pendingWriteTree_,t)){let t=new ImmutableTree(null);return null!=r.snap?t=t.set(newEmptyPath(),!0):each(r.children,(e=>{t=t.set(new Path(e),!0)})),syncTreeApplyOperationToSyncPoints_(e,new AckUserWrite(r.path,t,n))}return[]}function syncTreeApplyServerOverwrite(e,t,n){return syncTreeApplyOperationToSyncPoints_(e,new Overwrite({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,n))}function syncTreeRemoveEventRegistration(e,t,n,r,i=!1){const o=t._path,s=e.syncPointTree_.get(o);let a=[];if(s&&("default"===t._queryIdentifier||syncPointViewExistsForQuery(s,t))){const l=syncPointRemoveEventRegistration(s,t,n,r);(function syncPointIsEmpty(e){return 0===e.views.size})(s)&&(e.syncPointTree_=e.syncPointTree_.remove(o));const h=l.removed;if(a=l.events,!i){const n=-1!==h.findIndex((e=>e._queryParams.loadsAllData())),i=e.syncPointTree_.findOnPath(o,((e,t)=>syncPointHasCompleteView(t)));if(n&&!i){const t=e.syncPointTree_.subtree(o);if(!t.isEmpty()){const n=function syncTreeCollectDistinctViewsForSubTree_(e){return e.fold(((e,t,n)=>{if(t&&syncPointHasCompleteView(t)){return[syncPointGetCompleteView(t)]}{let e=[];return t&&(e=syncPointGetQueryViews(t)),each(n,((t,n)=>{e=e.concat(n)})),e}}))}(t);for(let t=0;t<n.length;++t){const r=n[t],i=r.query,o=syncTreeCreateListenerForView_(e,r);e.listenProvider_.startListening(syncTreeQueryForListening_(i),syncTreeTagForQuery(e,i),o.hashFn,o.onComplete)}}}if(!i&&h.length>0&&!r)if(n){const n=null;e.listenProvider_.stopListening(syncTreeQueryForListening_(t),n)}else h.forEach((t=>{const n=e.queryToTagMap.get(syncTreeMakeQueryKey_(t));e.listenProvider_.stopListening(syncTreeQueryForListening_(t),n)}))}!function syncTreeRemoveTags_(e,t){for(let n=0;n<t.length;++n){const r=t[n];if(!r._queryParams.loadsAllData()){const t=syncTreeMakeQueryKey_(r),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}(e,h)}return a}function syncTreeApplyTaggedQueryOverwrite(e,t,n,r){const i=syncTreeQueryKeyForTag_(e,r);if(null!=i){const r=syncTreeParseQueryKey_(i),o=r.path,s=r.queryId,a=newRelativePath(o,t);return syncTreeApplyTaggedOperation_(e,o,new Overwrite(newOperationSourceServerTaggedQuery(s),a,n))}return[]}function syncTreeAddEventRegistration(e,t,n,r=!1){const i=t._path;let o=null,s=!1;e.syncPointTree_.foreachOnPath(i,((e,t)=>{const n=newRelativePath(e,i);o=o||syncPointGetCompleteServerCache(t,n),s=s||syncPointHasCompleteView(t)}));let a,l=e.syncPointTree_.get(i);if(l?(s=s||syncPointHasCompleteView(l),o=o||syncPointGetCompleteServerCache(l,newEmptyPath())):(l=new SyncPoint,e.syncPointTree_=e.syncPointTree_.set(i,l)),null!=o)a=!0;else{a=!1,o=ChildrenNode.EMPTY_NODE;e.syncPointTree_.subtree(i).foreachChild(((e,t)=>{const n=syncPointGetCompleteServerCache(t,newEmptyPath());n&&(o=o.updateImmediateChild(e,n))}))}const h=syncPointViewExistsForQuery(l,t);if(!h&&!t._queryParams.loadsAllData()){const n=syncTreeMakeQueryKey_(t);assert(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");const r=function syncTreeGetNextQueryTag_(){return X++}();e.queryToTagMap.set(n,r),e.tagToQueryMap.set(r,n)}let c=syncPointAddEventRegistration(l,t,n,writeTreeChildWrites(e.pendingWriteTree_,i),o,a);if(!h&&!s&&!r){const n=syncPointViewForQuery(l,t);c=c.concat(function syncTreeSetupListener_(e,t,n){const r=t._path,i=syncTreeTagForQuery(e,t),o=syncTreeCreateListenerForView_(e,n),s=e.listenProvider_.startListening(syncTreeQueryForListening_(t),i,o.hashFn,o.onComplete),a=e.syncPointTree_.subtree(r);if(i)assert(!syncPointHasCompleteView(a.value),"If we're adding a query, it shouldn't be shadowed");else{const t=a.fold(((e,t,n)=>{if(!pathIsEmpty(e)&&t&&syncPointHasCompleteView(t))return[syncPointGetCompleteView(t).query];{let e=[];return t&&(e=e.concat(syncPointGetQueryViews(t).map((e=>e.query)))),each(n,((t,n)=>{e=e.concat(n)})),e}}));for(let n=0;n<t.length;++n){const r=t[n];e.listenProvider_.stopListening(syncTreeQueryForListening_(r),syncTreeTagForQuery(e,r))}}return s}(e,t,n))}return c}function syncTreeCalcCompleteEventCache(e,t,n){const r=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(t,((e,n)=>{const r=syncPointGetCompleteServerCache(n,newRelativePath(e,t));if(r)return r}));return writeTreeCalcCompleteEventCache(r,t,i,n,!0)}function syncTreeGetServerValue(e,t){const n=t._path;let r=null;e.syncPointTree_.foreachOnPath(n,((e,t)=>{const i=newRelativePath(e,n);r=r||syncPointGetCompleteServerCache(t,i)}));let i=e.syncPointTree_.get(n);i?r=r||syncPointGetCompleteServerCache(i,newEmptyPath()):(i=new SyncPoint,e.syncPointTree_=e.syncPointTree_.set(n,i));const o=null!=r,s=o?new CacheNode(r,!0,!1):null;return function viewGetCompleteNode(e){return viewCacheGetCompleteEventSnap(e.viewCache_)}(syncPointGetView(i,t,writeTreeChildWrites(e.pendingWriteTree_,t._path),o?s.getNode():ChildrenNode.EMPTY_NODE,o))}function syncTreeApplyOperationToSyncPoints_(e,t){return syncTreeApplyOperationHelper_(t,e.syncPointTree_,null,writeTreeChildWrites(e.pendingWriteTree_,newEmptyPath()))}function syncTreeApplyOperationHelper_(e,t,n,r){if(pathIsEmpty(e.path))return syncTreeApplyOperationDescendantsHelper_(e,t,n,r);{const i=t.get(newEmptyPath());null==n&&null!=i&&(n=syncPointGetCompleteServerCache(i,newEmptyPath()));let o=[];const s=pathGetFront(e.path),a=e.operationForChild(s),l=t.children.get(s);if(l&&a){const e=n?n.getImmediateChild(s):null,t=writeTreeRefChild(r,s);o=o.concat(syncTreeApplyOperationHelper_(a,l,e,t))}return i&&(o=o.concat(syncPointApplyOperation(i,e,r,n))),o}}function syncTreeApplyOperationDescendantsHelper_(e,t,n,r){const i=t.get(newEmptyPath());null==n&&null!=i&&(n=syncPointGetCompleteServerCache(i,newEmptyPath()));let o=[];return t.children.inorderTraversal(((t,i)=>{const s=n?n.getImmediateChild(t):null,a=writeTreeRefChild(r,t),l=e.operationForChild(t);l&&(o=o.concat(syncTreeApplyOperationDescendantsHelper_(l,i,s,a)))})),i&&(o=o.concat(syncPointApplyOperation(i,e,r,n))),o}function syncTreeCreateListenerForView_(e,t){const n=t.query,r=syncTreeTagForQuery(e,n);return{hashFn:()=>{const e=function viewGetServerCache(e){return e.viewCache_.serverCache.getNode()}(t)||ChildrenNode.EMPTY_NODE;return e.hash()},onComplete:t=>{if("ok"===t)return r?function syncTreeApplyTaggedListenComplete(e,t,n){const r=syncTreeQueryKeyForTag_(e,n);if(r){const n=syncTreeParseQueryKey_(r),i=n.path,o=n.queryId,s=newRelativePath(i,t);return syncTreeApplyTaggedOperation_(e,i,new ListenComplete(newOperationSourceServerTaggedQuery(o),s))}return[]}(e,n._path,r):function syncTreeApplyListenComplete(e,t){return syncTreeApplyOperationToSyncPoints_(e,new ListenComplete({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t))}(e,n._path);{const r=function errorForServerCode(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r}(t,n);return syncTreeRemoveEventRegistration(e,n,null,r)}}}}function syncTreeTagForQuery(e,t){const n=syncTreeMakeQueryKey_(t);return e.queryToTagMap.get(n)}function syncTreeMakeQueryKey_(e){return e._path.toString()+"$"+e._queryIdentifier}function syncTreeQueryKeyForTag_(e,t){return e.tagToQueryMap.get(t)}function syncTreeParseQueryKey_(e){const t=e.indexOf("$");return assert(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new Path(e.substr(0,t))}}function syncTreeApplyTaggedOperation_(e,t,n){const r=e.syncPointTree_.get(t);assert(r,"Missing sync point for query tag that we're tracking");return syncPointApplyOperation(r,n,writeTreeChildWrites(e.pendingWriteTree_,t),null)}function syncTreeQueryForListening_(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new(function syncTreeGetReferenceConstructor(){return assert(J,"Reference.ts has not been loaded"),J}())(e._repo,e._path):e}class ExistingValueProvider{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new ExistingValueProvider(t)}node(){return this.node_}}class DeferredValueProvider{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){const t=pathChild(this.path_,e);return new DeferredValueProvider(this.syncTree_,t)}node(){return syncTreeCalcCompleteEventCache(this.syncTree_,this.path_)}}const resolveDeferredLeafValue=function(e,t,n){return e&&"object"==typeof e?(assert(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?resolveScalarDeferredValue(e[".sv"],t,n):"object"==typeof e[".sv"]?resolveComplexDeferredValue(e[".sv"],t):void assert(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},resolveScalarDeferredValue=function(e,t,n){if("timestamp"===e)return n.timestamp;assert(!1,"Unexpected server value: "+e)},resolveComplexDeferredValue=function(e,t,n){e.hasOwnProperty("increment")||assert(!1,"Unexpected server value: "+JSON.stringify(e,null,2));const r=e.increment;"number"!=typeof r&&assert(!1,"Unexpected increment value: "+r);const i=t.node();if(assert(null!=i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;const o=i.getValue();return"number"!=typeof o?r:o+r},resolveDeferredValueTree=function(e,t,n,r){return resolveDeferredValue(t,new DeferredValueProvider(n,e),r)},resolveDeferredValueSnapshot=function(e,t,n){return resolveDeferredValue(e,new ExistingValueProvider(t),n)};function resolveDeferredValue(e,t,n){const r=e.getPriority().val(),i=resolveDeferredLeafValue(r,t.getImmediateChild(".priority"),n);let o;if(e.isLeafNode()){const r=e,o=resolveDeferredLeafValue(r.getValue(),t,n);return o!==r.getValue()||i!==r.getPriority().val()?new LeafNode(o,nodeFromJSON(i)):e}{const r=e;return o=r,i!==r.getPriority().val()&&(o=o.updatePriority(new LeafNode(i))),r.forEachChild(G,((e,r)=>{const i=resolveDeferredValue(r,t.getImmediateChild(e),n);i!==r&&(o=o.updateImmediateChild(e,i))})),o}}class Tree{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function treeSubTree(e,t){let n=t instanceof Path?t:new Path(t),r=e,i=pathGetFront(n);for(;null!==i;){const e=safeGet(r.node.children,i)||{children:{},childCount:0};r=new Tree(i,r,e),n=pathPopFront(n),i=pathGetFront(n)}return r}function treeGetValue(e){return e.node.value}function treeSetValue(e,t){e.node.value=t,treeUpdateParents(e)}function treeHasChildren(e){return e.node.childCount>0}function treeForEachChild(e,t){each(e.node.children,((n,r)=>{t(new Tree(n,e,r))}))}function treeForEachDescendant(e,t,n,r){n&&!r&&t(e),treeForEachChild(e,(e=>{treeForEachDescendant(e,t,!0,r)})),n&&r&&t(e)}function treeGetPath(e){return new Path(null===e.parent?e.name:treeGetPath(e.parent)+"/"+e.name)}function treeUpdateParents(e){null!==e.parent&&function treeUpdateChild(e,t,n){const r=function treeIsEmpty(e){return void 0===treeGetValue(e)&&!treeHasChildren(e)}(n),i=contains(e.node.children,t);r&&i?(delete e.node.children[t],e.node.childCount--,treeUpdateParents(e)):r||i||(e.node.children[t]=n.node,e.node.childCount++,treeUpdateParents(e))}(e.parent,e.name,e)}const Z=/[\[\].#$\/\u0000-\u001F\u007F]/,ee=/[\[\].#$\u0000-\u001F\u007F]/,te=10485760,isValidKey=function(e){return"string"==typeof e&&0!==e.length&&!Z.test(e)},isValidPathString=function(e){return"string"==typeof e&&0!==e.length&&!ee.test(e)},isValidPriority=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!isInvalidJSONNumber(e)||e&&"object"==typeof e&&contains(e,".sv")},validateFirebaseDataArg=function(e,t,n,r){r&&void 0===t||validateFirebaseData(errorPrefix(e,"value"),t,n)},validateFirebaseData=function(e,t,n){const r=n instanceof Path?new ValidationPath(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+validationPathToErrorString(r));if("function"==typeof t)throw new Error(e+"contains a function "+validationPathToErrorString(r)+" with contents = "+t.toString());if(isInvalidJSONNumber(t))throw new Error(e+"contains "+t.toString()+" "+validationPathToErrorString(r));if("string"==typeof t&&t.length>te/3&&stringLength(t)>te)throw new Error(e+"contains a string greater than "+te+" utf8 bytes "+validationPathToErrorString(r)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,i=!1;if(each(t,((t,o)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(i=!0,!isValidKey(t)))throw new Error(e+" contains an invalid key ("+t+") "+validationPathToErrorString(r)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');!function validationPathPush(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=stringLength(t),validationPathCheckValid(e)}(r,t),validateFirebaseData(e,o,r),function validationPathPop(e){const t=e.parts_.pop();e.byteLength_-=stringLength(t),e.parts_.length>0&&(e.byteLength_-=1)}(r)})),n&&i)throw new Error(e+' contains ".value" child '+validationPathToErrorString(r)+" in addition to actual children.")}},validateFirebaseMergeDataArg=function(e,t,n,r){if(r&&void 0===t)return;const i=errorPrefix(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");const o=[];each(t,((e,t)=>{const r=new Path(e);if(validateFirebaseData(i,t,pathChild(n,r)),".priority"===pathGetBack(r)&&!isValidPriority(t))throw new Error(i+"contains an invalid value for '"+r.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");o.push(r)})),function(e,t){let n,r;for(n=0;n<t.length;n++){r=t[n];const i=pathSlice(r);for(let t=0;t<i.length;t++)if(".priority"===i[t]&&t===i.length-1);else if(!isValidKey(i[t]))throw new Error(e+"contains an invalid key ("+i[t]+") in path "+r.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}t.sort(pathCompare);let i=null;for(n=0;n<t.length;n++){if(r=t[n],null!==i&&pathContains(i,r))throw new Error(e+"contains a path "+i.toString()+" that is ancestor of another path "+r.toString());i=r}}(i,o)},validatePriority=function(e,t,n){if(!n||void 0!==t){if(isInvalidJSONNumber(t))throw new Error(errorPrefix(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!isValidPriority(t))throw new Error(errorPrefix(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},validateKey=function(e,t,n,r){if(!(r&&void 0===n||isValidKey(n)))throw new Error(errorPrefix(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},validatePathString=function(e,t,n,r){if(!(r&&void 0===n||isValidPathString(n)))throw new Error(errorPrefix(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},validateWritablePath=function(e,t){if(".info"===pathGetFront(t))throw new Error(e+" failed = Can't modify data under /.info/")},validateUrl=function(e,t){const n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!isValidKey(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),isValidPathString(e)}(n))throw new Error(errorPrefix(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class EventQueue{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function eventQueueQueueEvents(e,t){let n=null;for(let r=0;r<t.length;r++){const i=t[r],o=i.getPath();null===n||pathEquals(o,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:o}),n.events.push(i)}n&&e.eventLists_.push(n)}function eventQueueRaiseEventsAtPath(e,t,n){eventQueueQueueEvents(e,n),eventQueueRaiseQueuedEventsMatchingPredicate(e,(e=>pathEquals(e,t)))}function eventQueueRaiseEventsForChangedPath(e,t,n){eventQueueQueueEvents(e,n),eventQueueRaiseQueuedEventsMatchingPredicate(e,(e=>pathContains(e,t)||pathContains(t,e)))}function eventQueueRaiseQueuedEventsMatchingPredicate(e,t){e.recursionDepth_++;let n=!0;for(let r=0;r<e.eventLists_.length;r++){const i=e.eventLists_[r];if(i){t(i.path)?(eventListRaise(e.eventLists_[r]),e.eventLists_[r]=null):n=!1}}n&&(e.eventLists_=[]),e.recursionDepth_--}function eventListRaise(e){for(let t=0;t<e.events.length;t++){const n=e.events[t];if(null!==n){e.events[t]=null;const r=n.getEventRunner();C&&log("event: "+n.toString()),exceptionGuard(r)}}}const ne="repo_interrupt";class Repo{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new EventQueue,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=newSparseSnapshotTree(),this.transactionQueueTree_=new Tree,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function repoStart(e,t,n){if(e.stats_=statsManagerGetCollection(e.repoInfo_),e.forceRestClient_||("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0)e.server_=new ReadonlyRestClient(e.repoInfo_,((t,n,r,i)=>{repoOnDataUpdate(e,t,n,r,i)}),e.authTokenProvider_,e.appCheckProvider_),setTimeout((()=>repoOnConnectStatus(e,!0)),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{stringify(n)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new PersistentConnection(e.repoInfo_,t,((t,n,r,i)=>{repoOnDataUpdate(e,t,n,r,i)}),(t=>{repoOnConnectStatus(e,t)}),(t=>{!function repoOnServerInfoUpdate(e,t){each(t,((t,n)=>{repoUpdateInfo(e,t,n)}))}(e,t)}),e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener((t=>{e.server_.refreshAuthToken(t)})),e.appCheckProvider_.addTokenChangeListener((t=>{e.server_.refreshAppCheckToken(t.token)})),e.statsReporter_=function statsManagerGetOrCreateReporter(e,t){const n=e.toString();return k[n]||(k[n]=t()),k[n]}(e.repoInfo_,(()=>new StatsReporter(e.stats_,e.server_))),e.infoData_=new SnapshotHolder,e.infoSyncTree_=new SyncTree({startListening:(t,n,r,i)=>{let o=[];const s=e.infoData_.getNode(t._path);return s.isEmpty()||(o=syncTreeApplyServerOverwrite(e.infoSyncTree_,t._path,s),setTimeout((()=>{i("ok")}),0)),o},stopListening:()=>{}}),repoUpdateInfo(e,"connected",!1),e.serverSyncTree_=new SyncTree({startListening:(t,n,r,i)=>(e.server_.listen(t,r,n,((n,r)=>{const o=i(n,r);eventQueueRaiseEventsForChangedPath(e.eventQueue_,t._path,o)})),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function repoServerTime(e){const t=e.infoData_.getNode(new Path(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function repoGenerateServerValues(e){return(t=(t={timestamp:repoServerTime(e)})||{}).timestamp=t.timestamp||(new Date).getTime(),t;var t}function repoOnDataUpdate(e,t,n,r,i){e.dataUpdateCount++;const o=new Path(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let s=[];if(i)if(r){const t=map(n,(e=>nodeFromJSON(e)));s=function syncTreeApplyTaggedQueryMerge(e,t,n,r){const i=syncTreeQueryKeyForTag_(e,r);if(i){const r=syncTreeParseQueryKey_(i),o=r.path,s=r.queryId,a=newRelativePath(o,t),l=ImmutableTree.fromObject(n);return syncTreeApplyTaggedOperation_(e,o,new Merge(newOperationSourceServerTaggedQuery(s),a,l))}return[]}(e.serverSyncTree_,o,t,i)}else{const t=nodeFromJSON(n);s=syncTreeApplyTaggedQueryOverwrite(e.serverSyncTree_,o,t,i)}else if(r){const t=map(n,(e=>nodeFromJSON(e)));s=function syncTreeApplyServerMerge(e,t,n){const r=ImmutableTree.fromObject(n);return syncTreeApplyOperationToSyncPoints_(e,new Merge({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,r))}(e.serverSyncTree_,o,t)}else{const t=nodeFromJSON(n);s=syncTreeApplyServerOverwrite(e.serverSyncTree_,o,t)}let a=o;s.length>0&&(a=repoRerunTransactions(e,o)),eventQueueRaiseEventsForChangedPath(e.eventQueue_,a,s)}function repoOnConnectStatus(e,t){repoUpdateInfo(e,"connected",t),!1===t&&function repoRunOnDisconnectEvents(e){repoLog(e,"onDisconnectEvents");const t=repoGenerateServerValues(e),n=newSparseSnapshotTree();sparseSnapshotTreeForEachTree(e.onDisconnect_,newEmptyPath(),((r,i)=>{const o=resolveDeferredValueTree(r,i,e.serverSyncTree_,t);sparseSnapshotTreeRemember(n,r,o)}));let r=[];sparseSnapshotTreeForEachTree(n,newEmptyPath(),((t,n)=>{r=r.concat(syncTreeApplyServerOverwrite(e.serverSyncTree_,t,n));const i=repoAbortTransactions(e,t);repoRerunTransactions(e,i)})),e.onDisconnect_=newSparseSnapshotTree(),eventQueueRaiseEventsForChangedPath(e.eventQueue_,newEmptyPath(),r)}(e)}function repoUpdateInfo(e,t,n){const r=new Path("/.info/"+t),i=nodeFromJSON(n);e.infoData_.updateSnapshot(r,i);const o=syncTreeApplyServerOverwrite(e.infoSyncTree_,r,i);eventQueueRaiseEventsForChangedPath(e.eventQueue_,r,o)}function repoGetNextWriteId(e){return e.nextWriteId_++}function repoSetWithPriority(e,t,n,r,i){repoLog(e,"set",{path:t.toString(),value:n,priority:r});const o=repoGenerateServerValues(e),s=nodeFromJSON(n,r),a=syncTreeCalcCompleteEventCache(e.serverSyncTree_,t),l=resolveDeferredValueSnapshot(s,a,o),h=repoGetNextWriteId(e),c=syncTreeApplyUserOverwrite(e.serverSyncTree_,t,l,h,!0);eventQueueQueueEvents(e.eventQueue_,c),e.server_.put(t.toString(),s.val(!0),((n,r)=>{const o="ok"===n;o||warn("set at "+t+" failed: "+n);const s=syncTreeAckUserWrite(e.serverSyncTree_,h,!o);eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,s),repoCallOnCompleteCallback(e,i,n,r)}));const d=repoAbortTransactions(e,t);repoRerunTransactions(e,d),eventQueueRaiseEventsForChangedPath(e.eventQueue_,d,[])}function repoOnDisconnectCancel(e,t,n){e.server_.onDisconnectCancel(t.toString(),((r,i)=>{"ok"===r&&sparseSnapshotTreeForget(e.onDisconnect_,t),repoCallOnCompleteCallback(e,n,r,i)}))}function repoOnDisconnectSet(e,t,n,r){const i=nodeFromJSON(n);e.server_.onDisconnectPut(t.toString(),i.val(!0),((n,o)=>{"ok"===n&&sparseSnapshotTreeRemember(e.onDisconnect_,t,i),repoCallOnCompleteCallback(e,r,n,o)}))}function repoRemoveEventCallbackForQuery(e,t,n){let r;r=".info"===pathGetFront(t._path)?syncTreeRemoveEventRegistration(e.infoSyncTree_,t,n):syncTreeRemoveEventRegistration(e.serverSyncTree_,t,n),eventQueueRaiseEventsAtPath(e.eventQueue_,t._path,r)}function repoInterrupt(e){e.persistentConnection_&&e.persistentConnection_.interrupt(ne)}function repoLog(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),log(n,...t)}function repoCallOnCompleteCallback(e,t,n,r){t&&exceptionGuard((()=>{if("ok"===n)t(null);else{const e=(n||"error").toUpperCase();let i=e;r&&(i+=": "+r);const o=new Error(i);o.code=e,t(o)}}))}function repoGetLatestState(e,t,n){return syncTreeCalcCompleteEventCache(e.serverSyncTree_,t,n)||ChildrenNode.EMPTY_NODE}function repoSendReadyTransactions(e,t=e.transactionQueueTree_){if(t||repoPruneCompletedTransactionsBelowNode(e,t),treeGetValue(t)){const n=repoBuildTransactionQueue(e,t);assert(n.length>0,"Sending zero length transaction queue");n.every((e=>0===e.status))&&function repoSendTransactionQueue(e,t,n){const r=n.map((e=>e.currentWriteId)),i=repoGetLatestState(e,t,r);let o=i;const s=i.hash();for(let e=0;e<n.length;e++){const r=n[e];assert(0===r.status,"tryToSendTransactionQueue_: items in queue should all be run."),r.status=1,r.retryCount++;const i=newRelativePath(t,r.path);o=o.updateChild(i,r.currentOutputSnapshotRaw)}const a=o.val(!0),l=t;e.server_.put(l.toString(),a,(r=>{repoLog(e,"transaction put response",{path:l.toString(),status:r});let i=[];if("ok"===r){const r=[];for(let t=0;t<n.length;t++)n[t].status=2,i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,n[t].currentWriteId)),n[t].onComplete&&r.push((()=>n[t].onComplete(null,!0,n[t].currentOutputSnapshotResolved))),n[t].unwatcher();repoPruneCompletedTransactionsBelowNode(e,treeSubTree(e.transactionQueueTree_,t)),repoSendReadyTransactions(e,e.transactionQueueTree_),eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,i);for(let e=0;e<r.length;e++)exceptionGuard(r[e])}else{if("datastale"===r)for(let e=0;e<n.length;e++)3===n[e].status?n[e].status=4:n[e].status=0;else{warn("transaction at "+l.toString()+" failed: "+r);for(let e=0;e<n.length;e++)n[e].status=4,n[e].abortReason=r}repoRerunTransactions(e,t)}}),s)}(e,treeGetPath(t),n)}else treeHasChildren(t)&&treeForEachChild(t,(t=>{repoSendReadyTransactions(e,t)}))}function repoRerunTransactions(e,t){const n=repoGetAncestorTransactionNode(e,t),r=treeGetPath(n);return function repoRerunTransactionQueue(e,t,n){if(0===t.length)return;const r=[];let i=[];const o=t.filter((e=>0===e.status)),s=o.map((e=>e.currentWriteId));for(let o=0;o<t.length;o++){const l=t[o],h=newRelativePath(n,l.path);let c,d=!1;if(assert(null!==h,"rerunTransactionsUnderNode_: relativePath should not be null."),4===l.status)d=!0,c=l.abortReason,i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,l.currentWriteId,!0));else if(0===l.status)if(l.retryCount>=25)d=!0,c="maxretry",i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,l.currentWriteId,!0));else{const n=repoGetLatestState(e,l.path,s);l.currentInputSnapshot=n;const r=t[o].update(n.val());if(void 0!==r){validateFirebaseData("transaction failed: Data returned ",r,l.path);let t=nodeFromJSON(r);"object"==typeof r&&null!=r&&contains(r,".priority")||(t=t.updatePriority(n.getPriority()));const o=l.currentWriteId,a=repoGenerateServerValues(e),h=resolveDeferredValueSnapshot(t,n,a);l.currentOutputSnapshotRaw=t,l.currentOutputSnapshotResolved=h,l.currentWriteId=repoGetNextWriteId(e),s.splice(s.indexOf(o),1),i=i.concat(syncTreeApplyUserOverwrite(e.serverSyncTree_,l.path,h,l.currentWriteId,l.applyLocally)),i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,o,!0))}else d=!0,c="nodata",i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,l.currentWriteId,!0))}eventQueueRaiseEventsForChangedPath(e.eventQueue_,n,i),i=[],d&&(t[o].status=2,a=t[o].unwatcher,setTimeout(a,Math.floor(0)),t[o].onComplete&&("nodata"===c?r.push((()=>t[o].onComplete(null,!1,t[o].currentInputSnapshot))):r.push((()=>t[o].onComplete(new Error(c),!1,null)))))}var a;repoPruneCompletedTransactionsBelowNode(e,e.transactionQueueTree_);for(let e=0;e<r.length;e++)exceptionGuard(r[e]);repoSendReadyTransactions(e,e.transactionQueueTree_)}(e,repoBuildTransactionQueue(e,n),r),r}function repoGetAncestorTransactionNode(e,t){let n,r=e.transactionQueueTree_;for(n=pathGetFront(t);null!==n&&void 0===treeGetValue(r);)r=treeSubTree(r,n),n=pathGetFront(t=pathPopFront(t));return r}function repoBuildTransactionQueue(e,t){const n=[];return repoAggregateTransactionQueuesForNode(e,t,n),n.sort(((e,t)=>e.order-t.order)),n}function repoAggregateTransactionQueuesForNode(e,t,n){const r=treeGetValue(t);if(r)for(let e=0;e<r.length;e++)n.push(r[e]);treeForEachChild(t,(t=>{repoAggregateTransactionQueuesForNode(e,t,n)}))}function repoPruneCompletedTransactionsBelowNode(e,t){const n=treeGetValue(t);if(n){let e=0;for(let t=0;t<n.length;t++)2!==n[t].status&&(n[e]=n[t],e++);n.length=e,treeSetValue(t,n.length>0?n:void 0)}treeForEachChild(t,(t=>{repoPruneCompletedTransactionsBelowNode(e,t)}))}function repoAbortTransactions(e,t){const n=treeGetPath(repoGetAncestorTransactionNode(e,t)),r=treeSubTree(e.transactionQueueTree_,t);return function treeForEachAncestor(e,t,n){let r=n?e:e.parent;for(;null!==r;){if(t(r))return!0;r=r.parent}return!1}(r,(t=>{repoAbortTransactionsOnNode(e,t)})),repoAbortTransactionsOnNode(e,r),treeForEachDescendant(r,(t=>{repoAbortTransactionsOnNode(e,t)})),n}function repoAbortTransactionsOnNode(e,t){const n=treeGetValue(t);if(n){const r=[];let i=[],o=-1;for(let t=0;t<n.length;t++)3===n[t].status||(1===n[t].status?(assert(o===t-1,"All SENT items should be at beginning of queue."),o=t,n[t].status=3,n[t].abortReason="set"):(assert(0===n[t].status,"Unexpected transaction status in abort"),n[t].unwatcher(),i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&r.push(n[t].onComplete.bind(null,new Error("set"),!1,null))));-1===o?treeSetValue(t,void 0):n.length=o+1,eventQueueRaiseEventsForChangedPath(e.eventQueue_,treeGetPath(t),i);for(let e=0;e<r.length;e++)exceptionGuard(r[e])}}const parseRepoInfo=function(e,t){const n=parseDatabaseURL(e),r=n.namespace;"firebase.com"===n.domain&&fatal(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||fatal("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&warn("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new RepoInfo(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new Path(n.pathString)}},parseDatabaseURL=function(e){let t="",n="",r="",i="",o="",s=!0,a="https",l=443;if("string"==typeof e){let h=e.indexOf("//");h>=0&&(a=e.substring(0,h-1),e=e.substring(h+2));let c=e.indexOf("/");-1===c&&(c=e.length);let d=e.indexOf("?");-1===d&&(d=e.length),t=e.substring(0,Math.min(c,d)),c<d&&(i=function decodePath(e){let t="";const n=e.split("/");for(let e=0;e<n.length;e++)if(n[e].length>0){let r=n[e];try{r=decodeURIComponent(r.replace(/\+/g," "))}catch(e){}t+="/"+r}return t}(e.substring(c,d)));const u=function decodeQuery(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const r=n.split("=");2===r.length?t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):warn(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,d)));h=t.indexOf(":"),h>=0?(s="https"===a||"wss"===a,l=parseInt(t.substring(h+1),10)):h=t.length;const p=t.slice(0,h);if("localhost"===p.toLowerCase())n="localhost";else if(p.split(".").length<=2)n=p;else{const e=t.indexOf(".");r=t.substring(0,e).toLowerCase(),n=t.substring(e+1),o=r}"ns"in u&&(o=u.ns)}return{host:t,port:l,domain:n,subdomain:r,secure:s,scheme:a,pathString:i,namespace:o}},re="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ie=function(){let e=0;const t=[];return function(n){const r=n===e;let i;e=n;const o=new Array(8);for(i=7;i>=0;i--)o[i]=re.charAt(n%64),n=Math.floor(n/64);assert(0===n,"Cannot push at time == 0");let s=o.join("");if(r){for(i=11;i>=0&&63===t[i];i--)t[i]=0;t[i]++}else for(i=0;i<12;i++)t[i]=Math.floor(64*Math.random());for(i=0;i<12;i++)s+=re.charAt(t[i]);return assert(20===s.length,"nextPushId: Length should be 20."),s}}();class DataEvent{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){const e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+stringify(this.snapshot.exportVal())}}class CancelEvent{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class CallbackContext{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return assert(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class OnDisconnect{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new Deferred;return repoOnDisconnectCancel(this._repo,this._path,e.wrapCallback((()=>{}))),e.promise}remove(){validateWritablePath("OnDisconnect.remove",this._path);const e=new Deferred;return repoOnDisconnectSet(this._repo,this._path,null,e.wrapCallback((()=>{}))),e.promise}set(e){validateWritablePath("OnDisconnect.set",this._path),validateFirebaseDataArg("OnDisconnect.set",e,this._path,!1);const t=new Deferred;return repoOnDisconnectSet(this._repo,this._path,e,t.wrapCallback((()=>{}))),t.promise}setWithPriority(e,t){validateWritablePath("OnDisconnect.setWithPriority",this._path),validateFirebaseDataArg("OnDisconnect.setWithPriority",e,this._path,!1),validatePriority("OnDisconnect.setWithPriority",t,!1);const n=new Deferred;return function repoOnDisconnectSetWithPriority(e,t,n,r,i){const o=nodeFromJSON(n,r);e.server_.onDisconnectPut(t.toString(),o.val(!0),((n,r)=>{"ok"===n&&sparseSnapshotTreeRemember(e.onDisconnect_,t,o),repoCallOnCompleteCallback(0,i,n,r)}))}(this._repo,this._path,e,t,n.wrapCallback((()=>{}))),n.promise}update(e){validateWritablePath("OnDisconnect.update",this._path),validateFirebaseMergeDataArg("OnDisconnect.update",e,this._path,!1);const t=new Deferred;return function repoOnDisconnectUpdate(e,t,n,r){if(isEmpty(n))return log("onDisconnect().update() called with empty data. Don't do anything."),void repoCallOnCompleteCallback(0,r,"ok",void 0);e.server_.onDisconnectMerge(t.toString(),n,((i,o)=>{"ok"===i&&each(n,((n,r)=>{const i=nodeFromJSON(r);sparseSnapshotTreeRemember(e.onDisconnect_,pathChild(t,n),i)})),repoCallOnCompleteCallback(0,r,i,o)}))}(this._repo,this._path,e,t.wrapCallback((()=>{}))),t.promise}}class QueryImpl{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return pathIsEmpty(this._path)?null:pathGetBack(this._path)}get ref(){return new ReferenceImpl(this._repo,this._path)}get _queryIdentifier(){const e=queryParamsGetQueryObject(this._queryParams),t=ObjectToUniqueKey(e);return"{}"===t?"default":t}get _queryObject(){return queryParamsGetQueryObject(this._queryParams)}isEqual(e){if(!((e=getModularInstance(e))instanceof QueryImpl))return!1;const t=this._repo===e._repo,n=pathEquals(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+function pathToUrlEncodedString(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}function validateNoPreviousOrderByCall(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function validateQueryEndpoints(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===D){const r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==T)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==E)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===G){if(null!=t&&!isValidPriority(t)||null!=n&&!isValidPriority(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(assert(e.getIndex()instanceof PathIndex||e.getIndex()===j,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function validateLimit(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class ReferenceImpl extends QueryImpl{constructor(e,t){super(e,t,new QueryParams,!1)}get parent(){const e=pathParent(this._path);return null===e?null:new ReferenceImpl(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class DataSnapshot{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const t=new Path(e),n=child(this.ref,e);return new DataSnapshot(this._node.getChild(t),n,G)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){if(this._node.isLeafNode())return!1;return!!this._node.forEachChild(this._index,((t,n)=>e(new DataSnapshot(n,child(this.ref,t),G))))}hasChild(e){const t=new Path(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function ref(e,t){return(e=getModularInstance(e))._checkNotDeleted("ref"),void 0!==t?child(e._root,t):e._root}function refFromURL(e,t){(e=getModularInstance(e))._checkNotDeleted("refFromURL");const n=parseRepoInfo(t,e._repo.repoInfo_.nodeAdmin);validateUrl("refFromURL",n);const r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||fatal("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),ref(e,n.path.toString())}function child(e,t){var n,r,i,o;return null===pathGetFront((e=getModularInstance(e))._path)?(n="child",r="path",o=!1,(i=t)&&(i=i.replace(/^\/*\.info(\/|$)/,"/")),validatePathString(n,r,i,o)):validatePathString("child","path",t,!1),new ReferenceImpl(e._repo,pathChild(e._path,t))}function onDisconnect(e){return e=getModularInstance(e),new OnDisconnect(e._repo,e._path)}function push(e,t){e=getModularInstance(e),validateWritablePath("push",e._path),validateFirebaseDataArg("push",t,e._path,!0);const n=repoServerTime(e._repo),r=ie(n),i=child(e,r),o=child(e,r);let s;return s=null!=t?set(o,t).then((()=>o)):Promise.resolve(o),i.then=s.then.bind(s),i.catch=s.then.bind(s,void 0),i}function remove(e){return validateWritablePath("remove",e._path),set(e,null)}function set(e,t){e=getModularInstance(e),validateWritablePath("set",e._path),validateFirebaseDataArg("set",t,e._path,!1);const n=new Deferred;return repoSetWithPriority(e._repo,e._path,t,null,n.wrapCallback((()=>{}))),n.promise}function setPriority(e,t){e=getModularInstance(e),validateWritablePath("setPriority",e._path),validatePriority("setPriority",t,!1);const n=new Deferred;return repoSetWithPriority(e._repo,pathChild(e._path,".priority"),t,null,n.wrapCallback((()=>{}))),n.promise}function setWithPriority(e,t,n){if(validateWritablePath("setWithPriority",e._path),validateFirebaseDataArg("setWithPriority",t,e._path,!1),validatePriority("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new Deferred;return repoSetWithPriority(e._repo,e._path,t,n,r.wrapCallback((()=>{}))),r.promise}function update(e,t){validateFirebaseMergeDataArg("update",t,e._path,!1);const n=new Deferred;return function repoUpdate(e,t,n,r){repoLog(e,"update",{path:t.toString(),value:n});let i=!0;const o=repoGenerateServerValues(e),s={};if(each(n,((n,r)=>{i=!1,s[n]=resolveDeferredValueTree(pathChild(t,n),nodeFromJSON(r),e.serverSyncTree_,o)})),i)log("update() called with empty data. Don't do anything."),repoCallOnCompleteCallback(0,r,"ok",void 0);else{const i=repoGetNextWriteId(e),o=syncTreeApplyUserMerge(e.serverSyncTree_,t,s,i);eventQueueQueueEvents(e.eventQueue_,o),e.server_.merge(t.toString(),n,((n,o)=>{const s="ok"===n;s||warn("update at "+t+" failed: "+n);const a=syncTreeAckUserWrite(e.serverSyncTree_,i,!s),l=a.length>0?repoRerunTransactions(e,t):t;eventQueueRaiseEventsForChangedPath(e.eventQueue_,l,a),repoCallOnCompleteCallback(0,r,n,o)})),each(n,(n=>{const r=repoAbortTransactions(e,pathChild(t,n));repoRerunTransactions(e,r)})),eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,[])}}(e._repo,e._path,t,n.wrapCallback((()=>{}))),n.promise}function get(e){e=getModularInstance(e);const t=new CallbackContext((()=>{})),n=new ValueEventRegistration(t);return function repoGetValue(e,t,n){const r=syncTreeGetServerValue(e.serverSyncTree_,t);return null!=r?Promise.resolve(r):e.server_.get(t).then((r=>{const i=nodeFromJSON(r).withIndex(t._queryParams.getIndex());let o;if(syncTreeAddEventRegistration(e.serverSyncTree_,t,n,!0),t._queryParams.loadsAllData())o=syncTreeApplyServerOverwrite(e.serverSyncTree_,t._path,i);else{const n=syncTreeTagForQuery(e.serverSyncTree_,t);o=syncTreeApplyTaggedQueryOverwrite(e.serverSyncTree_,t._path,i,n)}return eventQueueRaiseEventsForChangedPath(e.eventQueue_,t._path,o),syncTreeRemoveEventRegistration(e.serverSyncTree_,t,n,null,!0),i}),(n=>(repoLog(e,"get for query "+stringify(t)+" failed: "+n),Promise.reject(new Error(n)))))}(e._repo,e,n).then((t=>new DataSnapshot(t,new ReferenceImpl(e._repo,e._path),e._queryParams.getIndex())))}class ValueEventRegistration{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){const n=t._queryParams.getIndex();return new DataEvent("value",this,new DataSnapshot(e.snapshotNode,new ReferenceImpl(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new CancelEvent(this,e,t):null}matches(e){return e instanceof ValueEventRegistration&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class ChildEventRegistration{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new CancelEvent(this,e,t):null}createEvent(e,t){assert(null!=e.childName,"Child events should have a childName.");const n=child(new ReferenceImpl(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new DataEvent(e.type,this,new DataSnapshot(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof ChildEventRegistration&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function addEventListener(e,t,n,r,i){let o;if("object"==typeof r&&(o=void 0,i=r),"function"==typeof r&&(o=r),i&&i.onlyOnce){const t=n,onceCallback=(n,r)=>{repoRemoveEventCallbackForQuery(e._repo,e,a),t(n,r)};onceCallback.userCallback=n.userCallback,onceCallback.context=n.context,n=onceCallback}const s=new CallbackContext(n,o||void 0),a="value"===t?new ValueEventRegistration(s):new ChildEventRegistration(t,s);return function repoAddEventCallbackForQuery(e,t,n){let r;r=".info"===pathGetFront(t._path)?syncTreeAddEventRegistration(e.infoSyncTree_,t,n):syncTreeAddEventRegistration(e.serverSyncTree_,t,n),eventQueueRaiseEventsAtPath(e.eventQueue_,t._path,r)}(e._repo,e,a),()=>repoRemoveEventCallbackForQuery(e._repo,e,a)}function onValue(e,t,n,r){return addEventListener(e,"value",t,n,r)}function onChildAdded(e,t,n,r){return addEventListener(e,"child_added",t,n,r)}function onChildChanged(e,t,n,r){return addEventListener(e,"child_changed",t,n,r)}function onChildMoved(e,t,n,r){return addEventListener(e,"child_moved",t,n,r)}function onChildRemoved(e,t,n,r){return addEventListener(e,"child_removed",t,n,r)}function off(e,t,n){let r=null;const i=n?new CallbackContext(n):null;"value"===t?r=new ValueEventRegistration(i):t&&(r=new ChildEventRegistration(t,i)),repoRemoveEventCallbackForQuery(e._repo,e,r)}class QueryConstraint{}class QueryEndAtConstraint extends QueryConstraint{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){validateFirebaseDataArg("endAt",this._value,e._path,!0);const t=queryParamsEndAt(e._queryParams,this._value,this._key);if(validateLimit(t),validateQueryEndpoints(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function endAt(e,t){return validateKey("endAt","key",t,!0),new QueryEndAtConstraint(e,t)}class QueryEndBeforeConstraint extends QueryConstraint{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){validateFirebaseDataArg("endBefore",this._value,e._path,!1);const t=function queryParamsEndBefore(e,t,n){let r;return r=e.index_===D||n?queryParamsEndAt(e,t,n):queryParamsEndAt(e,t,T),r.endBeforeSet_=!0,r}(e._queryParams,this._value,this._key);if(validateLimit(t),validateQueryEndpoints(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function endBefore(e,t){return validateKey("endBefore","key",t,!0),new QueryEndBeforeConstraint(e,t)}class QueryStartAtConstraint extends QueryConstraint{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){validateFirebaseDataArg("startAt",this._value,e._path,!0);const t=queryParamsStartAt(e._queryParams,this._value,this._key);if(validateLimit(t),validateQueryEndpoints(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function startAt(e=null,t){return validateKey("startAt","key",t,!0),new QueryStartAtConstraint(e,t)}class QueryStartAfterConstraint extends QueryConstraint{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){validateFirebaseDataArg("startAfter",this._value,e._path,!1);const t=function queryParamsStartAfter(e,t,n){let r;return r=e.index_===D||n?queryParamsStartAt(e,t,n):queryParamsStartAt(e,t,E),r.startAfterSet_=!0,r}(e._queryParams,this._value,this._key);if(validateLimit(t),validateQueryEndpoints(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function startAfter(e,t){return validateKey("startAfter","key",t,!0),new QueryStartAfterConstraint(e,t)}class QueryLimitToFirstConstraint extends QueryConstraint{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new QueryImpl(e._repo,e._path,function queryParamsLimitToFirst(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}function limitToFirst(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new QueryLimitToFirstConstraint(e)}class QueryLimitToLastConstraint extends QueryConstraint{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new QueryImpl(e._repo,e._path,function queryParamsLimitToLast(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}function limitToLast(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new QueryLimitToLastConstraint(e)}class QueryOrderByChildConstraint extends QueryConstraint{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){validateNoPreviousOrderByCall(e,"orderByChild");const t=new Path(this._path);if(pathIsEmpty(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");const n=new PathIndex(t),r=queryParamsOrderBy(e._queryParams,n);return validateQueryEndpoints(r),new QueryImpl(e._repo,e._path,r,!0)}}function orderByChild(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return validatePathString("orderByChild","path",e,!1),new QueryOrderByChildConstraint(e)}class QueryOrderByKeyConstraint extends QueryConstraint{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){validateNoPreviousOrderByCall(e,"orderByKey");const t=queryParamsOrderBy(e._queryParams,D);return validateQueryEndpoints(t),new QueryImpl(e._repo,e._path,t,!0)}}function orderByKey(){return new QueryOrderByKeyConstraint}class QueryOrderByPriorityConstraint extends QueryConstraint{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){validateNoPreviousOrderByCall(e,"orderByPriority");const t=queryParamsOrderBy(e._queryParams,G);return validateQueryEndpoints(t),new QueryImpl(e._repo,e._path,t,!0)}}function orderByPriority(){return new QueryOrderByPriorityConstraint}class QueryOrderByValueConstraint extends QueryConstraint{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){validateNoPreviousOrderByCall(e,"orderByValue");const t=queryParamsOrderBy(e._queryParams,j);return validateQueryEndpoints(t),new QueryImpl(e._repo,e._path,t,!0)}}function orderByValue(){return new QueryOrderByValueConstraint}class QueryEqualToValueConstraint extends QueryConstraint{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(validateFirebaseDataArg("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new QueryEndAtConstraint(this._value,this._key)._apply(new QueryStartAtConstraint(this._value,this._key)._apply(e))}}function equalTo(e,t){return validateKey("equalTo","key",t,!0),new QueryEqualToValueConstraint(e,t)}function query(e,...t){let n=getModularInstance(e);for(const e of t)n=e._apply(n);return n}!function syncPointSetReferenceConstructor(e){assert(!$,"__referenceConstructor has already been defined"),$=e}(ReferenceImpl),function syncTreeSetReferenceConstructor(e){assert(!J,"__referenceConstructor has already been defined"),J=e}(ReferenceImpl);const oe={};let se=!1;function repoManagerDatabaseFromApp(e,t,n,r,i){let o=r||e.options.databaseURL;void 0===o&&(e.options.projectId||fatal("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),log("Using default host for project ",e.options.projectId),o=`${e.options.projectId}-default-rtdb.firebaseio.com`);let s,a,l=parseRepoInfo(o,i),h=l.repoInfo;"undefined"!=typeof process&&process.env&&(a=process.env.FIREBASE_DATABASE_EMULATOR_HOST),a?(s=!0,o=`http://${a}?ns=${h.namespace}`,l=parseRepoInfo(o,i),h=l.repoInfo):s=!l.repoInfo.secure;const c=i&&s?new EmulatorTokenProvider(EmulatorTokenProvider.OWNER):new FirebaseAuthTokenProvider(e.name,e.options,t);validateUrl("Invalid Firebase Database URL",l),pathIsEmpty(l.path)||fatal("Database URL must point to the root of a Firebase Database (not including a child path).");const d=function repoManagerCreateRepo(e,t,n,r){let i=oe[t.name];i||(i={},oe[t.name]=i);let o=i[e.toURLString()];o&&fatal("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return o=new Repo(e,se,n,r),i[e.toURLString()]=o,o}(h,e,c,new AppCheckTokenProvider(e,n));return new Database(d,e)}class Database{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(repoStart(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new ReferenceImpl(this._repo,newEmptyPath())),this._rootInternal}_delete(){return null!==this._rootInternal&&(!function repoManagerDeleteRepo(e,t){const n=oe[t];n&&n[e.key]===e||fatal(`Database ${t}(${e.repoInfo_}) has already been deleted.`),repoInterrupt(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&fatal("Cannot call "+e+" on a deleted database.")}}function checkTransportInit(){TransportManager.IS_TRANSPORT_INITIALIZED&&warn("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function forceWebSockets(){checkTransportInit(),BrowserPollConnection.forceDisallow()}function forceLongPolling(){checkTransportInit(),WebSocketConnection.forceDisallow(),BrowserPollConnection.forceAllow()}function getDatabase(t=e(),n){const r=_getProvider(t,"database").getImmediate({identifier:n});if(!r._instanceStarted){const e=getDefaultEmulatorHostnameAndPort("database");e&&connectDatabaseEmulator(r,...e)}return r}function connectDatabaseEmulator(e,t,n,r={}){(e=getModularInstance(e))._checkNotDeleted("useEmulator");const i=`${t}:${n}`,o=e._repoInternal;if(e._instanceStarted){if(i===e._repoInternal.repoInfo_.host&&deepEqual(r,o.repoInfo_.emulatorOptions))return;fatal("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let s;if(o.repoInfo_.nodeAdmin)r.mockUserToken&&fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),s=new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);else if(r.mockUserToken){const t="string"==typeof r.mockUserToken?r.mockUserToken:function createMockUserToken(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const o={iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}},...e};return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(o)),""].join(".")}(r.mockUserToken,e.app.options.projectId);s=new EmulatorTokenProvider(t)}isCloudWorkstation(t)&&async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(t),function repoManagerApplyEmulatorSettings(e,t,n,r){const i=t.lastIndexOf(":"),o=isCloudWorkstation(t.substring(0,i));e.repoInfo_=new RepoInfo(t,o,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0,n),r&&(e.authTokenProvider_=r)}(o,i,r,s)}function goOffline(e){(e=getModularInstance(e))._checkNotDeleted("goOffline"),repoInterrupt(e._repo)}function goOnline(e){(e=getModularInstance(e))._checkNotDeleted("goOnline"),function repoResume(e){e.persistentConnection_&&e.persistentConnection_.resume(ne)}(e._repo)}function enableLogging(e,t){enableLogging$1(e,t)}const ae={".sv":"timestamp"};function serverTimestamp(){return ae}function increment(e){return{".sv":{increment:e}}}class TransactionResult{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function runTransaction(e,t,n){if(e=getModularInstance(e),validateWritablePath("Reference.transaction",e._path),".length"===e.key||".keys"===e.key)throw"Reference.transaction failed: "+e.key+" is a read-only object.";const r=n?.applyLocally??!0,i=new Deferred,o=onValue(e,(()=>{}));return function repoStartTransaction(e,t,n,r,i,o){repoLog(e,"transaction on "+t);const s={path:t,update:n,onComplete:r,status:null,order:v(),applyLocally:o,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=repoGetLatestState(e,t,void 0);s.currentInputSnapshot=a;const l=s.update(a.val());if(void 0===l)s.unwatcher(),s.currentOutputSnapshotRaw=null,s.currentOutputSnapshotResolved=null,s.onComplete&&s.onComplete(null,!1,s.currentInputSnapshot);else{validateFirebaseData("transaction failed: Data returned ",l,s.path),s.status=0;const n=treeSubTree(e.transactionQueueTree_,t),r=treeGetValue(n)||[];let i;r.push(s),treeSetValue(n,r),"object"==typeof l&&null!==l&&contains(l,".priority")?(i=safeGet(l,".priority"),assert(isValidPriority(i),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):i=(syncTreeCalcCompleteEventCache(e.serverSyncTree_,t)||ChildrenNode.EMPTY_NODE).getPriority().val();const o=repoGenerateServerValues(e),h=nodeFromJSON(l,i),c=resolveDeferredValueSnapshot(h,a,o);s.currentOutputSnapshotRaw=h,s.currentOutputSnapshotResolved=c,s.currentWriteId=repoGetNextWriteId(e);const d=syncTreeApplyUserOverwrite(e.serverSyncTree_,t,c,s.currentWriteId,s.applyLocally);eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,d),repoSendReadyTransactions(e,e.transactionQueueTree_)}}(e._repo,e._path,t,((t,n,r)=>{let o=null;t?i.reject(t):(o=new DataSnapshot(r,new ReferenceImpl(e._repo,e._path),G),i.resolve(new TransactionResult(n,o)))}),o,r),i.promise}PersistentConnection.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},PersistentConnection.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)};const hijackHash=function(e){const t=PersistentConnection.prototype.put;return PersistentConnection.prototype.put=function(n,r,i,o){void 0!==o&&(o=e()),t.call(this,n,r,i,o)},function(){PersistentConnection.prototype.put=t}},forceRestClient=function(e){!function repoManagerForceRestClient(e){se=e}(e)};function _initStandalone({app:e,url:t,version:n,customAuthImpl:r,customAppCheckImpl:i,nodeAdmin:o=!1}){setSDKVersion(n);const s=new ComponentContainer("database-standalone"),a=new Provider("auth-internal",s);let l;return i&&(l=new Provider("app-check-internal",s),l.setComponent(new Component("app-check-internal",(()=>i),"PRIVATE"))),a.setComponent(new Component("auth-internal",(()=>r),"PRIVATE")),repoManagerDatabaseFromApp(e,a,l,t,o)}!function registerDatabase(e){setSDKVersion(i),t(new Component("database",((e,{instanceIdentifier:t})=>repoManagerDatabaseFromApp(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)),"PUBLIC").setMultipleInstances(!0)),n(p,_,e),n(p,_,"esm2020")}();export{DataSnapshot,Database,OnDisconnect,QueryConstraint,TransactionResult,QueryImpl as _QueryImpl,QueryParams as _QueryParams,ReferenceImpl as _ReferenceImpl,forceRestClient as _TEST_ACCESS_forceRestClient,hijackHash as _TEST_ACCESS_hijackHash,_initStandalone,repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp,setSDKVersion as _setSDKVersion,validatePathString as _validatePathString,validateWritablePath as _validateWritablePath,child,connectDatabaseEmulator,enableLogging,endAt,endBefore,equalTo,forceLongPolling,forceWebSockets,get,getDatabase,goOffline,goOnline,increment,limitToFirst,limitToLast,off,onChildAdded,onChildChanged,onChildMoved,onChildRemoved,onDisconnect,onValue,orderByChild,orderByKey,orderByPriority,orderByValue,push,query,ref,refFromURL,remove,runTransaction,serverTimestamp,set,setPriority,setWithPriority,startAfter,startAt,update};
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as n,_isFirebaseServerApp as r,SDK_VERSION as i}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";const o=!1,s="${JSCORE_VERSION}",assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+s+") INTERNAL ASSERT FAILED: "+e)},stringToByteArray$1=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++r)),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t},a={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const i=e[t],o=t+1<e.length,s=o?e[t+1]:0,a=t+2<e.length,l=a?e[t+2]:0,h=i>>2,c=(3&i)<<4|s>>4;let d=(15&s)<<2|l>>6,u=63&l;a||(u=64,o||(d=64)),r.push(n[h],n[c],n[d],n[u])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(stringToByteArray$1(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const i=e[n++];if(i<128)t[r++]=String.fromCharCode(i);else if(i>191&&i<224){const o=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&o)}else if(i>239&&i<365){const o=((7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(o>>10)),t[r++]=String.fromCharCode(56320+(1023&o))}else{const o=e[n++],s=e[n++];t[r++]=String.fromCharCode((15&i)<<12|(63&o)<<6|63&s)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const i=n[e.charAt(t++)],o=t<e.length?n[e.charAt(t)]:0;++t;const s=t<e.length?n[e.charAt(t)]:64;++t;const a=t<e.length?n[e.charAt(t)]:64;if(++t,null==i||null==o||null==s||null==a)throw new DecodeBase64StringError;const l=i<<2|o>>4;if(r.push(l),64!==s){const e=o<<4&240|s>>2;if(r.push(e),64!==a){const e=s<<6&192|a;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64Encode=function(e){const t=stringToByteArray$1(e);return a.encodeByteArray(t,!0)},base64urlEncodeWithoutPadding=function(e){return base64Encode(e).replace(/\./g,"")},base64Decode=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function deepCopy(e){return deepExtend(void 0,e)}function deepExtend(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=deepExtend(e[n],t[n]));return e}const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&base64Decode(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>getDefaults()?.emulatorHosts?.[e])(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]};class Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}function isMobileCordova(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(function getUA(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}())}function isNodeSdk(){return!0===o}function jsonEval(e){return JSON.parse(e)}function stringify(e){return JSON.stringify(e)}const decode=function(e){let t={},n={},r={},i="";try{const o=e.split(".");t=jsonEval(base64Decode(o[0])||""),n=jsonEval(base64Decode(o[1])||""),i=o[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}};function contains(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function safeGet(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function isEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function map(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const i of n){if(!r.includes(i))return!1;const n=e[i],o=t[i];if(isObject(n)&&isObject(o)){if(!deepEqual(n,o))return!1}else if(n!==o)return!1}for(const e of r)if(!n.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}class Sha1{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(e,t){t||(t=0);const n=this.W_;if("string"==typeof e)for(let r=0;r<16;r++)n[r]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let r=0;r<16;r++)n[r]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let e=16;e<80;e++){const t=n[e-3]^n[e-8]^n[e-14]^n[e-16];n[e]=4294967295&(t<<1|t>>>31)}let r,i,o=this.chain_[0],s=this.chain_[1],a=this.chain_[2],l=this.chain_[3],h=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(r=l^s&(a^l),i=1518500249):(r=s^a^l,i=1859775393):e<60?(r=s&a|l&(s|a),i=2400959708):(r=s^a^l,i=3395469782);const t=(o<<5|o>>>27)+r+h+i+n[e]&4294967295;h=l,l=a,a=4294967295&(s<<30|s>>>2),s=o,o=t}this.chain_[0]=this.chain_[0]+o&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+l&4294967295,this.chain_[4]=this.chain_[4]+h&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let r=0;const i=this.buf_;let o=this.inbuf_;for(;r<t;){if(0===o)for(;r<=n;)this.compress_(e,r),r+=this.blockSize;if("string"==typeof e){for(;r<t;)if(i[o]=e.charCodeAt(r),++o,++r,o===this.blockSize){this.compress_(i),o=0;break}}else for(;r<t;)if(i[o]=e[r],++o,++r,o===this.blockSize){this.compress_(i),o=0;break}}this.inbuf_=o,this.total_+=t}digest(){const e=[];let t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let e=this.blockSize-1;e>=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let r=24;r>=0;r-=8)e[n]=this.chain_[t]>>r&255,++n;return e}}function errorPrefix(e,t){return`${e} failed: ${t} argument `}const stringLength=function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);r<128?t++:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t};function getModularInstance(e){return e&&e._delegate?e._delegate:e}function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const l="[DEFAULT]";class Provider{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new Deferred;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){const t=this.normalizeInstanceIdentifier(e?.identifier),n=e?.optional??!1;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function isComponentEager(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:l})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=l){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return null!=this.component}isInitialized(e=l){return this.instances.has(e)}getOptions(e=l){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries()){n===this.normalizeInstanceIdentifier(e)&&t.resolve(r)}return r}onInit(e,t){const n=this.normalizeInstanceIdentifier(t),r=this.onInitCallbacks.get(n)??new Set;r.add(e),this.onInitCallbacks.set(n,r);const i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e,r===l?void 0:r),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch{}var r;return n||null}normalizeInstanceIdentifier(e=l){return this.component?this.component.multipleInstances?e:l:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class ComponentContainer{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new Provider(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}var h;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(h||(h={}));const c={debug:h.DEBUG,verbose:h.VERBOSE,info:h.INFO,warn:h.WARN,error:h.ERROR,silent:h.SILENT},d=h.INFO,u={[h.DEBUG]:"log",[h.VERBOSE]:"log",[h.INFO]:"info",[h.WARN]:"warn",[h.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),i=u[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)};const p="@firebase/database",_="1.1.3";let m="";function setSDKVersion(e){m=e}class DOMStorageWrapper{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),stringify(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:jsonEval(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class MemoryStorage{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return contains(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const createStoragefor=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new DOMStorageWrapper(t)}}catch(e){}return new MemoryStorage},f=createStoragefor("localStorage"),y=createStoragefor("sessionStorage"),g=new class Logger{constructor(e){this.name=e,this._logLevel=d,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in h))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?c[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,h.DEBUG,...e),this._logHandler(this,h.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,h.VERBOSE,...e),this._logHandler(this,h.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,h.INFO,...e),this._logHandler(this,h.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,h.WARN,...e),this._logHandler(this,h.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,h.ERROR,...e),this._logHandler(this,h.ERROR,...e)}}("@firebase/database"),v=function(){let e=1;return function(){return e++}}(),sha1=function(e){const t=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){const t=i-55296;r++,assert(r<e.length,"Surrogate pair missing trail surrogate."),i=65536+(t<<10)+(e.charCodeAt(r)-56320)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):i<65536?(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t}(e),n=new Sha1;n.update(t);const r=n.digest();return a.encodeByteArray(r)},buildLogMessage_=function(...e){let t="";for(let n=0;n<e.length;n++){const r=e[n];Array.isArray(r)||r&&"object"==typeof r&&"number"==typeof r.length?t+=buildLogMessage_.apply(null,r):t+="object"==typeof r?stringify(r):r,t+=" "}return t};let C=null,w=!0;const enableLogging$1=function(e,t){assert(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(g.logLevel=h.VERBOSE,C=g.log.bind(g),t&&y.set("logging_enabled",!0)):"function"==typeof e?C=e:(C=null,y.remove("logging_enabled"))},log=function(...e){if(!0===w&&(w=!1,null===C&&!0===y.get("logging_enabled")&&enableLogging$1(!0)),C){const t=buildLogMessage_.apply(null,e);C(t)}},logWrapper=function(e){return function(...t){log(e,...t)}},error=function(...e){const t="FIREBASE INTERNAL ERROR: "+buildLogMessage_(...e);g.error(t)},fatal=function(...e){const t=`FIREBASE FATAL ERROR: ${buildLogMessage_(...e)}`;throw g.error(t),new Error(t)},warn=function(...e){const t="FIREBASE WARNING: "+buildLogMessage_(...e);g.warn(t)},isInvalidJSONNumber=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},T="[MIN_NAME]",E="[MAX_NAME]",nameCompare=function(e,t){if(e===t)return 0;if(e===T||t===E)return-1;if(t===T||e===E)return 1;{const n=tryParseInt(e),r=tryParseInt(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null!==r?1:e<t?-1:1}},stringCompare=function(e,t){return e===t?0:e<t?-1:1},requireKey=function(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+stringify(t))},ObjectToUniqueKey=function(e){if("object"!=typeof e||null===e)return stringify(e);const t=[];for(const n in e)t.push(n);t.sort();let n="{";for(let r=0;r<t.length;r++)0!==r&&(n+=","),n+=stringify(t[r]),n+=":",n+=ObjectToUniqueKey(e[t[r]]);return n+="}",n},splitStringBySize=function(e,t){const n=e.length;if(n<=t)return[e];const r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r};function each(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const doubleToIEEE754String=function(e){assert(!isInvalidJSONNumber(e),"Invalid JSON number");const t=1023;let n,r,i,o,s;0===e?(r=0,i=0,n=1/e==-1/0?1:0):(n=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(o=Math.min(Math.floor(Math.log(e)/Math.LN2),t),r=o+t,i=Math.round(e*Math.pow(2,52-o)-Math.pow(2,52))):(r=0,i=Math.round(e/Math.pow(2,-1074))));const a=[];for(s=52;s;s-=1)a.push(i%2?1:0),i=Math.floor(i/2);for(s=11;s;s-=1)a.push(r%2?1:0),r=Math.floor(r/2);a.push(n?1:0),a.reverse();const l=a.join("");let h="";for(s=0;s<64;s+=8){let e=parseInt(l.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),h+=e}return h.toLowerCase()};const S=new RegExp("^-?(0*)\\d{1,10}$"),tryParseInt=function(e){if(S.test(e)){const t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},exceptionGuard=function(e){try{e()}catch(e){setTimeout((()=>{const t=e.stack||"";throw warn("Exception was thrown by user callback.",t),e}),Math.floor(0))}},setTimeoutNonBlocking=function(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n};class AppCheckTokenProvider{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,r(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then((e=>this.appCheck=e))}getToken(e){if(this.serverAppAppCheckToken){if(e)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(e):new Promise(((t,n)=>{setTimeout((()=>{this.appCheck?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){this.appCheckProvider?.get().then((t=>t.addTokenListener(e)))}notifyForInvalidToken(){warn(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}}class FirebaseAuthTokenProvider{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit((e=>this.auth_=e))}getToken(e){return this.auth_?this.auth_.getToken(e).catch((e=>e&&"auth/token-not-initialized"===e.code?(log("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e))):new Promise(((t,n)=>{setTimeout((()=>{this.auth_?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then((t=>t.addAuthTokenListener(e)))}removeTokenChangeListener(e){this.authProvider_.get().then((t=>t.removeAuthTokenListener(e)))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',warn(e)}}class EmulatorTokenProvider{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}EmulatorTokenProvider.OWNER="owner";const P=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,I="ac",b="websocket",N="long_polling";class RepoInfo{constructor(e,t,n,r,i=!1,o="",s=!1,a=!1,l=null){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=o,this.includeNamespaceInQueryParams=s,this.isUsingEmulator=a,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=f.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&f.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function repoInfoConnectionURL(e,t,n){let r;if(assert("string"==typeof t,"typeof type must == string"),assert("object"==typeof n,"typeof params must == object"),t===b)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==N)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}(function repoInfoNeedsQueryParam(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams})(e)&&(n.ns=e.namespace);const i=[];return each(n,((e,t)=>{i.push(e+"="+t)})),r+i.join("&")}class StatsCollection{constructor(){this.counters_={}}incrementCounter(e,t=1){contains(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return deepCopy(this.counters_)}}const R={},k={};function statsManagerGetCollection(e){const t=e.toString();return R[t]||(R[t]=new StatsCollection),R[t]}class PacketReceiver{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&exceptionGuard((()=>{this.onMessage_(e[t])}));if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const A="start";class BrowserPollConnection{constructor(e,t,n,r,i,o,s){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=o,this.lastSessionId=s,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=logWrapper(e),this.stats_=statsManagerGetCollection(t),this.urlFn=e=>(this.appCheckToken&&(e[I]=this.appCheckToken),repoInfoConnectionURL(t,N,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new PacketReceiver(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout((()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null}),Math.floor(3e4)),function(e){if("complete"===document.readyState)e();else{let t=!1;const wrappedFn=function(){document.body?t||(t=!0,e()):setTimeout(wrappedFn,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",wrappedFn,!1),window.addEventListener("load",wrappedFn,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",(()=>{"complete"===document.readyState&&wrappedFn()})),window.attachEvent("onload",wrappedFn))}}((()=>{if(this.isClosed_)return;this.scriptTagHolder=new FirebaseIFrameScriptHolder(((...e)=>{const[t,n,r,i,o]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===A)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,(()=>{this.onClosed_()}))):this.onClosed_()}}),((...e)=>{const[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)}),(()=>{this.onClosed_()}),this.urlFn);const e={};e[A]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e[I]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&P.test(location.hostname)&&(e.r="f");const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,(()=>{}))}))}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){BrowserPollConnection.forceAllow_=!0}static forceDisallow(){BrowserPollConnection.forceDisallow_=!0}static isAvailable(){return!!BrowserPollConnection.forceAllow_||!(BrowserPollConnection.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){const t=stringify(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=base64Encode(t),r=splitStringBySize(n,1840);for(let e=0;e<r.length;e++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,r.length,r[e]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const t=stringify(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class FirebaseIFrameScriptHolder{constructor(e,t,n,r){this.onDisconnect=n,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=v(),window["pLPCommand"+this.uniqueCallbackIdentifier]=e,window["pRTLPCB"+this.uniqueCallbackIdentifier]=t,this.myIFrame=FirebaseIFrameScriptHolder.createIFrame_();let n="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,11)){n='<script>document.domain="'+document.domain+'";<\/script>'}const r="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(r),this.myIFrame.doc.close()}catch(e){log("frame writing exception"),e.stack&&log(e.stack),log(e)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||log("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout((()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)}),Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",r=0;for(;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+30+n.length<=1870))break;{const e=this.pendingSegs.shift();n=n+"&seg"+r+"="+e.seg+"&ts"+r+"="+e.ts+"&d"+r+"="+e.d,r++}}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const doNewRequest=()=>{this.outstandingRequests.delete(t),this.newRequest_()},n=setTimeout(doNewRequest,Math.floor(25e3));this.addTag(e,(()=>{clearTimeout(n),doNewRequest()}))}addTag(e,t){setTimeout((()=>{try{if(!this.sendNewPolls)return;const n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){const e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{log("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(e){}}),Math.floor(1))}}let x=null;"undefined"!=typeof MozWebSocket?x=MozWebSocket:"undefined"!=typeof WebSocket&&(x=WebSocket);class WebSocketConnection{constructor(e,t,n,r,i,o,s){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=logWrapper(this.connId),this.stats_=statsManagerGetCollection(t),this.connURL=WebSocketConnection.connectionURL_(t,o,s,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){const o={v:"5"};return"undefined"!=typeof location&&location.hostname&&P.test(location.hostname)&&(o.r="f"),t&&(o.s=t),n&&(o.ls=n),r&&(o[I]=r),i&&(o.p=i),repoInfoConnectionURL(e,b,o)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,f.set("previous_websocket_failure",!0);try{let e;isNodeSdk(),this.mySock=new x(this.connURL,[],e)}catch(e){this.log_("Error instantiating WebSocket.");const t=e.message||e.data;return t&&this.log_(t),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){WebSocketConnection.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==x&&!WebSocketConnection.forceDisallow_}static previouslyFailed(){return f.isInMemoryStorage||!0===f.get("previous_websocket_failure")}markConnectionHealthy(){f.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=jsonEval(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(assert(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=stringify(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=splitStringBySize(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e<n.length;e++)this.sendString_(n[e])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval((()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()}),Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}WebSocketConnection.responsesRequiredToBeHealthy=2,WebSocketConnection.healthyTimeout=3e4;class TransportManager{static get ALL_TRANSPORTS(){return[BrowserPollConnection,WebSocketConnection]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){const t=WebSocketConnection&&WebSocketConnection.isAvailable();let n=t&&!WebSocketConnection.previouslyFailed();if(e.webSocketOnly&&(t||warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[WebSocketConnection];else{const e=this.transports_=[];for(const t of TransportManager.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);TransportManager.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}TransportManager.globalTransportInitialized_=!1;class Connection{constructor(e,t,n,r,i,o,s,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=o,this.onReady_=s,this.onDisconnect_=a,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=logWrapper("c:"+this.id+":"),this.transportManager_=new TransportManager(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout((()=>{this.conn_&&this.conn_.open(t,n)}),Math.floor(0));const r=e.healthyTimeout||0;r>0&&(this.healthyTimeout_=setTimeoutNonBlocking((()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))}),Math.floor(r)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if("t"in e){const t=e.t;"a"===t?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=requireKey("t",e),n=requireKey("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const t=requireKey("t",e),n=requireKey("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){const t=requireKey("t",e);if("d"in e){const n=e.d;if("h"===t){const e={...n};this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?error("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):error("Unknown control packet command: "+t)}}onHandshake_(e){const t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&warn("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),setTimeoutNonBlocking((()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())}),Math.floor(6e4))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):setTimeoutNonBlocking((()=>{this.sendPingOnPrimaryIfNecessary_()}),Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(f.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class ServerActions{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class EventEmitter{constructor(e){this.allowedEvents_=e,this.listeners_={},assert(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});const r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let e=0;e<r.length;e++)if(r[e].callback===t&&(!n||n===r[e].context))return void r.splice(e,1)}validateEventType_(e){assert(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}class OnlineMonitor extends EventEmitter{static getInstance(){return new OnlineMonitor}constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||isMobileCordova()||(window.addEventListener("online",(()=>{this.online_||(this.online_=!0,this.trigger("online",!0))}),!1),window.addEventListener("offline",(()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))}),!1))}getInitialEvent(e){return assert("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class Path{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++)this.pieces_[e].length>0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function newEmptyPath(){return new Path("")}function pathGetFront(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function pathGetLength(e){return e.pieces_.length-e.pieceNum_}function pathPopFront(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new Path(e.pieces_,t)}function pathGetBack(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function pathSlice(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function pathParent(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new Path(t,0)}function pathChild(e,t){const n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++)n.push(e.pieces_[t]);if(t instanceof Path)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{const e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new Path(n,0)}function pathIsEmpty(e){return e.pieceNum_>=e.pieces_.length}function newRelativePath(e,t){const n=pathGetFront(e),r=pathGetFront(t);if(null===n)return t;if(n===r)return newRelativePath(pathPopFront(e),pathPopFront(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function pathCompare(e,t){const n=pathSlice(e,0),r=pathSlice(t,0);for(let e=0;e<n.length&&e<r.length;e++){const t=nameCompare(n[e],r[e]);if(0!==t)return t}return n.length===r.length?0:n.length<r.length?-1:1}function pathEquals(e,t){if(pathGetLength(e)!==pathGetLength(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function pathContains(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(pathGetLength(e)>pathGetLength(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class ValidationPath{constructor(e,t){this.errorPrefix_=t,this.parts_=pathSlice(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++)this.byteLength_+=stringLength(this.parts_[e]);validationPathCheckValid(this)}}function validationPathCheckValid(e){if(e.byteLength_>768)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(e.parts_.length>32)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+validationPathToErrorString(e))}function validationPathToErrorString(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class VisibilityMonitor extends EventEmitter{static getInstance(){return new VisibilityMonitor}constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}getInitialEvent(e){return assert("visible"===e,"Unknown event type: "+e),[this.visible_]}}const F=1e3;class PersistentConnection extends ServerActions{constructor(e,t,n,r,i,o,s,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=o,this.appCheckTokenProvider_=s,this.authOverride_=a,this.id=PersistentConnection.nextPersistentConnectionId_++,this.log_=logWrapper("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=F,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a&&!isNodeSdk())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");VisibilityMonitor.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&OnlineMonitor.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){const r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(stringify(i)),assert(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();const t=new Deferred,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{const n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;const r=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(r),t.promise}listen(e,t,n,r){this.initConnection_();const i=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+i),this.listens.has(o)||this.listens.set(o,new Map),assert(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),assert(!this.listens.get(o).has(i),"listen() called twice for same path/queryId.");const s={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(o).set(i,s),this.connected_&&this.sendListen_(s)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,(n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)}))}sendListen_(e){const t=e.query,n=t._path.toString(),r=t._queryIdentifier;this.log_("Listen on "+n+" for "+r);const i={p:n};e.tag&&(i.q=t._queryObject,i.t=e.tag),i.h=e.hashFn(),this.sendRequest("q",i,(i=>{const o=i.d,s=i.s;PersistentConnection.warnOnListenWarnings_(o,t);(this.listens.get(n)&&this.listens.get(n).get(r))===e&&(this.log_("listen response",i),"ok"!==s&&this.removeListen_(n,r),e.onComplete&&e.onComplete(s,o))}))}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&contains(e,"w")){const n=safeGet(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();warn(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${e} at ${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},(()=>{})),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||function(e){const t=decode(e).claims;return"object"==typeof t&&!0===t.admin}(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},(()=>{}))}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,t=function(e){const t=decode(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")}(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,(t=>{const n=t.s,r=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,r))}))}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},(e=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)}))}unlisten(e,t){const n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),assert(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query");this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,r){const i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,(e=>{r&&setTimeout((()=>{r(e.s,e.d)}),Math.floor(0))}))}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const o={p:t,d:n};void 0!==i&&(o.h=i),this.outstandingPuts_.push({action:e,request:o,onComplete:r}),this.outstandingPutCount_++;const s=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(s):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,r=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,(n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(n.s,n.d)}))}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,(e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}}))}}onDataMessage_(e){if("r"in e){this.log_("from server: "+stringify(e));const t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):error("Unrecognized action received from server: "+stringify(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){assert(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout((()=>{this.establishConnectionTimer_=null,this.establishConnection_()}),Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=F,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=F,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){if(this.visible_){if(this.lastConnectionEstablishedTime_){(new Date).getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=F),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();const e=Math.max(0,(new Date).getTime()-this.lastConnectionAttemptTime_);let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),n=this.onRealtimeDisconnect_.bind(this),r=this.id+":"+PersistentConnection.nextConnectionId_++,i=this.lastSessionId;let o=!1,s=null;const closeFn=function(){s?s.close():(o=!0,n())},sendRequestFn=function(e){assert(s,"sendRequest call when we're not connected not allowed."),s.sendRequest(e)};this.realtime_={close:closeFn,sendRequest:sendRequestFn};const a=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[l,h]=await Promise.all([this.authTokenProvider_.getToken(a),this.appCheckTokenProvider_.getToken(a)]);o?log("getToken() completed but was canceled"):(log("getToken() completed. Creating connection."),this.authToken_=l&&l.accessToken,this.appCheckToken_=h&&h.token,s=new Connection(r,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,(e=>{warn(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")}),i))}catch(e){this.log_("Failed to get token: "+e),o||(this.repoInfo_.nodeAdmin&&warn(e),closeFn())}}}interrupt(e){log("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){log("Resuming connection for reason: "+e),delete this.interruptReasons_[e],isEmpty(this.interruptReasons_)&&(this.reconnectDelay_=F,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map((e=>ObjectToUniqueKey(e))).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){const n=new Path(e).toString();let r;if(this.listens.has(n)){const e=this.listens.get(n);r=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){log("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){log("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){const e={};e["sdk.js."+m.replace(/\./g,"-")]=1,isMobileCordova()?e["framework.cordova"]=1:function isReactNative(){return"object"==typeof navigator&&"ReactNative"===navigator.product}()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=OnlineMonitor.getInstance().currentlyOnline();return isEmpty(this.interruptReasons_)&&e}}PersistentConnection.nextPersistentConnectionId_=0,PersistentConnection.nextConnectionId_=0;class NamedNode{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new NamedNode(e,t)}}class Index{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const n=new NamedNode(T,e),r=new NamedNode(T,t);return 0!==this.compare(n,r)}minPost(){return NamedNode.MIN}}let O;class KeyIndex extends Index{static get __EMPTY_NODE(){return O}static set __EMPTY_NODE(e){O=e}compare(e,t){return nameCompare(e.name,t.name)}isDefinedOn(e){throw assertionError("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return NamedNode.MIN}maxPost(){return new NamedNode(E,O)}makePost(e,t){return assert("string"==typeof e,"KeyIndex indexValue must always be a string."),new NamedNode(e,O)}toString(){return".key"}}const D=new KeyIndex;class SortedMapIterator{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let o=1;for(;!e.isEmpty();)if(o=t?n(e.key,t):1,r&&(o*=-1),o<0)e=this.isReverse_?e.left:e.right;else{if(0===o){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e,t=this.nodeStack_.pop();if(e=this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value},this.isReverse_)for(t=t.left;!t.isEmpty();)this.nodeStack_.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack_.push(t),t=t.left;return e}hasNext(){return this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class LLRBNode{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:LLRBNode.RED,this.left=null!=r?r:SortedMap.EMPTY_NODE,this.right=null!=i?i:SortedMap.EMPTY_NODE}copy(e,t,n,r,i){return new LLRBNode(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;const i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return SortedMap.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let n,r;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return SortedMap.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){const e=this.copy(null,null,LLRBNode.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,LLRBNode.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}LLRBNode.RED=!0,LLRBNode.BLACK=!1;class SortedMap{constructor(e,t=SortedMap.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new SortedMap(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,LLRBNode.BLACK,null,null))}remove(e){return new SortedMap(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,LLRBNode.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t)return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new SortedMapIterator(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new SortedMapIterator(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new SortedMapIterator(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new SortedMapIterator(this.root_,null,this.comparator_,!0,e)}}function NAME_ONLY_COMPARATOR(e,t){return nameCompare(e.name,t.name)}function NAME_COMPARATOR(e,t){return nameCompare(e,t)}let L;SortedMap.EMPTY_NODE=new class LLRBEmptyNode{copy(e,t,n,r,i){return this}insert(e,t,n){return new LLRBNode(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};const priorityHashText=function(e){return"number"==typeof e?"number:"+doubleToIEEE754String(e):"string:"+e},validatePriorityNode=function(e){if(e.isLeafNode()){const t=e.val();assert("string"==typeof t||"number"==typeof t||"object"==typeof t&&contains(t,".sv"),"Priority must be a string or number.")}else assert(e===L||e.isEmpty(),"priority of unexpected type.");assert(e===L||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let M,W,q;class LeafNode{static set __childrenNodeConstructor(e){M=e}static get __childrenNodeConstructor(){return M}constructor(e,t=LeafNode.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,assert(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),validatePriorityNode(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new LeafNode(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:LeafNode.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return pathIsEmpty(e)?this:".priority"===pathGetFront(e)?this.priorityNode_:LeafNode.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const n=pathGetFront(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(assert(".priority"!==n||1===pathGetLength(e),".priority must be the last token in a path"),this.updateImmediateChild(n,LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+priorityHashText(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?doubleToIEEE754String(this.value_):this.value_,this.lazyHash_=sha1(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===LeafNode.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof LeafNode.__childrenNodeConstructor?-1:(assert(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,n=typeof this.value_,r=LeafNode.VALUE_TYPE_ORDER.indexOf(t),i=LeafNode.VALUE_TYPE_ORDER.indexOf(n);return assert(r>=0,"Unknown leaf type: "+t),assert(i>=0,"Unknown leaf type: "+n),r===i?"object"===n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){const t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}return!1}}LeafNode.VALUE_TYPE_ORDER=["object","boolean","number","string"];const G=new class PriorityIndex extends Index{compare(e,t){const n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return 0===i?nameCompare(e.name,t.name):i}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return NamedNode.MIN}maxPost(){return new NamedNode(E,new LeafNode("[PRIORITY-POST]",q))}makePost(e,t){const n=W(e);return new NamedNode(t,new LeafNode("[PRIORITY-POST]",n))}toString(){return".priority"}},Q=Math.log(2);class Base12Num{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/Q,10)),this.current_=this.count-1;const n=(r=this.count,parseInt(Array(r+1).join("1"),2));var r;this.bits_=e+1&n}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const buildChildSet=function(e,t,n,r){e.sort(t);const buildBalancedTree=function(t,r){const i=r-t;let o,s;if(0===i)return null;if(1===i)return o=e[t],s=n?n(o):o,new LLRBNode(s,o.node,LLRBNode.BLACK,null,null);{const a=parseInt(i/2,10)+t,l=buildBalancedTree(t,a),h=buildBalancedTree(a+1,r);return o=e[a],s=n?n(o):o,new LLRBNode(s,o.node,LLRBNode.BLACK,l,h)}},i=function(t){let r=null,i=null,o=e.length;const buildPennant=function(t,r){const i=o-t,s=o;o-=t;const a=buildBalancedTree(i+1,s),l=e[i],h=n?n(l):l;attachPennant(new LLRBNode(h,l.node,r,null,a))},attachPennant=function(e){r?(r.left=e,r=e):(i=e,r=e)};for(let e=0;e<t.count;++e){const n=t.nextBitIsOne(),r=Math.pow(2,t.count-(e+1));n?buildPennant(r,LLRBNode.BLACK):(buildPennant(r,LLRBNode.BLACK),buildPennant(r,LLRBNode.RED))}return i}(new Base12Num(e.length));return new SortedMap(r||t,i)};let B;const U={};class IndexMap{static get Default(){return assert(U&&G,"ChildrenNode.ts has not been loaded"),B=B||new IndexMap({".priority":U},{".priority":G}),B}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){const t=safeGet(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof SortedMap?t:null}hasIndex(e){return contains(this.indexSet_,e.toString())}addIndex(e,t){assert(e!==D,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(NamedNode.Wrap);let o,s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();o=r?buildChildSet(n,e.getCompare()):U;const a=e.toString(),l={...this.indexSet_};l[a]=e;const h={...this.indexes_};return h[a]=o,new IndexMap(h,l)}addToIndexes(e,t){const n=map(this.indexes_,((n,r)=>{const i=safeGet(this.indexSet_,r);if(assert(i,"Missing index implementation for "+r),n===U){if(i.isDefinedOn(e.node)){const n=[],r=t.getIterator(NamedNode.Wrap);let o=r.getNext();for(;o;)o.name!==e.name&&n.push(o),o=r.getNext();return n.push(e),buildChildSet(n,i.getCompare())}return U}{const r=t.get(e.name);let i=n;return r&&(i=i.remove(new NamedNode(e.name,r))),i.insert(e,e.node)}}));return new IndexMap(n,this.indexSet_)}removeFromIndexes(e,t){const n=map(this.indexes_,(n=>{if(n===U)return n;{const r=t.get(e.name);return r?n.remove(new NamedNode(e.name,r)):n}}));return new IndexMap(n,this.indexSet_)}}let V;class ChildrenNode{static get EMPTY_NODE(){return V||(V=new ChildrenNode(new SortedMap(NAME_COMPARATOR),null,IndexMap.Default))}constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&validatePriorityNode(this.priorityNode_),this.children_.isEmpty()&&assert(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||V}updatePriority(e){return this.children_.isEmpty()?this:new ChildrenNode(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?V:t}}getChild(e){const t=pathGetFront(e);return null===t?this:this.getImmediateChild(t).getChild(pathPopFront(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if(assert(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{const n=new NamedNode(e,t);let r,i;t.isEmpty()?(r=this.children_.remove(e),i=this.indexMap_.removeFromIndexes(n,this.children_)):(r=this.children_.insert(e,t),i=this.indexMap_.addToIndexes(n,this.children_));const o=r.isEmpty()?V:this.priorityNode_;return new ChildrenNode(r,o,i)}}updateChild(e,t){const n=pathGetFront(e);if(null===n)return t;{assert(".priority"!==pathGetFront(e)||1===pathGetLength(e),".priority must be the last token in a path");const r=this.getImmediateChild(n).updateChild(pathPopFront(e),t);return this.updateImmediateChild(n,r)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,r=0,i=!0;if(this.forEachChild(G,((o,s)=>{t[o]=s.val(e),n++,i&&ChildrenNode.INTEGER_REGEXP_.test(o)?r=Math.max(r,Number(o)):i=!1})),!e&&i&&r<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+priorityHashText(this.getPriority().val())+":"),this.forEachChild(G,((t,n)=>{const r=n.hash();""!==r&&(e+=":"+t+":"+r)})),this.lazyHash_=""===e?"":sha1(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){const n=r.getPredecessorKey(new NamedNode(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new NamedNode(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new NamedNode(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal((e=>t(e.name,e.node))):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,(e=>e));{const n=this.children_.getIteratorFrom(e.name,NamedNode.Wrap);let r=n.peek();for(;null!=r&&t.compare(r,e)<0;)n.getNext(),r=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,(e=>e));{const n=this.children_.getReverseIteratorFrom(e.name,NamedNode.Wrap);let r=n.peek();for(;null!=r&&t.compare(r,e)>0;)n.getNext(),r=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===H?-1:0}withIndex(e){if(e===D||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new ChildrenNode(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===D||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(G),n=t.getIterator(G);let r=e.getNext(),i=n.getNext();for(;r&&i;){if(r.name!==i.name||!r.node.equals(i.node))return!1;r=e.getNext(),i=n.getNext()}return null===r&&null===i}return!1}return!1}}resolveIndex_(e){return e===D?null:this.indexMap_.get(e.toString())}}ChildrenNode.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;const H=new class MaxNode extends ChildrenNode{constructor(){super(new SortedMap(NAME_COMPARATOR),ChildrenNode.EMPTY_NODE,IndexMap.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ChildrenNode.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(NamedNode,{MIN:{value:new NamedNode(T,ChildrenNode.EMPTY_NODE)},MAX:{value:new NamedNode(E,H)}}),KeyIndex.__EMPTY_NODE=ChildrenNode.EMPTY_NODE,LeafNode.__childrenNodeConstructor=ChildrenNode,function setMaxNode$1(e){L=e}(H),function setMaxNode(e){q=e}(H);function nodeFromJSON(e,t=null){if(null===e)return ChildrenNode.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),assert(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e){return new LeafNode(e,nodeFromJSON(t))}if(e instanceof Array){let n=ChildrenNode.EMPTY_NODE;return each(e,((t,r)=>{if(contains(e,t)&&"."!==t.substring(0,1)){const e=nodeFromJSON(r);!e.isLeafNode()&&e.isEmpty()||(n=n.updateImmediateChild(t,e))}})),n.updatePriority(nodeFromJSON(t))}{const n=[];let r=!1;if(each(e,((e,t)=>{if("."!==e.substring(0,1)){const i=nodeFromJSON(t);i.isEmpty()||(r=r||!i.getPriority().isEmpty(),n.push(new NamedNode(e,i)))}})),0===n.length)return ChildrenNode.EMPTY_NODE;const i=buildChildSet(n,NAME_ONLY_COMPARATOR,(e=>e.name),NAME_COMPARATOR);if(r){const e=buildChildSet(n,G.getCompare());return new ChildrenNode(i,nodeFromJSON(t),new IndexMap({".priority":e},{".priority":G}))}return new ChildrenNode(i,nodeFromJSON(t),IndexMap.Default)}}!function setNodeFromJSON(e){W=e}(nodeFromJSON);class PathIndex extends Index{constructor(e){super(),this.indexPath_=e,assert(!pathIsEmpty(e)&&".priority"!==pathGetFront(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node),r=this.extractChild(t.node),i=n.compareTo(r);return 0===i?nameCompare(e.name,t.name):i}makePost(e,t){const n=nodeFromJSON(e),r=ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_,n);return new NamedNode(t,r)}maxPost(){const e=ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_,H);return new NamedNode(E,e)}toString(){return pathSlice(this.indexPath_,0).join("/")}}const j=new class ValueIndex extends Index{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?nameCompare(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return NamedNode.MIN}maxPost(){return NamedNode.MAX}makePost(e,t){const n=nodeFromJSON(e);return new NamedNode(t,n)}toString(){return".value"}};function changeValue(e){return{type:"value",snapshotNode:e}}function changeChildAdded(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function changeChildRemoved(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function changeChildChanged(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class IndexedFilter{constructor(e){this.index_=e}updateChild(e,t,n,r,i,o){assert(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const s=e.getImmediateChild(t);return s.getChild(r).equals(n.getChild(r))&&s.isEmpty()===n.isEmpty()?e:(null!=o&&(n.isEmpty()?e.hasChild(t)?o.trackChildChange(changeChildRemoved(t,s)):assert(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):s.isEmpty()?o.trackChildChange(changeChildAdded(t,n)):o.trackChildChange(changeChildChanged(t,n,s))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(G,((e,r)=>{t.hasChild(e)||n.trackChildChange(changeChildRemoved(e,r))})),t.isLeafNode()||t.forEachChild(G,((t,r)=>{if(e.hasChild(t)){const i=e.getImmediateChild(t);i.equals(r)||n.trackChildChange(changeChildChanged(t,r,i))}else n.trackChildChange(changeChildAdded(t,r))}))),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?ChildrenNode.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class RangedFilter{constructor(e){this.indexedFilter_=new IndexedFilter(e.getIndex()),this.index_=e.getIndex(),this.startPost_=RangedFilter.getStartPost_(e),this.endPost_=RangedFilter.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,o){return this.matches(new NamedNode(t,n))||(n=ChildrenNode.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,o)}updateFullNode(e,t,n){t.isLeafNode()&&(t=ChildrenNode.EMPTY_NODE);let r=t.withIndex(this.index_);r=r.updatePriority(ChildrenNode.EMPTY_NODE);const i=this;return t.forEachChild(G,((e,t)=>{i.matches(new NamedNode(e,t))||(r=r.updateImmediateChild(e,ChildrenNode.EMPTY_NODE))})),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class LimitedFilter{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{const t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{const t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new RangedFilter(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,o){return this.rangedFilter_.matches(new NamedNode(t,n))||(n=ChildrenNode.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,o):this.fullLimitUpdateChild_(e,t,n,i,o)}updateFullNode(e,t,n){let r;if(t.isLeafNode()||t.isEmpty())r=ChildrenNode.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;r=ChildrenNode.EMPTY_NODE.withIndex(this.index_),e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){const t=e.getNext();if(this.withinDirectionalStart(t)){if(!this.withinDirectionalEnd(t))break;r=r.updateImmediateChild(t.name,t.node),n++}}}else{let e;r=t.withIndex(this.index_),r=r.updatePriority(ChildrenNode.EMPTY_NODE),e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_);let n=0;for(;e.hasNext();){const t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:r=r.updateImmediateChild(t.name,ChildrenNode.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let o;if(this.reverse_){const e=this.index_.getCompare();o=(t,n)=>e(n,t)}else o=this.index_.getCompare();const s=e;assert(s.numChildren()===this.limit_,"");const a=new NamedNode(t,n),l=this.reverse_?s.getFirstChild(this.index_):s.getLastChild(this.index_),h=this.rangedFilter_.matches(a);if(s.hasChild(t)){const e=s.getImmediateChild(t);let c=r.getChildAfterChild(this.index_,l,this.reverse_);for(;null!=c&&(c.name===t||s.hasChild(c.name));)c=r.getChildAfterChild(this.index_,c,this.reverse_);const d=null==c?1:o(c,a);if(h&&!n.isEmpty()&&d>=0)return null!=i&&i.trackChildChange(changeChildChanged(t,n,e)),s.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(changeChildRemoved(t,e));const n=s.updateImmediateChild(t,ChildrenNode.EMPTY_NODE);return null!=c&&this.rangedFilter_.matches(c)?(null!=i&&i.trackChildChange(changeChildAdded(c.name,c.node)),n.updateImmediateChild(c.name,c.node)):n}}return n.isEmpty()?e:h&&o(l,a)>=0?(null!=i&&(i.trackChildChange(changeChildRemoved(l.name,l.node)),i.trackChildChange(changeChildAdded(t,n))),s.updateImmediateChild(t,n).updateImmediateChild(l.name,ChildrenNode.EMPTY_NODE)):e}}class QueryParams{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=G}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return assert(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return assert(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:T}hasEnd(){return this.endSet_}getIndexEndValue(){return assert(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return assert(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:E}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return assert(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===G}copy(){const e=new QueryParams;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function queryParamsStartAt(e,t,n){const r=e.copy();return r.startSet_=!0,void 0===t&&(t=null),r.indexStartValue_=t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function queryParamsEndAt(e,t,n){const r=e.copy();return r.endSet_=!0,void 0===t&&(t=null),r.indexEndValue_=t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function queryParamsOrderBy(e,t){const n=e.copy();return n.index_=t,n}function queryParamsToRestQueryStringParameters(e){const t={};if(e.isDefault())return t;let n;if(e.index_===G?n="$priority":e.index_===j?n="$value":e.index_===D?n="$key":(assert(e.index_ instanceof PathIndex,"Unrecognized index type!"),n=e.index_.toString()),t.orderBy=stringify(n),e.startSet_){const n=e.startAfterSet_?"startAfter":"startAt";t[n]=stringify(e.indexStartValue_),e.startNameSet_&&(t[n]+=","+stringify(e.indexStartName_))}if(e.endSet_){const n=e.endBeforeSet_?"endBefore":"endAt";t[n]=stringify(e.indexEndValue_),e.endNameSet_&&(t[n]+=","+stringify(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function queryParamsGetQueryObject(e){const t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==G&&(t.i=e.index_.toString()),t}class ReadonlyRestClient extends ServerActions{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(assert(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=logWrapper("p:rest:"),this.listens_={}}listen(e,t,n,r){const i=e._path.toString();this.log_("Listen called for "+i+" "+e._queryIdentifier);const o=ReadonlyRestClient.getListenId_(e,n),s={};this.listens_[o]=s;const a=queryParamsToRestQueryStringParameters(e._queryParams);this.restRequest_(i+".json",a,((e,t)=>{let a=t;if(404===e&&(a=null,e=null),null===e&&this.onDataUpdate_(i,a,!1,n),safeGet(this.listens_,o)===s){let t;t=e?401===e?"permission_denied":"rest_error:"+e:"ok",r(t,null)}}))}unlisten(e,t){const n=ReadonlyRestClient.getListenId_(e,t);delete this.listens_[n]}get(e){const t=queryParamsToRestQueryStringParameters(e._queryParams),n=e._path.toString(),r=new Deferred;return this.restRequest_(n+".json",t,((e,t)=>{let i=t;404===e&&(i=null,e=null),null===e?(this.onDataUpdate_(n,i,!1,null),r.resolve(i)):r.reject(new Error(i))})),r.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then((([r,i])=>{r&&r.accessToken&&(t.auth=r.accessToken),i&&i.token&&(t.ac=i.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+function querystring(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}(t);this.log_("Sending REST request for "+o);const s=new XMLHttpRequest;s.onreadystatechange=()=>{if(n&&4===s.readyState){this.log_("REST Response for "+o+" received. status:",s.status,"response:",s.responseText);let e=null;if(s.status>=200&&s.status<300){try{e=jsonEval(s.responseText)}catch(e){warn("Failed to parse JSON response for "+o+": "+s.responseText)}n(null,e)}else 401!==s.status&&404!==s.status&&warn("Got unsuccessful REST response for "+o+" Status: "+s.status),n(s.status);n=null}},s.open("GET",o,!0),s.send()}))}}class SnapshotHolder{constructor(){this.rootNode_=ChildrenNode.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function newSparseSnapshotTree(){return{value:null,children:new Map}}function sparseSnapshotTreeRemember(e,t,n){if(pathIsEmpty(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const r=pathGetFront(t);e.children.has(r)||e.children.set(r,newSparseSnapshotTree());sparseSnapshotTreeRemember(e.children.get(r),t=pathPopFront(t),n)}}function sparseSnapshotTreeForget(e,t){if(pathIsEmpty(t))return e.value=null,e.children.clear(),!0;if(null!==e.value){if(e.value.isLeafNode())return!1;{const n=e.value;return e.value=null,n.forEachChild(G,((t,n)=>{sparseSnapshotTreeRemember(e,new Path(t),n)})),sparseSnapshotTreeForget(e,t)}}if(e.children.size>0){const n=pathGetFront(t);if(t=pathPopFront(t),e.children.has(n)){sparseSnapshotTreeForget(e.children.get(n),t)&&e.children.delete(n)}return 0===e.children.size}return!0}function sparseSnapshotTreeForEachTree(e,t,n){null!==e.value?n(t,e.value):function sparseSnapshotTreeForEachChild(e,t){e.children.forEach(((e,n)=>{t(n,e)}))}(e,((e,r)=>{sparseSnapshotTreeForEachTree(r,new Path(t.toString()+"/"+e),n)}))}class StatsListener{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t={...e};return this.last_&&each(this.last_,((e,n)=>{t[e]=t[e]-n})),this.last_=e,t}}class StatsReporter{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new StatsListener(e);const n=1e4+2e4*Math.random();setTimeoutNonBlocking(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;each(e,((e,r)=>{r>0&&contains(this.statsToReport_,e)&&(t[e]=r,n=!0)})),n&&this.server_.reportStats(t),setTimeoutNonBlocking(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}var z;function newOperationSourceServerTaggedQuery(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}!function(e){e[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(z||(z={}));class AckUserWrite{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=z.ACK_USER_WRITE,this.source={fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}operationForChild(e){if(pathIsEmpty(this.path)){if(null!=this.affectedTree.value)return assert(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new Path(e));return new AckUserWrite(newEmptyPath(),t,this.revert)}}return assert(pathGetFront(this.path)===e,"operationForChild called for unrelated child."),new AckUserWrite(pathPopFront(this.path),this.affectedTree,this.revert)}}class ListenComplete{constructor(e,t){this.source=e,this.path=t,this.type=z.LISTEN_COMPLETE}operationForChild(e){return pathIsEmpty(this.path)?new ListenComplete(this.source,newEmptyPath()):new ListenComplete(this.source,pathPopFront(this.path))}}class Overwrite{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=z.OVERWRITE}operationForChild(e){return pathIsEmpty(this.path)?new Overwrite(this.source,newEmptyPath(),this.snap.getImmediateChild(e)):new Overwrite(this.source,pathPopFront(this.path),this.snap)}}class Merge{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=z.MERGE}operationForChild(e){if(pathIsEmpty(this.path)){const t=this.children.subtree(new Path(e));return t.isEmpty()?null:t.value?new Overwrite(this.source,newEmptyPath(),t.value):new Merge(this.source,newEmptyPath(),t)}return assert(pathGetFront(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Merge(this.source,pathPopFront(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class CacheNode{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(pathIsEmpty(e))return this.isFullyInitialized()&&!this.filtered_;const t=pathGetFront(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class EventGenerator{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function eventGeneratorGenerateEventsForType(e,t,n,r,i,o){const s=r.filter((e=>e.type===n));s.sort(((t,n)=>function eventGeneratorCompareChanges(e,t,n){if(null==t.childName||null==n.childName)throw assertionError("Should only compare child_ events.");const r=new NamedNode(t.childName,t.snapshotNode),i=new NamedNode(n.childName,n.snapshotNode);return e.index_.compare(r,i)}(e,t,n))),s.forEach((n=>{const r=function eventGeneratorMaterializeSingleChange(e,t,n){return"value"===t.type||"child_removed"===t.type||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}(e,n,o);i.forEach((i=>{i.respondsTo(n.type)&&t.push(i.createEvent(r,e.query_))}))}))}function newViewCache(e,t){return{eventCache:e,serverCache:t}}function viewCacheUpdateEventSnap(e,t,n,r){return newViewCache(new CacheNode(t,n,r),e.serverCache)}function viewCacheUpdateServerSnap(e,t,n,r){return newViewCache(e.eventCache,new CacheNode(t,n,r))}function viewCacheGetCompleteEventSnap(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function viewCacheGetCompleteServerSnap(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let K;class ImmutableTree{static fromObject(e){let t=new ImmutableTree(null);return each(e,((e,n)=>{t=t.set(new Path(e),n)})),t}constructor(e,t=(()=>(K||(K=new SortedMap(stringCompare)),K))()){this.value=e,this.children=t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:newEmptyPath(),value:this.value};if(pathIsEmpty(e))return null;{const n=pathGetFront(e),r=this.children.get(n);if(null!==r){const i=r.findRootMostMatchingPathAndValue(pathPopFront(e),t);if(null!=i){return{path:pathChild(new Path(n),i.path),value:i.value}}return null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,(()=>!0))}subtree(e){if(pathIsEmpty(e))return this;{const t=pathGetFront(e),n=this.children.get(t);return null!==n?n.subtree(pathPopFront(e)):new ImmutableTree(null)}}set(e,t){if(pathIsEmpty(e))return new ImmutableTree(t,this.children);{const n=pathGetFront(e),r=(this.children.get(n)||new ImmutableTree(null)).set(pathPopFront(e),t),i=this.children.insert(n,r);return new ImmutableTree(this.value,i)}}remove(e){if(pathIsEmpty(e))return this.children.isEmpty()?new ImmutableTree(null):new ImmutableTree(null,this.children);{const t=pathGetFront(e),n=this.children.get(t);if(n){const r=n.remove(pathPopFront(e));let i;return i=r.isEmpty()?this.children.remove(t):this.children.insert(t,r),null===this.value&&i.isEmpty()?new ImmutableTree(null):new ImmutableTree(this.value,i)}return this}}get(e){if(pathIsEmpty(e))return this.value;{const t=pathGetFront(e),n=this.children.get(t);return n?n.get(pathPopFront(e)):null}}setTree(e,t){if(pathIsEmpty(e))return t;{const n=pathGetFront(e),r=(this.children.get(n)||new ImmutableTree(null)).setTree(pathPopFront(e),t);let i;return i=r.isEmpty()?this.children.remove(n):this.children.insert(n,r),new ImmutableTree(this.value,i)}}fold(e){return this.fold_(newEmptyPath(),e)}fold_(e,t){const n={};return this.children.inorderTraversal(((r,i)=>{n[r]=i.fold_(pathChild(e,r),t)})),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,newEmptyPath(),t)}findOnPath_(e,t,n){const r=!!this.value&&n(t,this.value);if(r)return r;if(pathIsEmpty(e))return null;{const r=pathGetFront(e),i=this.children.get(r);return i?i.findOnPath_(pathPopFront(e),pathChild(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,newEmptyPath(),t)}foreachOnPath_(e,t,n){if(pathIsEmpty(e))return this;{this.value&&n(t,this.value);const r=pathGetFront(e),i=this.children.get(r);return i?i.foreachOnPath_(pathPopFront(e),pathChild(t,r),n):new ImmutableTree(null)}}foreach(e){this.foreach_(newEmptyPath(),e)}foreach_(e,t){this.children.inorderTraversal(((n,r)=>{r.foreach_(pathChild(e,n),t)})),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal(((t,n)=>{n.value&&e(t,n.value)}))}}class CompoundWrite{constructor(e){this.writeTree_=e}static empty(){return new CompoundWrite(new ImmutableTree(null))}}function compoundWriteAddWrite(e,t,n){if(pathIsEmpty(t))return new CompoundWrite(new ImmutableTree(n));{const r=e.writeTree_.findRootMostValueAndPath(t);if(null!=r){const i=r.path;let o=r.value;const s=newRelativePath(i,t);return o=o.updateChild(s,n),new CompoundWrite(e.writeTree_.set(i,o))}{const r=new ImmutableTree(n),i=e.writeTree_.setTree(t,r);return new CompoundWrite(i)}}}function compoundWriteAddWrites(e,t,n){let r=e;return each(n,((e,n)=>{r=compoundWriteAddWrite(r,pathChild(t,e),n)})),r}function compoundWriteRemoveWrite(e,t){if(pathIsEmpty(t))return CompoundWrite.empty();{const n=e.writeTree_.setTree(t,new ImmutableTree(null));return new CompoundWrite(n)}}function compoundWriteHasCompleteWrite(e,t){return null!=compoundWriteGetCompleteNode(e,t)}function compoundWriteGetCompleteNode(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(newRelativePath(n.path,t)):null}function compoundWriteGetCompleteChildren(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(G,((e,n)=>{t.push(new NamedNode(e,n))})):e.writeTree_.children.inorderTraversal(((e,n)=>{null!=n.value&&t.push(new NamedNode(e,n.value))})),t}function compoundWriteChildCompoundWrite(e,t){if(pathIsEmpty(t))return e;{const n=compoundWriteGetCompleteNode(e,t);return new CompoundWrite(null!=n?new ImmutableTree(n):e.writeTree_.subtree(t))}}function compoundWriteIsEmpty(e){return e.writeTree_.isEmpty()}function compoundWriteApply(e,t){return applySubtreeWrite(newEmptyPath(),e.writeTree_,t)}function applySubtreeWrite(e,t,n){if(null!=t.value)return n.updateChild(e,t.value);{let r=null;return t.children.inorderTraversal(((t,i)=>{".priority"===t?(assert(null!==i.value,"Priority writes must always be leaf nodes"),r=i.value):n=applySubtreeWrite(pathChild(e,t),i,n)})),n.getChild(e).isEmpty()||null===r||(n=n.updateChild(pathChild(e,".priority"),r)),n}}function writeTreeChildWrites(e,t){return newWriteTreeRef(t,e)}function writeTreeRemoveWrite(e,t){const n=e.allWrites.findIndex((e=>e.writeId===t));assert(n>=0,"removeWrite called with nonexistent writeId.");const r=e.allWrites[n];e.allWrites.splice(n,1);let i=r.visible,o=!1,s=e.allWrites.length-1;for(;i&&s>=0;){const t=e.allWrites[s];t.visible&&(s>=n&&writeTreeRecordContainsPath_(t,r.path)?i=!1:pathContains(r.path,t.path)&&(o=!0)),s--}if(i){if(o)return function writeTreeResetTree_(e){e.visibleWrites=writeTreeLayerTree_(e.allWrites,writeTreeDefaultFilter_,newEmptyPath()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}(e),!0;if(r.snap)e.visibleWrites=compoundWriteRemoveWrite(e.visibleWrites,r.path);else{each(r.children,(t=>{e.visibleWrites=compoundWriteRemoveWrite(e.visibleWrites,pathChild(r.path,t))}))}return!0}return!1}function writeTreeRecordContainsPath_(e,t){if(e.snap)return pathContains(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&pathContains(pathChild(e.path,n),t))return!0;return!1}function writeTreeDefaultFilter_(e){return e.visible}function writeTreeLayerTree_(e,t,n){let r=CompoundWrite.empty();for(let i=0;i<e.length;++i){const o=e[i];if(t(o)){const e=o.path;let t;if(o.snap)pathContains(n,e)?(t=newRelativePath(n,e),r=compoundWriteAddWrite(r,t,o.snap)):pathContains(e,n)&&(t=newRelativePath(e,n),r=compoundWriteAddWrite(r,newEmptyPath(),o.snap.getChild(t)));else{if(!o.children)throw assertionError("WriteRecord should have .snap or .children");if(pathContains(n,e))t=newRelativePath(n,e),r=compoundWriteAddWrites(r,t,o.children);else if(pathContains(e,n))if(t=newRelativePath(e,n),pathIsEmpty(t))r=compoundWriteAddWrites(r,newEmptyPath(),o.children);else{const e=safeGet(o.children,pathGetFront(t));if(e){const n=e.getChild(pathPopFront(t));r=compoundWriteAddWrite(r,newEmptyPath(),n)}}}}}return r}function writeTreeCalcCompleteEventCache(e,t,n,r,i){if(r||i){const o=compoundWriteChildCompoundWrite(e.visibleWrites,t);if(!i&&compoundWriteIsEmpty(o))return n;if(i||null!=n||compoundWriteHasCompleteWrite(o,newEmptyPath())){const filter=function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(pathContains(e.path,t)||pathContains(t,e.path))};return compoundWriteApply(writeTreeLayerTree_(e.allWrites,filter,t),n||ChildrenNode.EMPTY_NODE)}return null}{const r=compoundWriteGetCompleteNode(e.visibleWrites,t);if(null!=r)return r;{const r=compoundWriteChildCompoundWrite(e.visibleWrites,t);if(compoundWriteIsEmpty(r))return n;if(null!=n||compoundWriteHasCompleteWrite(r,newEmptyPath())){return compoundWriteApply(r,n||ChildrenNode.EMPTY_NODE)}return null}}}function writeTreeRefCalcCompleteEventCache(e,t,n,r){return writeTreeCalcCompleteEventCache(e.writeTree,e.treePath,t,n,r)}function writeTreeRefCalcCompleteEventChildren(e,t){return function writeTreeCalcCompleteEventChildren(e,t,n){let r=ChildrenNode.EMPTY_NODE;const i=compoundWriteGetCompleteNode(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(G,((e,t)=>{r=r.updateImmediateChild(e,t)})),r;if(n){const i=compoundWriteChildCompoundWrite(e.visibleWrites,t);return n.forEachChild(G,((e,t)=>{const n=compoundWriteApply(compoundWriteChildCompoundWrite(i,new Path(e)),t);r=r.updateImmediateChild(e,n)})),compoundWriteGetCompleteChildren(i).forEach((e=>{r=r.updateImmediateChild(e.name,e.node)})),r}return compoundWriteGetCompleteChildren(compoundWriteChildCompoundWrite(e.visibleWrites,t)).forEach((e=>{r=r.updateImmediateChild(e.name,e.node)})),r}(e.writeTree,e.treePath,t)}function writeTreeRefCalcEventCacheAfterServerOverwrite(e,t,n,r){return function writeTreeCalcEventCacheAfterServerOverwrite(e,t,n,r,i){assert(r||i,"Either existingEventSnap or existingServerSnap must exist");const o=pathChild(t,n);if(compoundWriteHasCompleteWrite(e.visibleWrites,o))return null;{const t=compoundWriteChildCompoundWrite(e.visibleWrites,o);return compoundWriteIsEmpty(t)?i.getChild(n):compoundWriteApply(t,i.getChild(n))}}(e.writeTree,e.treePath,t,n,r)}function writeTreeRefShadowingWrite(e,t){return function writeTreeShadowingWrite(e,t){return compoundWriteGetCompleteNode(e.visibleWrites,t)}(e.writeTree,pathChild(e.treePath,t))}function writeTreeRefCalcIndexedSlice(e,t,n,r,i,o){return function writeTreeCalcIndexedSlice(e,t,n,r,i,o,s){let a;const l=compoundWriteChildCompoundWrite(e.visibleWrites,t),h=compoundWriteGetCompleteNode(l,newEmptyPath());if(null!=h)a=h;else{if(null==n)return[];a=compoundWriteApply(l,n)}if(a=a.withIndex(s),a.isEmpty()||a.isLeafNode())return[];{const e=[],t=s.getCompare(),n=o?a.getReverseIteratorFrom(r,s):a.getIteratorFrom(r,s);let l=n.getNext();for(;l&&e.length<i;)0!==t(l,r)&&e.push(l),l=n.getNext();return e}}(e.writeTree,e.treePath,t,n,r,i,o)}function writeTreeRefCalcCompleteChild(e,t,n){return function writeTreeCalcCompleteChild(e,t,n,r){const i=pathChild(t,n),o=compoundWriteGetCompleteNode(e.visibleWrites,i);if(null!=o)return o;if(r.isCompleteForChild(n))return compoundWriteApply(compoundWriteChildCompoundWrite(e.visibleWrites,i),r.getNode().getImmediateChild(n));return null}(e.writeTree,e.treePath,t,n)}function writeTreeRefChild(e,t){return newWriteTreeRef(pathChild(e.treePath,t),e.writeTree)}function newWriteTreeRef(e,t){return{treePath:e,writeTree:t}}class ChildChangeAccumulator{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,n=e.childName;assert("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),assert(".priority"!==n,"Only non-priority child changes can be tracked.");const r=this.changeMap.get(n);if(r){const i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,changeChildChanged(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,changeChildRemoved(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,changeChildAdded(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw assertionError("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,changeChildChanged(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const Y=new class NoCompleteChildSource_{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class WriteTreeCompleteChildSource{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{const t=null!=this.optCompleteServerCache_?new CacheNode(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return writeTreeRefCalcCompleteChild(this.writes_,e,t)}}getChildAfterChild(e,t,n){const r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:viewCacheGetCompleteServerSnap(this.viewCache_),i=writeTreeRefCalcIndexedSlice(this.writes_,r,t,1,n,e);return 0===i.length?null:i[0]}}function viewProcessorApplyOperation(e,t,n,r,i){const o=new ChildChangeAccumulator;let s,a;if(n.type===z.OVERWRITE){const l=n;l.source.fromUser?s=viewProcessorApplyUserOverwrite(e,t,l.path,l.snap,r,i,o):(assert(l.source.fromServer,"Unknown source."),a=l.source.tagged||t.serverCache.isFiltered()&&!pathIsEmpty(l.path),s=viewProcessorApplyServerOverwrite(e,t,l.path,l.snap,r,i,a,o))}else if(n.type===z.MERGE){const l=n;l.source.fromUser?s=function viewProcessorApplyUserMerge(e,t,n,r,i,o,s){let a=t;return r.foreach(((r,l)=>{const h=pathChild(n,r);viewProcessorCacheHasChild(t,pathGetFront(h))&&(a=viewProcessorApplyUserOverwrite(e,a,h,l,i,o,s))})),r.foreach(((r,l)=>{const h=pathChild(n,r);viewProcessorCacheHasChild(t,pathGetFront(h))||(a=viewProcessorApplyUserOverwrite(e,a,h,l,i,o,s))})),a}(e,t,l.path,l.children,r,i,o):(assert(l.source.fromServer,"Unknown source."),a=l.source.tagged||t.serverCache.isFiltered(),s=viewProcessorApplyServerMerge(e,t,l.path,l.children,r,i,a,o))}else if(n.type===z.ACK_USER_WRITE){const a=n;s=a.revert?function viewProcessorRevertUserWrite(e,t,n,r,i,o){let s;if(null!=writeTreeRefShadowingWrite(r,n))return t;{const a=new WriteTreeCompleteChildSource(r,t,i),l=t.eventCache.getNode();let h;if(pathIsEmpty(n)||".priority"===pathGetFront(n)){let n;if(t.serverCache.isFullyInitialized())n=writeTreeRefCalcCompleteEventCache(r,viewCacheGetCompleteServerSnap(t));else{const e=t.serverCache.getNode();assert(e instanceof ChildrenNode,"serverChildren would be complete if leaf node"),n=writeTreeRefCalcCompleteEventChildren(r,e)}h=e.filter.updateFullNode(l,n,o)}else{const i=pathGetFront(n);let c=writeTreeRefCalcCompleteChild(r,i,t.serverCache);null==c&&t.serverCache.isCompleteForChild(i)&&(c=l.getImmediateChild(i)),h=null!=c?e.filter.updateChild(l,i,c,pathPopFront(n),a,o):t.eventCache.getNode().hasChild(i)?e.filter.updateChild(l,i,ChildrenNode.EMPTY_NODE,pathPopFront(n),a,o):l,h.isEmpty()&&t.serverCache.isFullyInitialized()&&(s=writeTreeRefCalcCompleteEventCache(r,viewCacheGetCompleteServerSnap(t)),s.isLeafNode()&&(h=e.filter.updateFullNode(h,s,o)))}return s=t.serverCache.isFullyInitialized()||null!=writeTreeRefShadowingWrite(r,newEmptyPath()),viewCacheUpdateEventSnap(t,h,s,e.filter.filtersNodes())}}(e,t,a.path,r,i,o):function viewProcessorAckUserWrite(e,t,n,r,i,o,s){if(null!=writeTreeRefShadowingWrite(i,n))return t;const a=t.serverCache.isFiltered(),l=t.serverCache;if(null!=r.value){if(pathIsEmpty(n)&&l.isFullyInitialized()||l.isCompleteForPath(n))return viewProcessorApplyServerOverwrite(e,t,n,l.getNode().getChild(n),i,o,a,s);if(pathIsEmpty(n)){let r=new ImmutableTree(null);return l.getNode().forEachChild(D,((e,t)=>{r=r.set(new Path(e),t)})),viewProcessorApplyServerMerge(e,t,n,r,i,o,a,s)}return t}{let h=new ImmutableTree(null);return r.foreach(((e,t)=>{const r=pathChild(n,e);l.isCompleteForPath(r)&&(h=h.set(e,l.getNode().getChild(r)))})),viewProcessorApplyServerMerge(e,t,n,h,i,o,a,s)}}(e,t,a.path,a.affectedTree,r,i,o)}else{if(n.type!==z.LISTEN_COMPLETE)throw assertionError("Unknown operation type: "+n.type);s=function viewProcessorListenComplete(e,t,n,r,i){const o=t.serverCache,s=viewCacheUpdateServerSnap(t,o.getNode(),o.isFullyInitialized()||pathIsEmpty(n),o.isFiltered());return viewProcessorGenerateEventCacheAfterServerEvent(e,s,n,r,Y,i)}(e,t,n.path,r,o)}const l=o.getChanges();return function viewProcessorMaybeAddValueEvent(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){const i=r.getNode().isLeafNode()||r.getNode().isEmpty(),o=viewCacheGetCompleteEventSnap(e);(n.length>0||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(o)||!r.getNode().getPriority().equals(o.getPriority()))&&n.push(changeValue(viewCacheGetCompleteEventSnap(t)))}}(t,s,l),{viewCache:s,changes:l}}function viewProcessorGenerateEventCacheAfterServerEvent(e,t,n,r,i,o){const s=t.eventCache;if(null!=writeTreeRefShadowingWrite(r,n))return t;{let a,l;if(pathIsEmpty(n))if(assert(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t.serverCache.isFiltered()){const n=viewCacheGetCompleteServerSnap(t),i=writeTreeRefCalcCompleteEventChildren(r,n instanceof ChildrenNode?n:ChildrenNode.EMPTY_NODE);a=e.filter.updateFullNode(t.eventCache.getNode(),i,o)}else{const n=writeTreeRefCalcCompleteEventCache(r,viewCacheGetCompleteServerSnap(t));a=e.filter.updateFullNode(t.eventCache.getNode(),n,o)}else{const h=pathGetFront(n);if(".priority"===h){assert(1===pathGetLength(n),"Can't have a priority with additional path components");const i=s.getNode();l=t.serverCache.getNode();const o=writeTreeRefCalcEventCacheAfterServerOverwrite(r,n,i,l);a=null!=o?e.filter.updatePriority(i,o):s.getNode()}else{const c=pathPopFront(n);let d;if(s.isCompleteForChild(h)){l=t.serverCache.getNode();const e=writeTreeRefCalcEventCacheAfterServerOverwrite(r,n,s.getNode(),l);d=null!=e?s.getNode().getImmediateChild(h).updateChild(c,e):s.getNode().getImmediateChild(h)}else d=writeTreeRefCalcCompleteChild(r,h,t.serverCache);a=null!=d?e.filter.updateChild(s.getNode(),h,d,c,i,o):s.getNode()}}return viewCacheUpdateEventSnap(t,a,s.isFullyInitialized()||pathIsEmpty(n),e.filter.filtersNodes())}}function viewProcessorApplyServerOverwrite(e,t,n,r,i,o,s,a){const l=t.serverCache;let h;const c=s?e.filter:e.filter.getIndexedFilter();if(pathIsEmpty(n))h=c.updateFullNode(l.getNode(),r,null);else if(c.filtersNodes()&&!l.isFiltered()){const e=l.getNode().updateChild(n,r);h=c.updateFullNode(l.getNode(),e,null)}else{const e=pathGetFront(n);if(!l.isCompleteForPath(n)&&pathGetLength(n)>1)return t;const i=pathPopFront(n),o=l.getNode().getImmediateChild(e).updateChild(i,r);h=".priority"===e?c.updatePriority(l.getNode(),o):c.updateChild(l.getNode(),e,o,i,Y,null)}const d=viewCacheUpdateServerSnap(t,h,l.isFullyInitialized()||pathIsEmpty(n),c.filtersNodes());return viewProcessorGenerateEventCacheAfterServerEvent(e,d,n,i,new WriteTreeCompleteChildSource(i,d,o),a)}function viewProcessorApplyUserOverwrite(e,t,n,r,i,o,s){const a=t.eventCache;let l,h;const c=new WriteTreeCompleteChildSource(i,t,o);if(pathIsEmpty(n))h=e.filter.updateFullNode(t.eventCache.getNode(),r,s),l=viewCacheUpdateEventSnap(t,h,!0,e.filter.filtersNodes());else{const i=pathGetFront(n);if(".priority"===i)h=e.filter.updatePriority(t.eventCache.getNode(),r),l=viewCacheUpdateEventSnap(t,h,a.isFullyInitialized(),a.isFiltered());else{const o=pathPopFront(n),h=a.getNode().getImmediateChild(i);let d;if(pathIsEmpty(o))d=r;else{const e=c.getCompleteChild(i);d=null!=e?".priority"===pathGetBack(o)&&e.getChild(pathParent(o)).isEmpty()?e:e.updateChild(o,r):ChildrenNode.EMPTY_NODE}if(h.equals(d))l=t;else{l=viewCacheUpdateEventSnap(t,e.filter.updateChild(a.getNode(),i,d,o,c,s),a.isFullyInitialized(),e.filter.filtersNodes())}}}return l}function viewProcessorCacheHasChild(e,t){return e.eventCache.isCompleteForChild(t)}function viewProcessorApplyMerge(e,t,n){return n.foreach(((e,n)=>{t=t.updateChild(e,n)})),t}function viewProcessorApplyServerMerge(e,t,n,r,i,o,s,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let l,h=t;l=pathIsEmpty(n)?r:new ImmutableTree(null).setTree(n,r);const c=t.serverCache.getNode();return l.children.inorderTraversal(((n,r)=>{if(c.hasChild(n)){const l=viewProcessorApplyMerge(0,t.serverCache.getNode().getImmediateChild(n),r);h=viewProcessorApplyServerOverwrite(e,h,new Path(n),l,i,o,s,a)}})),l.children.inorderTraversal(((n,r)=>{const l=!t.serverCache.isCompleteForChild(n)&&null===r.value;if(!c.hasChild(n)&&!l){const l=viewProcessorApplyMerge(0,t.serverCache.getNode().getImmediateChild(n),r);h=viewProcessorApplyServerOverwrite(e,h,new Path(n),l,i,o,s,a)}})),h}class View{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new IndexedFilter(n.getIndex()),i=function queryParamsGetNodeFilter(e){return e.loadsAllData()?new IndexedFilter(e.getIndex()):e.hasLimit()?new LimitedFilter(e):new RangedFilter(e)}(n);this.processor_=function newViewProcessor(e){return{filter:e}}(i);const o=t.serverCache,s=t.eventCache,a=r.updateFullNode(ChildrenNode.EMPTY_NODE,o.getNode(),null),l=i.updateFullNode(ChildrenNode.EMPTY_NODE,s.getNode(),null),h=new CacheNode(a,o.isFullyInitialized(),r.filtersNodes()),c=new CacheNode(l,s.isFullyInitialized(),i.filtersNodes());this.viewCache_=newViewCache(c,h),this.eventGenerator_=new EventGenerator(this.query_)}get query(){return this.query_}}function viewGetCompleteServerCache(e,t){const n=viewCacheGetCompleteServerSnap(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!pathIsEmpty(t)&&!n.getImmediateChild(pathGetFront(t)).isEmpty())?n.getChild(t):null}function viewIsEmpty(e){return 0===e.eventRegistrations_.length}function viewRemoveEventRegistration(e,t,n){const r=[];if(n){assert(null==t,"A cancel should cancel all event registrations.");const i=e.query._path;e.eventRegistrations_.forEach((e=>{const t=e.createCancelEvent(n,i);t&&r.push(t)}))}if(t){let n=[];for(let r=0;r<e.eventRegistrations_.length;++r){const i=e.eventRegistrations_[r];if(i.matches(t)){if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(r+1));break}}else n.push(i)}e.eventRegistrations_=n}else e.eventRegistrations_=[];return r}function viewApplyOperation(e,t,n,r){t.type===z.MERGE&&null!==t.source.queryId&&(assert(viewCacheGetCompleteServerSnap(e.viewCache_),"We should always have a full cache before handling merges"),assert(viewCacheGetCompleteEventSnap(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,o=viewProcessorApplyOperation(e.processor_,i,t,n,r);return function viewProcessorAssertIndexed(e,t){assert(t.eventCache.getNode().isIndexed(e.filter.getIndex()),"Event snap not indexed"),assert(t.serverCache.getNode().isIndexed(e.filter.getIndex()),"Server snap not indexed")}(e.processor_,o.viewCache),assert(o.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=o.viewCache,viewGenerateEventsForChanges_(e,o.changes,o.viewCache.eventCache.getNode(),null)}function viewGenerateEventsForChanges_(e,t,n,r){const i=r?[r]:e.eventRegistrations_;return function eventGeneratorGenerateEventsForChanges(e,t,n,r){const i=[],o=[];return t.forEach((t=>{"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&o.push(function changeChildMoved(e,t){return{type:"child_moved",snapshotNode:t,childName:e}}(t.childName,t.snapshotNode))})),eventGeneratorGenerateEventsForType(e,i,"child_removed",t,r,n),eventGeneratorGenerateEventsForType(e,i,"child_added",t,r,n),eventGeneratorGenerateEventsForType(e,i,"child_moved",o,r,n),eventGeneratorGenerateEventsForType(e,i,"child_changed",t,r,n),eventGeneratorGenerateEventsForType(e,i,"value",t,r,n),i}(e.eventGenerator_,t,n,i)}let $,J;class SyncPoint{constructor(){this.views=new Map}}function syncPointApplyOperation(e,t,n,r){const i=t.source.queryId;if(null!==i){const o=e.views.get(i);return assert(null!=o,"SyncTree gave us an op for an invalid query."),viewApplyOperation(o,t,n,r)}{let i=[];for(const o of e.views.values())i=i.concat(viewApplyOperation(o,t,n,r));return i}}function syncPointGetView(e,t,n,r,i){const o=t._queryIdentifier,s=e.views.get(o);if(!s){let e=writeTreeRefCalcCompleteEventCache(n,i?r:null),o=!1;e?o=!0:r instanceof ChildrenNode?(e=writeTreeRefCalcCompleteEventChildren(n,r),o=!1):(e=ChildrenNode.EMPTY_NODE,o=!1);const s=newViewCache(new CacheNode(e,o,!1),new CacheNode(r,i,!1));return new View(t,s)}return s}function syncPointAddEventRegistration(e,t,n,r,i,o){const s=syncPointGetView(e,t,r,i,o);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,s),function viewAddEventRegistration(e,t){e.eventRegistrations_.push(t)}(s,n),function viewGetInitialEvents(e,t){const n=e.viewCache_.eventCache,r=[];n.getNode().isLeafNode()||n.getNode().forEachChild(G,((e,t)=>{r.push(changeChildAdded(e,t))}));return n.isFullyInitialized()&&r.push(changeValue(n.getNode())),viewGenerateEventsForChanges_(e,r,n.getNode(),t)}(s,n)}function syncPointRemoveEventRegistration(e,t,n,r){const i=t._queryIdentifier,o=[];let s=[];const a=syncPointHasCompleteView(e);if("default"===i)for(const[t,i]of e.views.entries())s=s.concat(viewRemoveEventRegistration(i,n,r)),viewIsEmpty(i)&&(e.views.delete(t),i.query._queryParams.loadsAllData()||o.push(i.query));else{const t=e.views.get(i);t&&(s=s.concat(viewRemoveEventRegistration(t,n,r)),viewIsEmpty(t)&&(e.views.delete(i),t.query._queryParams.loadsAllData()||o.push(t.query)))}return a&&!syncPointHasCompleteView(e)&&o.push(new(function syncPointGetReferenceConstructor(){return assert($,"Reference.ts has not been loaded"),$}())(t._repo,t._path)),{removed:o,events:s}}function syncPointGetQueryViews(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function syncPointGetCompleteServerCache(e,t){let n=null;for(const r of e.views.values())n=n||viewGetCompleteServerCache(r,t);return n}function syncPointViewForQuery(e,t){if(t._queryParams.loadsAllData())return syncPointGetCompleteView(e);{const n=t._queryIdentifier;return e.views.get(n)}}function syncPointViewExistsForQuery(e,t){return null!=syncPointViewForQuery(e,t)}function syncPointHasCompleteView(e){return null!=syncPointGetCompleteView(e)}function syncPointGetCompleteView(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let X=1;class SyncTree{constructor(e){this.listenProvider_=e,this.syncPointTree_=new ImmutableTree(null),this.pendingWriteTree_=function newWriteTree(){return{visibleWrites:CompoundWrite.empty(),allWrites:[],lastWriteId:-1}}(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function syncTreeApplyUserOverwrite(e,t,n,r,i){return function writeTreeAddOverwrite(e,t,n,r,i){assert(r>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===i&&(i=!0),e.allWrites.push({path:t,snap:n,writeId:r,visible:i}),i&&(e.visibleWrites=compoundWriteAddWrite(e.visibleWrites,t,n)),e.lastWriteId=r}(e.pendingWriteTree_,t,n,r,i),i?syncTreeApplyOperationToSyncPoints_(e,new Overwrite({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,n)):[]}function syncTreeApplyUserMerge(e,t,n,r){!function writeTreeAddMerge(e,t,n,r){assert(r>e.lastWriteId,"Stacking an older merge on top of newer ones"),e.allWrites.push({path:t,children:n,writeId:r,visible:!0}),e.visibleWrites=compoundWriteAddWrites(e.visibleWrites,t,n),e.lastWriteId=r}(e.pendingWriteTree_,t,n,r);const i=ImmutableTree.fromObject(n);return syncTreeApplyOperationToSyncPoints_(e,new Merge({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,i))}function syncTreeAckUserWrite(e,t,n=!1){const r=function writeTreeGetWrite(e,t){for(let n=0;n<e.allWrites.length;n++){const r=e.allWrites[n];if(r.writeId===t)return r}return null}(e.pendingWriteTree_,t);if(writeTreeRemoveWrite(e.pendingWriteTree_,t)){let t=new ImmutableTree(null);return null!=r.snap?t=t.set(newEmptyPath(),!0):each(r.children,(e=>{t=t.set(new Path(e),!0)})),syncTreeApplyOperationToSyncPoints_(e,new AckUserWrite(r.path,t,n))}return[]}function syncTreeApplyServerOverwrite(e,t,n){return syncTreeApplyOperationToSyncPoints_(e,new Overwrite({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,n))}function syncTreeRemoveEventRegistration(e,t,n,r,i=!1){const o=t._path,s=e.syncPointTree_.get(o);let a=[];if(s&&("default"===t._queryIdentifier||syncPointViewExistsForQuery(s,t))){const l=syncPointRemoveEventRegistration(s,t,n,r);(function syncPointIsEmpty(e){return 0===e.views.size})(s)&&(e.syncPointTree_=e.syncPointTree_.remove(o));const h=l.removed;if(a=l.events,!i){const n=-1!==h.findIndex((e=>e._queryParams.loadsAllData())),i=e.syncPointTree_.findOnPath(o,((e,t)=>syncPointHasCompleteView(t)));if(n&&!i){const t=e.syncPointTree_.subtree(o);if(!t.isEmpty()){const n=function syncTreeCollectDistinctViewsForSubTree_(e){return e.fold(((e,t,n)=>{if(t&&syncPointHasCompleteView(t)){return[syncPointGetCompleteView(t)]}{let e=[];return t&&(e=syncPointGetQueryViews(t)),each(n,((t,n)=>{e=e.concat(n)})),e}}))}(t);for(let t=0;t<n.length;++t){const r=n[t],i=r.query,o=syncTreeCreateListenerForView_(e,r);e.listenProvider_.startListening(syncTreeQueryForListening_(i),syncTreeTagForQuery(e,i),o.hashFn,o.onComplete)}}}if(!i&&h.length>0&&!r)if(n){const n=null;e.listenProvider_.stopListening(syncTreeQueryForListening_(t),n)}else h.forEach((t=>{const n=e.queryToTagMap.get(syncTreeMakeQueryKey_(t));e.listenProvider_.stopListening(syncTreeQueryForListening_(t),n)}))}!function syncTreeRemoveTags_(e,t){for(let n=0;n<t.length;++n){const r=t[n];if(!r._queryParams.loadsAllData()){const t=syncTreeMakeQueryKey_(r),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}(e,h)}return a}function syncTreeApplyTaggedQueryOverwrite(e,t,n,r){const i=syncTreeQueryKeyForTag_(e,r);if(null!=i){const r=syncTreeParseQueryKey_(i),o=r.path,s=r.queryId,a=newRelativePath(o,t);return syncTreeApplyTaggedOperation_(e,o,new Overwrite(newOperationSourceServerTaggedQuery(s),a,n))}return[]}function syncTreeAddEventRegistration(e,t,n,r=!1){const i=t._path;let o=null,s=!1;e.syncPointTree_.foreachOnPath(i,((e,t)=>{const n=newRelativePath(e,i);o=o||syncPointGetCompleteServerCache(t,n),s=s||syncPointHasCompleteView(t)}));let a,l=e.syncPointTree_.get(i);if(l?(s=s||syncPointHasCompleteView(l),o=o||syncPointGetCompleteServerCache(l,newEmptyPath())):(l=new SyncPoint,e.syncPointTree_=e.syncPointTree_.set(i,l)),null!=o)a=!0;else{a=!1,o=ChildrenNode.EMPTY_NODE;e.syncPointTree_.subtree(i).foreachChild(((e,t)=>{const n=syncPointGetCompleteServerCache(t,newEmptyPath());n&&(o=o.updateImmediateChild(e,n))}))}const h=syncPointViewExistsForQuery(l,t);if(!h&&!t._queryParams.loadsAllData()){const n=syncTreeMakeQueryKey_(t);assert(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");const r=function syncTreeGetNextQueryTag_(){return X++}();e.queryToTagMap.set(n,r),e.tagToQueryMap.set(r,n)}let c=syncPointAddEventRegistration(l,t,n,writeTreeChildWrites(e.pendingWriteTree_,i),o,a);if(!h&&!s&&!r){const n=syncPointViewForQuery(l,t);c=c.concat(function syncTreeSetupListener_(e,t,n){const r=t._path,i=syncTreeTagForQuery(e,t),o=syncTreeCreateListenerForView_(e,n),s=e.listenProvider_.startListening(syncTreeQueryForListening_(t),i,o.hashFn,o.onComplete),a=e.syncPointTree_.subtree(r);if(i)assert(!syncPointHasCompleteView(a.value),"If we're adding a query, it shouldn't be shadowed");else{const t=a.fold(((e,t,n)=>{if(!pathIsEmpty(e)&&t&&syncPointHasCompleteView(t))return[syncPointGetCompleteView(t).query];{let e=[];return t&&(e=e.concat(syncPointGetQueryViews(t).map((e=>e.query)))),each(n,((t,n)=>{e=e.concat(n)})),e}}));for(let n=0;n<t.length;++n){const r=t[n];e.listenProvider_.stopListening(syncTreeQueryForListening_(r),syncTreeTagForQuery(e,r))}}return s}(e,t,n))}return c}function syncTreeCalcCompleteEventCache(e,t,n){const r=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(t,((e,n)=>{const r=syncPointGetCompleteServerCache(n,newRelativePath(e,t));if(r)return r}));return writeTreeCalcCompleteEventCache(r,t,i,n,!0)}function syncTreeGetServerValue(e,t){const n=t._path;let r=null;e.syncPointTree_.foreachOnPath(n,((e,t)=>{const i=newRelativePath(e,n);r=r||syncPointGetCompleteServerCache(t,i)}));let i=e.syncPointTree_.get(n);i?r=r||syncPointGetCompleteServerCache(i,newEmptyPath()):(i=new SyncPoint,e.syncPointTree_=e.syncPointTree_.set(n,i));const o=null!=r,s=o?new CacheNode(r,!0,!1):null;return function viewGetCompleteNode(e){return viewCacheGetCompleteEventSnap(e.viewCache_)}(syncPointGetView(i,t,writeTreeChildWrites(e.pendingWriteTree_,t._path),o?s.getNode():ChildrenNode.EMPTY_NODE,o))}function syncTreeApplyOperationToSyncPoints_(e,t){return syncTreeApplyOperationHelper_(t,e.syncPointTree_,null,writeTreeChildWrites(e.pendingWriteTree_,newEmptyPath()))}function syncTreeApplyOperationHelper_(e,t,n,r){if(pathIsEmpty(e.path))return syncTreeApplyOperationDescendantsHelper_(e,t,n,r);{const i=t.get(newEmptyPath());null==n&&null!=i&&(n=syncPointGetCompleteServerCache(i,newEmptyPath()));let o=[];const s=pathGetFront(e.path),a=e.operationForChild(s),l=t.children.get(s);if(l&&a){const e=n?n.getImmediateChild(s):null,t=writeTreeRefChild(r,s);o=o.concat(syncTreeApplyOperationHelper_(a,l,e,t))}return i&&(o=o.concat(syncPointApplyOperation(i,e,r,n))),o}}function syncTreeApplyOperationDescendantsHelper_(e,t,n,r){const i=t.get(newEmptyPath());null==n&&null!=i&&(n=syncPointGetCompleteServerCache(i,newEmptyPath()));let o=[];return t.children.inorderTraversal(((t,i)=>{const s=n?n.getImmediateChild(t):null,a=writeTreeRefChild(r,t),l=e.operationForChild(t);l&&(o=o.concat(syncTreeApplyOperationDescendantsHelper_(l,i,s,a)))})),i&&(o=o.concat(syncPointApplyOperation(i,e,r,n))),o}function syncTreeCreateListenerForView_(e,t){const n=t.query,r=syncTreeTagForQuery(e,n);return{hashFn:()=>{const e=function viewGetServerCache(e){return e.viewCache_.serverCache.getNode()}(t)||ChildrenNode.EMPTY_NODE;return e.hash()},onComplete:t=>{if("ok"===t)return r?function syncTreeApplyTaggedListenComplete(e,t,n){const r=syncTreeQueryKeyForTag_(e,n);if(r){const n=syncTreeParseQueryKey_(r),i=n.path,o=n.queryId,s=newRelativePath(i,t);return syncTreeApplyTaggedOperation_(e,i,new ListenComplete(newOperationSourceServerTaggedQuery(o),s))}return[]}(e,n._path,r):function syncTreeApplyListenComplete(e,t){return syncTreeApplyOperationToSyncPoints_(e,new ListenComplete({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t))}(e,n._path);{const r=function errorForServerCode(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r}(t,n);return syncTreeRemoveEventRegistration(e,n,null,r)}}}}function syncTreeTagForQuery(e,t){const n=syncTreeMakeQueryKey_(t);return e.queryToTagMap.get(n)}function syncTreeMakeQueryKey_(e){return e._path.toString()+"$"+e._queryIdentifier}function syncTreeQueryKeyForTag_(e,t){return e.tagToQueryMap.get(t)}function syncTreeParseQueryKey_(e){const t=e.indexOf("$");return assert(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new Path(e.substr(0,t))}}function syncTreeApplyTaggedOperation_(e,t,n){const r=e.syncPointTree_.get(t);assert(r,"Missing sync point for query tag that we're tracking");return syncPointApplyOperation(r,n,writeTreeChildWrites(e.pendingWriteTree_,t),null)}function syncTreeQueryForListening_(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new(function syncTreeGetReferenceConstructor(){return assert(J,"Reference.ts has not been loaded"),J}())(e._repo,e._path):e}class ExistingValueProvider{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new ExistingValueProvider(t)}node(){return this.node_}}class DeferredValueProvider{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){const t=pathChild(this.path_,e);return new DeferredValueProvider(this.syncTree_,t)}node(){return syncTreeCalcCompleteEventCache(this.syncTree_,this.path_)}}const resolveDeferredLeafValue=function(e,t,n){return e&&"object"==typeof e?(assert(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?resolveScalarDeferredValue(e[".sv"],t,n):"object"==typeof e[".sv"]?resolveComplexDeferredValue(e[".sv"],t):void assert(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},resolveScalarDeferredValue=function(e,t,n){if("timestamp"===e)return n.timestamp;assert(!1,"Unexpected server value: "+e)},resolveComplexDeferredValue=function(e,t,n){e.hasOwnProperty("increment")||assert(!1,"Unexpected server value: "+JSON.stringify(e,null,2));const r=e.increment;"number"!=typeof r&&assert(!1,"Unexpected increment value: "+r);const i=t.node();if(assert(null!=i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;const o=i.getValue();return"number"!=typeof o?r:o+r},resolveDeferredValueTree=function(e,t,n,r){return resolveDeferredValue(t,new DeferredValueProvider(n,e),r)},resolveDeferredValueSnapshot=function(e,t,n){return resolveDeferredValue(e,new ExistingValueProvider(t),n)};function resolveDeferredValue(e,t,n){const r=e.getPriority().val(),i=resolveDeferredLeafValue(r,t.getImmediateChild(".priority"),n);let o;if(e.isLeafNode()){const r=e,o=resolveDeferredLeafValue(r.getValue(),t,n);return o!==r.getValue()||i!==r.getPriority().val()?new LeafNode(o,nodeFromJSON(i)):e}{const r=e;return o=r,i!==r.getPriority().val()&&(o=o.updatePriority(new LeafNode(i))),r.forEachChild(G,((e,r)=>{const i=resolveDeferredValue(r,t.getImmediateChild(e),n);i!==r&&(o=o.updateImmediateChild(e,i))})),o}}class Tree{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function treeSubTree(e,t){let n=t instanceof Path?t:new Path(t),r=e,i=pathGetFront(n);for(;null!==i;){const e=safeGet(r.node.children,i)||{children:{},childCount:0};r=new Tree(i,r,e),n=pathPopFront(n),i=pathGetFront(n)}return r}function treeGetValue(e){return e.node.value}function treeSetValue(e,t){e.node.value=t,treeUpdateParents(e)}function treeHasChildren(e){return e.node.childCount>0}function treeForEachChild(e,t){each(e.node.children,((n,r)=>{t(new Tree(n,e,r))}))}function treeForEachDescendant(e,t,n,r){n&&!r&&t(e),treeForEachChild(e,(e=>{treeForEachDescendant(e,t,!0,r)})),n&&r&&t(e)}function treeGetPath(e){return new Path(null===e.parent?e.name:treeGetPath(e.parent)+"/"+e.name)}function treeUpdateParents(e){null!==e.parent&&function treeUpdateChild(e,t,n){const r=function treeIsEmpty(e){return void 0===treeGetValue(e)&&!treeHasChildren(e)}(n),i=contains(e.node.children,t);r&&i?(delete e.node.children[t],e.node.childCount--,treeUpdateParents(e)):r||i||(e.node.children[t]=n.node,e.node.childCount++,treeUpdateParents(e))}(e.parent,e.name,e)}const Z=/[\[\].#$\/\u0000-\u001F\u007F]/,ee=/[\[\].#$\u0000-\u001F\u007F]/,te=10485760,isValidKey=function(e){return"string"==typeof e&&0!==e.length&&!Z.test(e)},isValidPathString=function(e){return"string"==typeof e&&0!==e.length&&!ee.test(e)},isValidPriority=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!isInvalidJSONNumber(e)||e&&"object"==typeof e&&contains(e,".sv")},validateFirebaseDataArg=function(e,t,n,r){r&&void 0===t||validateFirebaseData(errorPrefix(e,"value"),t,n)},validateFirebaseData=function(e,t,n){const r=n instanceof Path?new ValidationPath(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+validationPathToErrorString(r));if("function"==typeof t)throw new Error(e+"contains a function "+validationPathToErrorString(r)+" with contents = "+t.toString());if(isInvalidJSONNumber(t))throw new Error(e+"contains "+t.toString()+" "+validationPathToErrorString(r));if("string"==typeof t&&t.length>te/3&&stringLength(t)>te)throw new Error(e+"contains a string greater than "+te+" utf8 bytes "+validationPathToErrorString(r)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,i=!1;if(each(t,((t,o)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(i=!0,!isValidKey(t)))throw new Error(e+" contains an invalid key ("+t+") "+validationPathToErrorString(r)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');!function validationPathPush(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=stringLength(t),validationPathCheckValid(e)}(r,t),validateFirebaseData(e,o,r),function validationPathPop(e){const t=e.parts_.pop();e.byteLength_-=stringLength(t),e.parts_.length>0&&(e.byteLength_-=1)}(r)})),n&&i)throw new Error(e+' contains ".value" child '+validationPathToErrorString(r)+" in addition to actual children.")}},validateFirebaseMergeDataArg=function(e,t,n,r){if(r&&void 0===t)return;const i=errorPrefix(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");const o=[];each(t,((e,t)=>{const r=new Path(e);if(validateFirebaseData(i,t,pathChild(n,r)),".priority"===pathGetBack(r)&&!isValidPriority(t))throw new Error(i+"contains an invalid value for '"+r.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");o.push(r)})),function(e,t){let n,r;for(n=0;n<t.length;n++){r=t[n];const i=pathSlice(r);for(let t=0;t<i.length;t++)if(".priority"===i[t]&&t===i.length-1);else if(!isValidKey(i[t]))throw new Error(e+"contains an invalid key ("+i[t]+") in path "+r.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}t.sort(pathCompare);let i=null;for(n=0;n<t.length;n++){if(r=t[n],null!==i&&pathContains(i,r))throw new Error(e+"contains a path "+i.toString()+" that is ancestor of another path "+r.toString());i=r}}(i,o)},validatePriority=function(e,t,n){if(!n||void 0!==t){if(isInvalidJSONNumber(t))throw new Error(errorPrefix(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!isValidPriority(t))throw new Error(errorPrefix(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},validateKey=function(e,t,n,r){if(!(r&&void 0===n||isValidKey(n)))throw new Error(errorPrefix(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},validatePathString=function(e,t,n,r){if(!(r&&void 0===n||isValidPathString(n)))throw new Error(errorPrefix(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},validateWritablePath=function(e,t){if(".info"===pathGetFront(t))throw new Error(e+" failed = Can't modify data under /.info/")},validateUrl=function(e,t){const n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!isValidKey(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),isValidPathString(e)}(n))throw new Error(errorPrefix(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class EventQueue{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function eventQueueQueueEvents(e,t){let n=null;for(let r=0;r<t.length;r++){const i=t[r],o=i.getPath();null===n||pathEquals(o,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:o}),n.events.push(i)}n&&e.eventLists_.push(n)}function eventQueueRaiseEventsAtPath(e,t,n){eventQueueQueueEvents(e,n),eventQueueRaiseQueuedEventsMatchingPredicate(e,(e=>pathEquals(e,t)))}function eventQueueRaiseEventsForChangedPath(e,t,n){eventQueueQueueEvents(e,n),eventQueueRaiseQueuedEventsMatchingPredicate(e,(e=>pathContains(e,t)||pathContains(t,e)))}function eventQueueRaiseQueuedEventsMatchingPredicate(e,t){e.recursionDepth_++;let n=!0;for(let r=0;r<e.eventLists_.length;r++){const i=e.eventLists_[r];if(i){t(i.path)?(eventListRaise(e.eventLists_[r]),e.eventLists_[r]=null):n=!1}}n&&(e.eventLists_=[]),e.recursionDepth_--}function eventListRaise(e){for(let t=0;t<e.events.length;t++){const n=e.events[t];if(null!==n){e.events[t]=null;const r=n.getEventRunner();C&&log("event: "+n.toString()),exceptionGuard(r)}}}const ne="repo_interrupt";class Repo{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new EventQueue,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=newSparseSnapshotTree(),this.transactionQueueTree_=new Tree,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function repoStart(e,t,n){if(e.stats_=statsManagerGetCollection(e.repoInfo_),e.forceRestClient_||("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0)e.server_=new ReadonlyRestClient(e.repoInfo_,((t,n,r,i)=>{repoOnDataUpdate(e,t,n,r,i)}),e.authTokenProvider_,e.appCheckProvider_),setTimeout((()=>repoOnConnectStatus(e,!0)),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{stringify(n)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new PersistentConnection(e.repoInfo_,t,((t,n,r,i)=>{repoOnDataUpdate(e,t,n,r,i)}),(t=>{repoOnConnectStatus(e,t)}),(t=>{!function repoOnServerInfoUpdate(e,t){each(t,((t,n)=>{repoUpdateInfo(e,t,n)}))}(e,t)}),e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener((t=>{e.server_.refreshAuthToken(t)})),e.appCheckProvider_.addTokenChangeListener((t=>{e.server_.refreshAppCheckToken(t.token)})),e.statsReporter_=function statsManagerGetOrCreateReporter(e,t){const n=e.toString();return k[n]||(k[n]=t()),k[n]}(e.repoInfo_,(()=>new StatsReporter(e.stats_,e.server_))),e.infoData_=new SnapshotHolder,e.infoSyncTree_=new SyncTree({startListening:(t,n,r,i)=>{let o=[];const s=e.infoData_.getNode(t._path);return s.isEmpty()||(o=syncTreeApplyServerOverwrite(e.infoSyncTree_,t._path,s),setTimeout((()=>{i("ok")}),0)),o},stopListening:()=>{}}),repoUpdateInfo(e,"connected",!1),e.serverSyncTree_=new SyncTree({startListening:(t,n,r,i)=>(e.server_.listen(t,r,n,((n,r)=>{const o=i(n,r);eventQueueRaiseEventsForChangedPath(e.eventQueue_,t._path,o)})),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function repoServerTime(e){const t=e.infoData_.getNode(new Path(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function repoGenerateServerValues(e){return(t=(t={timestamp:repoServerTime(e)})||{}).timestamp=t.timestamp||(new Date).getTime(),t;var t}function repoOnDataUpdate(e,t,n,r,i){e.dataUpdateCount++;const o=new Path(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let s=[];if(i)if(r){const t=map(n,(e=>nodeFromJSON(e)));s=function syncTreeApplyTaggedQueryMerge(e,t,n,r){const i=syncTreeQueryKeyForTag_(e,r);if(i){const r=syncTreeParseQueryKey_(i),o=r.path,s=r.queryId,a=newRelativePath(o,t),l=ImmutableTree.fromObject(n);return syncTreeApplyTaggedOperation_(e,o,new Merge(newOperationSourceServerTaggedQuery(s),a,l))}return[]}(e.serverSyncTree_,o,t,i)}else{const t=nodeFromJSON(n);s=syncTreeApplyTaggedQueryOverwrite(e.serverSyncTree_,o,t,i)}else if(r){const t=map(n,(e=>nodeFromJSON(e)));s=function syncTreeApplyServerMerge(e,t,n){const r=ImmutableTree.fromObject(n);return syncTreeApplyOperationToSyncPoints_(e,new Merge({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,r))}(e.serverSyncTree_,o,t)}else{const t=nodeFromJSON(n);s=syncTreeApplyServerOverwrite(e.serverSyncTree_,o,t)}let a=o;s.length>0&&(a=repoRerunTransactions(e,o)),eventQueueRaiseEventsForChangedPath(e.eventQueue_,a,s)}function repoOnConnectStatus(e,t){repoUpdateInfo(e,"connected",t),!1===t&&function repoRunOnDisconnectEvents(e){repoLog(e,"onDisconnectEvents");const t=repoGenerateServerValues(e),n=newSparseSnapshotTree();sparseSnapshotTreeForEachTree(e.onDisconnect_,newEmptyPath(),((r,i)=>{const o=resolveDeferredValueTree(r,i,e.serverSyncTree_,t);sparseSnapshotTreeRemember(n,r,o)}));let r=[];sparseSnapshotTreeForEachTree(n,newEmptyPath(),((t,n)=>{r=r.concat(syncTreeApplyServerOverwrite(e.serverSyncTree_,t,n));const i=repoAbortTransactions(e,t);repoRerunTransactions(e,i)})),e.onDisconnect_=newSparseSnapshotTree(),eventQueueRaiseEventsForChangedPath(e.eventQueue_,newEmptyPath(),r)}(e)}function repoUpdateInfo(e,t,n){const r=new Path("/.info/"+t),i=nodeFromJSON(n);e.infoData_.updateSnapshot(r,i);const o=syncTreeApplyServerOverwrite(e.infoSyncTree_,r,i);eventQueueRaiseEventsForChangedPath(e.eventQueue_,r,o)}function repoGetNextWriteId(e){return e.nextWriteId_++}function repoSetWithPriority(e,t,n,r,i){repoLog(e,"set",{path:t.toString(),value:n,priority:r});const o=repoGenerateServerValues(e),s=nodeFromJSON(n,r),a=syncTreeCalcCompleteEventCache(e.serverSyncTree_,t),l=resolveDeferredValueSnapshot(s,a,o),h=repoGetNextWriteId(e),c=syncTreeApplyUserOverwrite(e.serverSyncTree_,t,l,h,!0);eventQueueQueueEvents(e.eventQueue_,c),e.server_.put(t.toString(),s.val(!0),((n,r)=>{const o="ok"===n;o||warn("set at "+t+" failed: "+n);const s=syncTreeAckUserWrite(e.serverSyncTree_,h,!o);eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,s),repoCallOnCompleteCallback(e,i,n,r)}));const d=repoAbortTransactions(e,t);repoRerunTransactions(e,d),eventQueueRaiseEventsForChangedPath(e.eventQueue_,d,[])}function repoOnDisconnectCancel(e,t,n){e.server_.onDisconnectCancel(t.toString(),((r,i)=>{"ok"===r&&sparseSnapshotTreeForget(e.onDisconnect_,t),repoCallOnCompleteCallback(e,n,r,i)}))}function repoOnDisconnectSet(e,t,n,r){const i=nodeFromJSON(n);e.server_.onDisconnectPut(t.toString(),i.val(!0),((n,o)=>{"ok"===n&&sparseSnapshotTreeRemember(e.onDisconnect_,t,i),repoCallOnCompleteCallback(e,r,n,o)}))}function repoRemoveEventCallbackForQuery(e,t,n){let r;r=".info"===pathGetFront(t._path)?syncTreeRemoveEventRegistration(e.infoSyncTree_,t,n):syncTreeRemoveEventRegistration(e.serverSyncTree_,t,n),eventQueueRaiseEventsAtPath(e.eventQueue_,t._path,r)}function repoInterrupt(e){e.persistentConnection_&&e.persistentConnection_.interrupt(ne)}function repoLog(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),log(n,...t)}function repoCallOnCompleteCallback(e,t,n,r){t&&exceptionGuard((()=>{if("ok"===n)t(null);else{const e=(n||"error").toUpperCase();let i=e;r&&(i+=": "+r);const o=new Error(i);o.code=e,t(o)}}))}function repoGetLatestState(e,t,n){return syncTreeCalcCompleteEventCache(e.serverSyncTree_,t,n)||ChildrenNode.EMPTY_NODE}function repoSendReadyTransactions(e,t=e.transactionQueueTree_){if(t||repoPruneCompletedTransactionsBelowNode(e,t),treeGetValue(t)){const n=repoBuildTransactionQueue(e,t);assert(n.length>0,"Sending zero length transaction queue");n.every((e=>0===e.status))&&function repoSendTransactionQueue(e,t,n){const r=n.map((e=>e.currentWriteId)),i=repoGetLatestState(e,t,r);let o=i;const s=i.hash();for(let e=0;e<n.length;e++){const r=n[e];assert(0===r.status,"tryToSendTransactionQueue_: items in queue should all be run."),r.status=1,r.retryCount++;const i=newRelativePath(t,r.path);o=o.updateChild(i,r.currentOutputSnapshotRaw)}const a=o.val(!0),l=t;e.server_.put(l.toString(),a,(r=>{repoLog(e,"transaction put response",{path:l.toString(),status:r});let i=[];if("ok"===r){const r=[];for(let t=0;t<n.length;t++)n[t].status=2,i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,n[t].currentWriteId)),n[t].onComplete&&r.push((()=>n[t].onComplete(null,!0,n[t].currentOutputSnapshotResolved))),n[t].unwatcher();repoPruneCompletedTransactionsBelowNode(e,treeSubTree(e.transactionQueueTree_,t)),repoSendReadyTransactions(e,e.transactionQueueTree_),eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,i);for(let e=0;e<r.length;e++)exceptionGuard(r[e])}else{if("datastale"===r)for(let e=0;e<n.length;e++)3===n[e].status?n[e].status=4:n[e].status=0;else{warn("transaction at "+l.toString()+" failed: "+r);for(let e=0;e<n.length;e++)n[e].status=4,n[e].abortReason=r}repoRerunTransactions(e,t)}}),s)}(e,treeGetPath(t),n)}else treeHasChildren(t)&&treeForEachChild(t,(t=>{repoSendReadyTransactions(e,t)}))}function repoRerunTransactions(e,t){const n=repoGetAncestorTransactionNode(e,t),r=treeGetPath(n);return function repoRerunTransactionQueue(e,t,n){if(0===t.length)return;const r=[];let i=[];const o=t.filter((e=>0===e.status)),s=o.map((e=>e.currentWriteId));for(let o=0;o<t.length;o++){const l=t[o],h=newRelativePath(n,l.path);let c,d=!1;if(assert(null!==h,"rerunTransactionsUnderNode_: relativePath should not be null."),4===l.status)d=!0,c=l.abortReason,i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,l.currentWriteId,!0));else if(0===l.status)if(l.retryCount>=25)d=!0,c="maxretry",i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,l.currentWriteId,!0));else{const n=repoGetLatestState(e,l.path,s);l.currentInputSnapshot=n;const r=t[o].update(n.val());if(void 0!==r){validateFirebaseData("transaction failed: Data returned ",r,l.path);let t=nodeFromJSON(r);"object"==typeof r&&null!=r&&contains(r,".priority")||(t=t.updatePriority(n.getPriority()));const o=l.currentWriteId,a=repoGenerateServerValues(e),h=resolveDeferredValueSnapshot(t,n,a);l.currentOutputSnapshotRaw=t,l.currentOutputSnapshotResolved=h,l.currentWriteId=repoGetNextWriteId(e),s.splice(s.indexOf(o),1),i=i.concat(syncTreeApplyUserOverwrite(e.serverSyncTree_,l.path,h,l.currentWriteId,l.applyLocally)),i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,o,!0))}else d=!0,c="nodata",i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,l.currentWriteId,!0))}eventQueueRaiseEventsForChangedPath(e.eventQueue_,n,i),i=[],d&&(t[o].status=2,a=t[o].unwatcher,setTimeout(a,Math.floor(0)),t[o].onComplete&&("nodata"===c?r.push((()=>t[o].onComplete(null,!1,t[o].currentInputSnapshot))):r.push((()=>t[o].onComplete(new Error(c),!1,null)))))}var a;repoPruneCompletedTransactionsBelowNode(e,e.transactionQueueTree_);for(let e=0;e<r.length;e++)exceptionGuard(r[e]);repoSendReadyTransactions(e,e.transactionQueueTree_)}(e,repoBuildTransactionQueue(e,n),r),r}function repoGetAncestorTransactionNode(e,t){let n,r=e.transactionQueueTree_;for(n=pathGetFront(t);null!==n&&void 0===treeGetValue(r);)r=treeSubTree(r,n),n=pathGetFront(t=pathPopFront(t));return r}function repoBuildTransactionQueue(e,t){const n=[];return repoAggregateTransactionQueuesForNode(e,t,n),n.sort(((e,t)=>e.order-t.order)),n}function repoAggregateTransactionQueuesForNode(e,t,n){const r=treeGetValue(t);if(r)for(let e=0;e<r.length;e++)n.push(r[e]);treeForEachChild(t,(t=>{repoAggregateTransactionQueuesForNode(e,t,n)}))}function repoPruneCompletedTransactionsBelowNode(e,t){const n=treeGetValue(t);if(n){let e=0;for(let t=0;t<n.length;t++)2!==n[t].status&&(n[e]=n[t],e++);n.length=e,treeSetValue(t,n.length>0?n:void 0)}treeForEachChild(t,(t=>{repoPruneCompletedTransactionsBelowNode(e,t)}))}function repoAbortTransactions(e,t){const n=treeGetPath(repoGetAncestorTransactionNode(e,t)),r=treeSubTree(e.transactionQueueTree_,t);return function treeForEachAncestor(e,t,n){let r=n?e:e.parent;for(;null!==r;){if(t(r))return!0;r=r.parent}return!1}(r,(t=>{repoAbortTransactionsOnNode(e,t)})),repoAbortTransactionsOnNode(e,r),treeForEachDescendant(r,(t=>{repoAbortTransactionsOnNode(e,t)})),n}function repoAbortTransactionsOnNode(e,t){const n=treeGetValue(t);if(n){const r=[];let i=[],o=-1;for(let t=0;t<n.length;t++)3===n[t].status||(1===n[t].status?(assert(o===t-1,"All SENT items should be at beginning of queue."),o=t,n[t].status=3,n[t].abortReason="set"):(assert(0===n[t].status,"Unexpected transaction status in abort"),n[t].unwatcher(),i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&r.push(n[t].onComplete.bind(null,new Error("set"),!1,null))));-1===o?treeSetValue(t,void 0):n.length=o+1,eventQueueRaiseEventsForChangedPath(e.eventQueue_,treeGetPath(t),i);for(let e=0;e<r.length;e++)exceptionGuard(r[e])}}const parseRepoInfo=function(e,t){const n=parseDatabaseURL(e),r=n.namespace;"firebase.com"===n.domain&&fatal(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||fatal("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&warn("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new RepoInfo(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new Path(n.pathString)}},parseDatabaseURL=function(e){let t="",n="",r="",i="",o="",s=!0,a="https",l=443;if("string"==typeof e){let h=e.indexOf("//");h>=0&&(a=e.substring(0,h-1),e=e.substring(h+2));let c=e.indexOf("/");-1===c&&(c=e.length);let d=e.indexOf("?");-1===d&&(d=e.length),t=e.substring(0,Math.min(c,d)),c<d&&(i=function decodePath(e){let t="";const n=e.split("/");for(let e=0;e<n.length;e++)if(n[e].length>0){let r=n[e];try{r=decodeURIComponent(r.replace(/\+/g," "))}catch(e){}t+="/"+r}return t}(e.substring(c,d)));const u=function decodeQuery(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const r=n.split("=");2===r.length?t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):warn(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,d)));h=t.indexOf(":"),h>=0?(s="https"===a||"wss"===a,l=parseInt(t.substring(h+1),10)):h=t.length;const p=t.slice(0,h);if("localhost"===p.toLowerCase())n="localhost";else if(p.split(".").length<=2)n=p;else{const e=t.indexOf(".");r=t.substring(0,e).toLowerCase(),n=t.substring(e+1),o=r}"ns"in u&&(o=u.ns)}return{host:t,port:l,domain:n,subdomain:r,secure:s,scheme:a,pathString:i,namespace:o}},re="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ie=function(){let e=0;const t=[];return function(n){const r=n===e;let i;e=n;const o=new Array(8);for(i=7;i>=0;i--)o[i]=re.charAt(n%64),n=Math.floor(n/64);assert(0===n,"Cannot push at time == 0");let s=o.join("");if(r){for(i=11;i>=0&&63===t[i];i--)t[i]=0;t[i]++}else for(i=0;i<12;i++)t[i]=Math.floor(64*Math.random());for(i=0;i<12;i++)s+=re.charAt(t[i]);return assert(20===s.length,"nextPushId: Length should be 20."),s}}();class DataEvent{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){const e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+stringify(this.snapshot.exportVal())}}class CancelEvent{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class CallbackContext{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return assert(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class OnDisconnect{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new Deferred;return repoOnDisconnectCancel(this._repo,this._path,e.wrapCallback((()=>{}))),e.promise}remove(){validateWritablePath("OnDisconnect.remove",this._path);const e=new Deferred;return repoOnDisconnectSet(this._repo,this._path,null,e.wrapCallback((()=>{}))),e.promise}set(e){validateWritablePath("OnDisconnect.set",this._path),validateFirebaseDataArg("OnDisconnect.set",e,this._path,!1);const t=new Deferred;return repoOnDisconnectSet(this._repo,this._path,e,t.wrapCallback((()=>{}))),t.promise}setWithPriority(e,t){validateWritablePath("OnDisconnect.setWithPriority",this._path),validateFirebaseDataArg("OnDisconnect.setWithPriority",e,this._path,!1),validatePriority("OnDisconnect.setWithPriority",t,!1);const n=new Deferred;return function repoOnDisconnectSetWithPriority(e,t,n,r,i){const o=nodeFromJSON(n,r);e.server_.onDisconnectPut(t.toString(),o.val(!0),((n,r)=>{"ok"===n&&sparseSnapshotTreeRemember(e.onDisconnect_,t,o),repoCallOnCompleteCallback(0,i,n,r)}))}(this._repo,this._path,e,t,n.wrapCallback((()=>{}))),n.promise}update(e){validateWritablePath("OnDisconnect.update",this._path),validateFirebaseMergeDataArg("OnDisconnect.update",e,this._path,!1);const t=new Deferred;return function repoOnDisconnectUpdate(e,t,n,r){if(isEmpty(n))return log("onDisconnect().update() called with empty data. Don't do anything."),void repoCallOnCompleteCallback(0,r,"ok",void 0);e.server_.onDisconnectMerge(t.toString(),n,((i,o)=>{"ok"===i&&each(n,((n,r)=>{const i=nodeFromJSON(r);sparseSnapshotTreeRemember(e.onDisconnect_,pathChild(t,n),i)})),repoCallOnCompleteCallback(0,r,i,o)}))}(this._repo,this._path,e,t.wrapCallback((()=>{}))),t.promise}}class QueryImpl{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return pathIsEmpty(this._path)?null:pathGetBack(this._path)}get ref(){return new ReferenceImpl(this._repo,this._path)}get _queryIdentifier(){const e=queryParamsGetQueryObject(this._queryParams),t=ObjectToUniqueKey(e);return"{}"===t?"default":t}get _queryObject(){return queryParamsGetQueryObject(this._queryParams)}isEqual(e){if(!((e=getModularInstance(e))instanceof QueryImpl))return!1;const t=this._repo===e._repo,n=pathEquals(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+function pathToUrlEncodedString(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}function validateNoPreviousOrderByCall(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function validateQueryEndpoints(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===D){const r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==T)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==E)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===G){if(null!=t&&!isValidPriority(t)||null!=n&&!isValidPriority(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(assert(e.getIndex()instanceof PathIndex||e.getIndex()===j,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function validateLimit(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class ReferenceImpl extends QueryImpl{constructor(e,t){super(e,t,new QueryParams,!1)}get parent(){const e=pathParent(this._path);return null===e?null:new ReferenceImpl(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class DataSnapshot{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const t=new Path(e),n=child(this.ref,e);return new DataSnapshot(this._node.getChild(t),n,G)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){if(this._node.isLeafNode())return!1;return!!this._node.forEachChild(this._index,((t,n)=>e(new DataSnapshot(n,child(this.ref,t),G))))}hasChild(e){const t=new Path(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function ref(e,t){return(e=getModularInstance(e))._checkNotDeleted("ref"),void 0!==t?child(e._root,t):e._root}function refFromURL(e,t){(e=getModularInstance(e))._checkNotDeleted("refFromURL");const n=parseRepoInfo(t,e._repo.repoInfo_.nodeAdmin);validateUrl("refFromURL",n);const r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||fatal("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),ref(e,n.path.toString())}function child(e,t){var n,r,i,o;return null===pathGetFront((e=getModularInstance(e))._path)?(n="child",r="path",o=!1,(i=t)&&(i=i.replace(/^\/*\.info(\/|$)/,"/")),validatePathString(n,r,i,o)):validatePathString("child","path",t,!1),new ReferenceImpl(e._repo,pathChild(e._path,t))}function onDisconnect(e){return e=getModularInstance(e),new OnDisconnect(e._repo,e._path)}function push(e,t){e=getModularInstance(e),validateWritablePath("push",e._path),validateFirebaseDataArg("push",t,e._path,!0);const n=repoServerTime(e._repo),r=ie(n),i=child(e,r),o=child(e,r);let s;return s=null!=t?set(o,t).then((()=>o)):Promise.resolve(o),i.then=s.then.bind(s),i.catch=s.then.bind(s,void 0),i}function remove(e){return validateWritablePath("remove",e._path),set(e,null)}function set(e,t){e=getModularInstance(e),validateWritablePath("set",e._path),validateFirebaseDataArg("set",t,e._path,!1);const n=new Deferred;return repoSetWithPriority(e._repo,e._path,t,null,n.wrapCallback((()=>{}))),n.promise}function setPriority(e,t){e=getModularInstance(e),validateWritablePath("setPriority",e._path),validatePriority("setPriority",t,!1);const n=new Deferred;return repoSetWithPriority(e._repo,pathChild(e._path,".priority"),t,null,n.wrapCallback((()=>{}))),n.promise}function setWithPriority(e,t,n){if(validateWritablePath("setWithPriority",e._path),validateFirebaseDataArg("setWithPriority",t,e._path,!1),validatePriority("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new Deferred;return repoSetWithPriority(e._repo,e._path,t,n,r.wrapCallback((()=>{}))),r.promise}function update(e,t){validateFirebaseMergeDataArg("update",t,e._path,!1);const n=new Deferred;return function repoUpdate(e,t,n,r){repoLog(e,"update",{path:t.toString(),value:n});let i=!0;const o=repoGenerateServerValues(e),s={};if(each(n,((n,r)=>{i=!1,s[n]=resolveDeferredValueTree(pathChild(t,n),nodeFromJSON(r),e.serverSyncTree_,o)})),i)log("update() called with empty data. Don't do anything."),repoCallOnCompleteCallback(0,r,"ok",void 0);else{const i=repoGetNextWriteId(e),o=syncTreeApplyUserMerge(e.serverSyncTree_,t,s,i);eventQueueQueueEvents(e.eventQueue_,o),e.server_.merge(t.toString(),n,((n,o)=>{const s="ok"===n;s||warn("update at "+t+" failed: "+n);const a=syncTreeAckUserWrite(e.serverSyncTree_,i,!s),l=a.length>0?repoRerunTransactions(e,t):t;eventQueueRaiseEventsForChangedPath(e.eventQueue_,l,a),repoCallOnCompleteCallback(0,r,n,o)})),each(n,(n=>{const r=repoAbortTransactions(e,pathChild(t,n));repoRerunTransactions(e,r)})),eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,[])}}(e._repo,e._path,t,n.wrapCallback((()=>{}))),n.promise}function get(e){e=getModularInstance(e);const t=new CallbackContext((()=>{})),n=new ValueEventRegistration(t);return function repoGetValue(e,t,n){const r=syncTreeGetServerValue(e.serverSyncTree_,t);return null!=r?Promise.resolve(r):e.server_.get(t).then((r=>{const i=nodeFromJSON(r).withIndex(t._queryParams.getIndex());let o;if(syncTreeAddEventRegistration(e.serverSyncTree_,t,n,!0),t._queryParams.loadsAllData())o=syncTreeApplyServerOverwrite(e.serverSyncTree_,t._path,i);else{const n=syncTreeTagForQuery(e.serverSyncTree_,t);o=syncTreeApplyTaggedQueryOverwrite(e.serverSyncTree_,t._path,i,n)}return eventQueueRaiseEventsForChangedPath(e.eventQueue_,t._path,o),syncTreeRemoveEventRegistration(e.serverSyncTree_,t,n,null,!0),i}),(n=>(repoLog(e,"get for query "+stringify(t)+" failed: "+n),Promise.reject(new Error(n)))))}(e._repo,e,n).then((t=>new DataSnapshot(t,new ReferenceImpl(e._repo,e._path),e._queryParams.getIndex())))}class ValueEventRegistration{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){const n=t._queryParams.getIndex();return new DataEvent("value",this,new DataSnapshot(e.snapshotNode,new ReferenceImpl(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new CancelEvent(this,e,t):null}matches(e){return e instanceof ValueEventRegistration&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class ChildEventRegistration{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new CancelEvent(this,e,t):null}createEvent(e,t){assert(null!=e.childName,"Child events should have a childName.");const n=child(new ReferenceImpl(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new DataEvent(e.type,this,new DataSnapshot(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof ChildEventRegistration&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function addEventListener(e,t,n,r,i){let o;if("object"==typeof r&&(o=void 0,i=r),"function"==typeof r&&(o=r),i&&i.onlyOnce){const t=n,onceCallback=(n,r)=>{repoRemoveEventCallbackForQuery(e._repo,e,a),t(n,r)};onceCallback.userCallback=n.userCallback,onceCallback.context=n.context,n=onceCallback}const s=new CallbackContext(n,o||void 0),a="value"===t?new ValueEventRegistration(s):new ChildEventRegistration(t,s);return function repoAddEventCallbackForQuery(e,t,n){let r;r=".info"===pathGetFront(t._path)?syncTreeAddEventRegistration(e.infoSyncTree_,t,n):syncTreeAddEventRegistration(e.serverSyncTree_,t,n),eventQueueRaiseEventsAtPath(e.eventQueue_,t._path,r)}(e._repo,e,a),()=>repoRemoveEventCallbackForQuery(e._repo,e,a)}function onValue(e,t,n,r){return addEventListener(e,"value",t,n,r)}function onChildAdded(e,t,n,r){return addEventListener(e,"child_added",t,n,r)}function onChildChanged(e,t,n,r){return addEventListener(e,"child_changed",t,n,r)}function onChildMoved(e,t,n,r){return addEventListener(e,"child_moved",t,n,r)}function onChildRemoved(e,t,n,r){return addEventListener(e,"child_removed",t,n,r)}function off(e,t,n){let r=null;const i=n?new CallbackContext(n):null;"value"===t?r=new ValueEventRegistration(i):t&&(r=new ChildEventRegistration(t,i)),repoRemoveEventCallbackForQuery(e._repo,e,r)}class QueryConstraint{}class QueryEndAtConstraint extends QueryConstraint{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){validateFirebaseDataArg("endAt",this._value,e._path,!0);const t=queryParamsEndAt(e._queryParams,this._value,this._key);if(validateLimit(t),validateQueryEndpoints(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function endAt(e,t){return validateKey("endAt","key",t,!0),new QueryEndAtConstraint(e,t)}class QueryEndBeforeConstraint extends QueryConstraint{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){validateFirebaseDataArg("endBefore",this._value,e._path,!1);const t=function queryParamsEndBefore(e,t,n){let r;return r=e.index_===D||n?queryParamsEndAt(e,t,n):queryParamsEndAt(e,t,T),r.endBeforeSet_=!0,r}(e._queryParams,this._value,this._key);if(validateLimit(t),validateQueryEndpoints(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function endBefore(e,t){return validateKey("endBefore","key",t,!0),new QueryEndBeforeConstraint(e,t)}class QueryStartAtConstraint extends QueryConstraint{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){validateFirebaseDataArg("startAt",this._value,e._path,!0);const t=queryParamsStartAt(e._queryParams,this._value,this._key);if(validateLimit(t),validateQueryEndpoints(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function startAt(e=null,t){return validateKey("startAt","key",t,!0),new QueryStartAtConstraint(e,t)}class QueryStartAfterConstraint extends QueryConstraint{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){validateFirebaseDataArg("startAfter",this._value,e._path,!1);const t=function queryParamsStartAfter(e,t,n){let r;return r=e.index_===D||n?queryParamsStartAt(e,t,n):queryParamsStartAt(e,t,E),r.startAfterSet_=!0,r}(e._queryParams,this._value,this._key);if(validateLimit(t),validateQueryEndpoints(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function startAfter(e,t){return validateKey("startAfter","key",t,!0),new QueryStartAfterConstraint(e,t)}class QueryLimitToFirstConstraint extends QueryConstraint{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new QueryImpl(e._repo,e._path,function queryParamsLimitToFirst(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}function limitToFirst(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new QueryLimitToFirstConstraint(e)}class QueryLimitToLastConstraint extends QueryConstraint{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new QueryImpl(e._repo,e._path,function queryParamsLimitToLast(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}function limitToLast(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new QueryLimitToLastConstraint(e)}class QueryOrderByChildConstraint extends QueryConstraint{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){validateNoPreviousOrderByCall(e,"orderByChild");const t=new Path(this._path);if(pathIsEmpty(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");const n=new PathIndex(t),r=queryParamsOrderBy(e._queryParams,n);return validateQueryEndpoints(r),new QueryImpl(e._repo,e._path,r,!0)}}function orderByChild(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return validatePathString("orderByChild","path",e,!1),new QueryOrderByChildConstraint(e)}class QueryOrderByKeyConstraint extends QueryConstraint{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){validateNoPreviousOrderByCall(e,"orderByKey");const t=queryParamsOrderBy(e._queryParams,D);return validateQueryEndpoints(t),new QueryImpl(e._repo,e._path,t,!0)}}function orderByKey(){return new QueryOrderByKeyConstraint}class QueryOrderByPriorityConstraint extends QueryConstraint{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){validateNoPreviousOrderByCall(e,"orderByPriority");const t=queryParamsOrderBy(e._queryParams,G);return validateQueryEndpoints(t),new QueryImpl(e._repo,e._path,t,!0)}}function orderByPriority(){return new QueryOrderByPriorityConstraint}class QueryOrderByValueConstraint extends QueryConstraint{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){validateNoPreviousOrderByCall(e,"orderByValue");const t=queryParamsOrderBy(e._queryParams,j);return validateQueryEndpoints(t),new QueryImpl(e._repo,e._path,t,!0)}}function orderByValue(){return new QueryOrderByValueConstraint}class QueryEqualToValueConstraint extends QueryConstraint{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(validateFirebaseDataArg("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new QueryEndAtConstraint(this._value,this._key)._apply(new QueryStartAtConstraint(this._value,this._key)._apply(e))}}function equalTo(e,t){return validateKey("equalTo","key",t,!0),new QueryEqualToValueConstraint(e,t)}function query(e,...t){let n=getModularInstance(e);for(const e of t)n=e._apply(n);return n}!function syncPointSetReferenceConstructor(e){assert(!$,"__referenceConstructor has already been defined"),$=e}(ReferenceImpl),function syncTreeSetReferenceConstructor(e){assert(!J,"__referenceConstructor has already been defined"),J=e}(ReferenceImpl);const oe={};let se=!1;function repoManagerDatabaseFromApp(e,t,n,r,i){let o=r||e.options.databaseURL;void 0===o&&(e.options.projectId||fatal("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),log("Using default host for project ",e.options.projectId),o=`${e.options.projectId}-default-rtdb.firebaseio.com`);let s,a,l=parseRepoInfo(o,i),h=l.repoInfo;"undefined"!=typeof process&&process.env&&(a=process.env.FIREBASE_DATABASE_EMULATOR_HOST),a?(s=!0,o=`http://${a}?ns=${h.namespace}`,l=parseRepoInfo(o,i),h=l.repoInfo):s=!l.repoInfo.secure;const c=i&&s?new EmulatorTokenProvider(EmulatorTokenProvider.OWNER):new FirebaseAuthTokenProvider(e.name,e.options,t);validateUrl("Invalid Firebase Database URL",l),pathIsEmpty(l.path)||fatal("Database URL must point to the root of a Firebase Database (not including a child path).");const d=function repoManagerCreateRepo(e,t,n,r){let i=oe[t.name];i||(i={},oe[t.name]=i);let o=i[e.toURLString()];o&&fatal("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return o=new Repo(e,se,n,r),i[e.toURLString()]=o,o}(h,e,c,new AppCheckTokenProvider(e,n));return new Database(d,e)}class Database{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(repoStart(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new ReferenceImpl(this._repo,newEmptyPath())),this._rootInternal}_delete(){return null!==this._rootInternal&&(!function repoManagerDeleteRepo(e,t){const n=oe[t];n&&n[e.key]===e||fatal(`Database ${t}(${e.repoInfo_}) has already been deleted.`),repoInterrupt(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&fatal("Cannot call "+e+" on a deleted database.")}}function checkTransportInit(){TransportManager.IS_TRANSPORT_INITIALIZED&&warn("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function forceWebSockets(){checkTransportInit(),BrowserPollConnection.forceDisallow()}function forceLongPolling(){checkTransportInit(),WebSocketConnection.forceDisallow(),BrowserPollConnection.forceAllow()}function getDatabase(t=e(),n){const r=_getProvider(t,"database").getImmediate({identifier:n});if(!r._instanceStarted){const e=getDefaultEmulatorHostnameAndPort("database");e&&connectDatabaseEmulator(r,...e)}return r}function connectDatabaseEmulator(e,t,n,r={}){(e=getModularInstance(e))._checkNotDeleted("useEmulator");const i=`${t}:${n}`,o=e._repoInternal;if(e._instanceStarted){if(i===e._repoInternal.repoInfo_.host&&deepEqual(r,o.repoInfo_.emulatorOptions))return;fatal("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let s;if(o.repoInfo_.nodeAdmin)r.mockUserToken&&fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),s=new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);else if(r.mockUserToken){const t="string"==typeof r.mockUserToken?r.mockUserToken:function createMockUserToken(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const o={iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}},...e};return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(o)),""].join(".")}(r.mockUserToken,e.app.options.projectId);s=new EmulatorTokenProvider(t)}isCloudWorkstation(t)&&async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(t),function repoManagerApplyEmulatorSettings(e,t,n,r){const i=t.lastIndexOf(":"),o=isCloudWorkstation(t.substring(0,i));e.repoInfo_=new RepoInfo(t,o,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0,n),r&&(e.authTokenProvider_=r)}(o,i,r,s)}function goOffline(e){(e=getModularInstance(e))._checkNotDeleted("goOffline"),repoInterrupt(e._repo)}function goOnline(e){(e=getModularInstance(e))._checkNotDeleted("goOnline"),function repoResume(e){e.persistentConnection_&&e.persistentConnection_.resume(ne)}(e._repo)}function enableLogging(e,t){enableLogging$1(e,t)}const ae={".sv":"timestamp"};function serverTimestamp(){return ae}function increment(e){return{".sv":{increment:e}}}class TransactionResult{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function runTransaction(e,t,n){if(e=getModularInstance(e),validateWritablePath("Reference.transaction",e._path),".length"===e.key||".keys"===e.key)throw"Reference.transaction failed: "+e.key+" is a read-only object.";const r=n?.applyLocally??!0,i=new Deferred,o=onValue(e,(()=>{}));return function repoStartTransaction(e,t,n,r,i,o){repoLog(e,"transaction on "+t);const s={path:t,update:n,onComplete:r,status:null,order:v(),applyLocally:o,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=repoGetLatestState(e,t,void 0);s.currentInputSnapshot=a;const l=s.update(a.val());if(void 0===l)s.unwatcher(),s.currentOutputSnapshotRaw=null,s.currentOutputSnapshotResolved=null,s.onComplete&&s.onComplete(null,!1,s.currentInputSnapshot);else{validateFirebaseData("transaction failed: Data returned ",l,s.path),s.status=0;const n=treeSubTree(e.transactionQueueTree_,t),r=treeGetValue(n)||[];let i;r.push(s),treeSetValue(n,r),"object"==typeof l&&null!==l&&contains(l,".priority")?(i=safeGet(l,".priority"),assert(isValidPriority(i),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):i=(syncTreeCalcCompleteEventCache(e.serverSyncTree_,t)||ChildrenNode.EMPTY_NODE).getPriority().val();const o=repoGenerateServerValues(e),h=nodeFromJSON(l,i),c=resolveDeferredValueSnapshot(h,a,o);s.currentOutputSnapshotRaw=h,s.currentOutputSnapshotResolved=c,s.currentWriteId=repoGetNextWriteId(e);const d=syncTreeApplyUserOverwrite(e.serverSyncTree_,t,c,s.currentWriteId,s.applyLocally);eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,d),repoSendReadyTransactions(e,e.transactionQueueTree_)}}(e._repo,e._path,t,((t,n,r)=>{let o=null;t?i.reject(t):(o=new DataSnapshot(r,new ReferenceImpl(e._repo,e._path),G),i.resolve(new TransactionResult(n,o)))}),o,r),i.promise}PersistentConnection.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},PersistentConnection.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)};const hijackHash=function(e){const t=PersistentConnection.prototype.put;return PersistentConnection.prototype.put=function(n,r,i,o){void 0!==o&&(o=e()),t.call(this,n,r,i,o)},function(){PersistentConnection.prototype.put=t}},forceRestClient=function(e){!function repoManagerForceRestClient(e){se=e}(e)};function _initStandalone({app:e,url:t,version:n,customAuthImpl:r,customAppCheckImpl:i,nodeAdmin:o=!1}){setSDKVersion(n);const s=new ComponentContainer("database-standalone"),a=new Provider("auth-internal",s);let l;return i&&(l=new Provider("app-check-internal",s),l.setComponent(new Component("app-check-internal",(()=>i),"PRIVATE"))),a.setComponent(new Component("auth-internal",(()=>r),"PRIVATE")),repoManagerDatabaseFromApp(e,a,l,t,o)}!function registerDatabase(e){setSDKVersion(i),t(new Component("database",((e,{instanceIdentifier:t})=>repoManagerDatabaseFromApp(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)),"PUBLIC").setMultipleInstances(!0)),n(p,_,e),n(p,_,"esm2020")}();export{DataSnapshot,Database,OnDisconnect,QueryConstraint,TransactionResult,QueryImpl as _QueryImpl,QueryParams as _QueryParams,ReferenceImpl as _ReferenceImpl,forceRestClient as _TEST_ACCESS_forceRestClient,hijackHash as _TEST_ACCESS_hijackHash,_initStandalone,repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp,setSDKVersion as _setSDKVersion,validatePathString as _validatePathString,validateWritablePath as _validateWritablePath,child,connectDatabaseEmulator,enableLogging,endAt,endBefore,equalTo,forceLongPolling,forceWebSockets,get,getDatabase,goOffline,goOnline,increment,limitToFirst,limitToLast,off,onChildAdded,onChildChanged,onChildMoved,onChildRemoved,onDisconnect,onValue,orderByChild,orderByKey,orderByPriority,orderByValue,push,query,ref,refFromURL,remove,runTransaction,serverTimestamp,set,setPriority,setWithPriority,startAfter,startAt,update};
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import{_isFirebaseServerApp as e,_getProvider,getApp as r,_removeServiceInstance as i,_registerComponent as s,registerVersion as o,SDK_VERSION as a}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";const stringToByteArray$1=function(e){const r=[];let i=0;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);o<128?r[i++]=o:o<2048?(r[i++]=o>>6|192,r[i++]=63&o|128):55296==(64512&o)&&s+1<e.length&&56320==(64512&e.charCodeAt(s+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++s)),r[i++]=o>>18|240,r[i++]=o>>12&63|128,r[i++]=o>>6&63|128,r[i++]=63&o|128):(r[i++]=o>>12|224,r[i++]=o>>6&63|128,r[i++]=63&o|128)}return r},_={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,r){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const i=r?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let r=0;r<e.length;r+=3){const o=e[r],a=r+1<e.length,_=a?e[r+1]:0,h=r+2<e.length,d=h?e[r+2]:0,f=o>>2,g=(3&o)<<4|_>>4;let E=(15&_)<<2|d>>6,T=63&d;h||(T=64,a||(E=64)),s.push(i[f],i[g],i[E],i[T])}return s.join("")},encodeString(e,r){return this.HAS_NATIVE_SUPPORT&&!r?btoa(e):this.encodeByteArray(stringToByteArray$1(e),r)},decodeString(e,r){return this.HAS_NATIVE_SUPPORT&&!r?atob(e):function(e){const r=[];let i=0,s=0;for(;i<e.length;){const o=e[i++];if(o<128)r[s++]=String.fromCharCode(o);else if(o>191&&o<224){const a=e[i++];r[s++]=String.fromCharCode((31&o)<<6|63&a)}else if(o>239&&o<365){const a=((7&o)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536;r[s++]=String.fromCharCode(55296+(a>>10)),r[s++]=String.fromCharCode(56320+(1023&a))}else{const a=e[i++],_=e[i++];r[s++]=String.fromCharCode((15&o)<<12|(63&a)<<6|63&_)}}return r.join("")}(this.decodeStringToByteArray(e,r))},decodeStringToByteArray(e,r){this.init_();const i=r?this.charToByteMapWebSafe_:this.charToByteMap_,s=[];for(let r=0;r<e.length;){const o=i[e.charAt(r++)],a=r<e.length?i[e.charAt(r)]:0;++r;const _=r<e.length?i[e.charAt(r)]:64;++r;const h=r<e.length?i[e.charAt(r)]:64;if(++r,null==o||null==a||null==_||null==h)throw new DecodeBase64StringError;const d=o<<2|a>>4;if(s.push(d),64!==_){const e=a<<4&240|_>>2;if(s.push(e),64!==h){const e=_<<6&192|h;s.push(e)}}}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64urlEncodeWithoutPadding=function(e){return function(e){const r=stringToByteArray$1(e);return _.encodeByteArray(r,!0)}(e).replace(/\./g,"")};const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const r=e&&function(e){try{return _.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return r&&JSON.parse(r)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const r=(e=>getDefaults()?.emulatorHosts?.[e])(e);if(!r)return;const i=r.lastIndexOf(":");if(i<=0||i+1===r.length)throw new Error(`Invalid host ${r} with no separate hostname and port!`);const s=parseInt(r.substring(i+1),10);return"["===r[0]?[r.substring(1,i-1),s]:[r.substring(0,i),s]};class FirebaseError extends Error{constructor(e,r,i){super(r),this.code=e,this.customData=i,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,r,i){this.service=e,this.serviceName=r,this.errors=i}create(e,...r){const i=r[0]||{},s=`${this.service}/${e}`,o=this.errors[e],a=o?function replaceTemplate(e,r){return e.replace(h,((e,i)=>{const s=r[i];return null!=s?String(s):`<${i}?>`}))}(o,i):"Error",_=`${this.serviceName}: ${a} (${s}).`;return new FirebaseError(s,_,i)}}const h=/\{\$([^}]+)}/g;function deepEqual(e,r){if(e===r)return!0;const i=Object.keys(e),s=Object.keys(r);for(const o of i){if(!s.includes(o))return!1;const i=e[o],a=r[o];if(isObject(i)&&isObject(a)){if(!deepEqual(i,a))return!1}else if(i!==a)return!1}for(const e of s)if(!i.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function getModularInstance(e){return e&&e._delegate?e._delegate:e}function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class Component{constructor(e,r,i){this.name=e,this.instanceFactory=r,this.type=i,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var d;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(d||(d={}));const f={debug:d.DEBUG,verbose:d.VERBOSE,info:d.INFO,warn:d.WARN,error:d.ERROR,silent:d.SILENT},g=d.INFO,E={[d.DEBUG]:"log",[d.VERBOSE]:"log",[d.INFO]:"info",[d.WARN]:"warn",[d.ERROR]:"error"},defaultLogHandler=(e,r,...i)=>{if(r<e.logLevel)return;const s=(new Date).toISOString(),o=E[r];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${r})`);console[o](`[${s}] ${e.name}:`,...i)};var T,A="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};(function(){var e;function m(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.C=Array(this.blockSize),this.o=this.h=0,this.u()}function n(e,r,i){i||(i=0);const s=Array(16);if("string"==typeof r)for(var o=0;o<16;++o)s[o]=r.charCodeAt(i++)|r.charCodeAt(i++)<<8|r.charCodeAt(i++)<<16|r.charCodeAt(i++)<<24;else for(o=0;o<16;++o)s[o]=r[i++]|r[i++]<<8|r[i++]<<16|r[i++]<<24;r=e.g[0],i=e.g[1],o=e.g[2];let a,_=e.g[3];a=r+(_^i&(o^_))+s[0]+3614090360&4294967295,a=_+(o^(r=i+(a<<7&4294967295|a>>>25))&(i^o))+s[1]+3905402710&4294967295,_=r+(a<<12&4294967295|a>>>20),a=o+(i^_&(r^i))+s[2]+606105819&4294967295,a=i+(r^(o=_+(a<<17&4294967295|a>>>15))&(_^r))+s[3]+3250441966&4294967295,a=r+(_^(i=o+(a<<22&4294967295|a>>>10))&(o^_))+s[4]+4118548399&4294967295,a=_+(o^(r=i+(a<<7&4294967295|a>>>25))&(i^o))+s[5]+1200080426&4294967295,_=r+(a<<12&4294967295|a>>>20),a=o+(i^_&(r^i))+s[6]+2821735955&4294967295,a=i+(r^(o=_+(a<<17&4294967295|a>>>15))&(_^r))+s[7]+4249261313&4294967295,a=r+(_^(i=o+(a<<22&4294967295|a>>>10))&(o^_))+s[8]+1770035416&4294967295,a=_+(o^(r=i+(a<<7&4294967295|a>>>25))&(i^o))+s[9]+2336552879&4294967295,_=r+(a<<12&4294967295|a>>>20),a=o+(i^_&(r^i))+s[10]+4294925233&4294967295,a=i+(r^(o=_+(a<<17&4294967295|a>>>15))&(_^r))+s[11]+2304563134&4294967295,a=r+(_^(i=o+(a<<22&4294967295|a>>>10))&(o^_))+s[12]+1804603682&4294967295,a=_+(o^(r=i+(a<<7&4294967295|a>>>25))&(i^o))+s[13]+4254626195&4294967295,_=r+(a<<12&4294967295|a>>>20),a=o+(i^_&(r^i))+s[14]+2792965006&4294967295,a=i+(r^(o=_+(a<<17&4294967295|a>>>15))&(_^r))+s[15]+1236535329&4294967295,a=r+(o^_&((i=o+(a<<22&4294967295|a>>>10))^o))+s[1]+4129170786&4294967295,a=_+(i^o&((r=i+(a<<5&4294967295|a>>>27))^i))+s[6]+3225465664&4294967295,_=r+(a<<9&4294967295|a>>>23),a=o+(r^i&(_^r))+s[11]+643717713&4294967295,a=i+(_^r&((o=_+(a<<14&4294967295|a>>>18))^_))+s[0]+3921069994&4294967295,a=r+(o^_&((i=o+(a<<20&4294967295|a>>>12))^o))+s[5]+3593408605&4294967295,a=_+(i^o&((r=i+(a<<5&4294967295|a>>>27))^i))+s[10]+38016083&4294967295,_=r+(a<<9&4294967295|a>>>23),a=o+(r^i&(_^r))+s[15]+3634488961&4294967295,a=i+(_^r&((o=_+(a<<14&4294967295|a>>>18))^_))+s[4]+3889429448&4294967295,a=r+(o^_&((i=o+(a<<20&4294967295|a>>>12))^o))+s[9]+568446438&4294967295,a=_+(i^o&((r=i+(a<<5&4294967295|a>>>27))^i))+s[14]+3275163606&4294967295,_=r+(a<<9&4294967295|a>>>23),a=o+(r^i&(_^r))+s[3]+4107603335&4294967295,a=i+(_^r&((o=_+(a<<14&4294967295|a>>>18))^_))+s[8]+1163531501&4294967295,a=r+(o^_&((i=o+(a<<20&4294967295|a>>>12))^o))+s[13]+2850285829&4294967295,a=_+(i^o&((r=i+(a<<5&4294967295|a>>>27))^i))+s[2]+4243563512&4294967295,_=r+(a<<9&4294967295|a>>>23),a=o+(r^i&(_^r))+s[7]+1735328473&4294967295,a=i+(_^r&((o=_+(a<<14&4294967295|a>>>18))^_))+s[12]+2368359562&4294967295,a=r+((i=o+(a<<20&4294967295|a>>>12))^o^_)+s[5]+4294588738&4294967295,a=_+((r=i+(a<<4&4294967295|a>>>28))^i^o)+s[8]+2272392833&4294967295,_=r+(a<<11&4294967295|a>>>21),a=o+(_^r^i)+s[11]+1839030562&4294967295,a=i+((o=_+(a<<16&4294967295|a>>>16))^_^r)+s[14]+4259657740&4294967295,a=r+((i=o+(a<<23&4294967295|a>>>9))^o^_)+s[1]+2763975236&4294967295,a=_+((r=i+(a<<4&4294967295|a>>>28))^i^o)+s[4]+1272893353&4294967295,_=r+(a<<11&4294967295|a>>>21),a=o+(_^r^i)+s[7]+4139469664&4294967295,a=i+((o=_+(a<<16&4294967295|a>>>16))^_^r)+s[10]+3200236656&4294967295,a=r+((i=o+(a<<23&4294967295|a>>>9))^o^_)+s[13]+681279174&4294967295,a=_+((r=i+(a<<4&4294967295|a>>>28))^i^o)+s[0]+3936430074&4294967295,_=r+(a<<11&4294967295|a>>>21),a=o+(_^r^i)+s[3]+3572445317&4294967295,a=i+((o=_+(a<<16&4294967295|a>>>16))^_^r)+s[6]+76029189&4294967295,a=r+((i=o+(a<<23&4294967295|a>>>9))^o^_)+s[9]+3654602809&4294967295,a=_+((r=i+(a<<4&4294967295|a>>>28))^i^o)+s[12]+3873151461&4294967295,_=r+(a<<11&4294967295|a>>>21),a=o+(_^r^i)+s[15]+530742520&4294967295,a=i+((o=_+(a<<16&4294967295|a>>>16))^_^r)+s[2]+3299628645&4294967295,a=r+(o^((i=o+(a<<23&4294967295|a>>>9))|~_))+s[0]+4096336452&4294967295,a=_+(i^((r=i+(a<<6&4294967295|a>>>26))|~o))+s[7]+1126891415&4294967295,_=r+(a<<10&4294967295|a>>>22),a=o+(r^(_|~i))+s[14]+2878612391&4294967295,a=i+(_^((o=_+(a<<15&4294967295|a>>>17))|~r))+s[5]+4237533241&4294967295,a=r+(o^((i=o+(a<<21&4294967295|a>>>11))|~_))+s[12]+1700485571&4294967295,a=_+(i^((r=i+(a<<6&4294967295|a>>>26))|~o))+s[3]+2399980690&4294967295,_=r+(a<<10&4294967295|a>>>22),a=o+(r^(_|~i))+s[10]+4293915773&4294967295,a=i+(_^((o=_+(a<<15&4294967295|a>>>17))|~r))+s[1]+2240044497&4294967295,a=r+(o^((i=o+(a<<21&4294967295|a>>>11))|~_))+s[8]+1873313359&4294967295,a=_+(i^((r=i+(a<<6&4294967295|a>>>26))|~o))+s[15]+4264355552&4294967295,_=r+(a<<10&4294967295|a>>>22),a=o+(r^(_|~i))+s[6]+2734768916&4294967295,a=i+(_^((o=_+(a<<15&4294967295|a>>>17))|~r))+s[13]+1309151649&4294967295,a=r+(o^((i=o+(a<<21&4294967295|a>>>11))|~_))+s[4]+4149444226&4294967295,a=_+(i^((r=i+(a<<6&4294967295|a>>>26))|~o))+s[11]+3174756917&4294967295,_=r+(a<<10&4294967295|a>>>22),a=o+(r^(_|~i))+s[2]+718787259&4294967295,a=i+(_^((o=_+(a<<15&4294967295|a>>>17))|~r))+s[9]+3951481745&4294967295,e.g[0]=e.g[0]+r&4294967295,e.g[1]=e.g[1]+(o+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+o&4294967295,e.g[3]=e.g[3]+_&4294967295}function t(e,r){this.h=r;const i=[];let s=!0;for(let o=e.length-1;o>=0;o--){const a=0|e[o];s&&a==r||(i[o]=a,s=!1)}this.g=i}!function k(e,r){function c(){}c.prototype=r.prototype,e.F=r.prototype,e.prototype=new c,e.prototype.constructor=e,e.D=function(e,i,s){for(var o=Array(arguments.length-2),a=2;a<arguments.length;a++)o[a-2]=arguments[a];return r.prototype[i].apply(e,o)}}(m,(function l(){this.blockSize=-1})),m.prototype.u=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},m.prototype.v=function(e,r){void 0===r&&(r=e.length);const i=r-this.blockSize,s=this.C;let o=this.h,a=0;for(;a<r;){if(0==o)for(;a<=i;)n(this,e,a),a+=this.blockSize;if("string"==typeof e){for(;a<r;)if(s[o++]=e.charCodeAt(a++),o==this.blockSize){n(this,s),o=0;break}}else for(;a<r;)if(s[o++]=e[a++],o==this.blockSize){n(this,s),o=0;break}}this.h=o,this.o+=r},m.prototype.A=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var r=1;r<e.length-8;++r)e[r]=0;r=8*this.o;for(var i=e.length-8;i<e.length;++i)e[i]=255&r,r/=256;for(this.v(e),e=Array(16),r=0,i=0;i<4;++i)for(let s=0;s<32;s+=8)e[r++]=this.g[i]>>>s&255;return e};var r={};function u(e){return-128<=e&&e<128?function p(e,i){var s=r;return Object.prototype.hasOwnProperty.call(s,e)?s[e]:s[e]=i(e)}(e,(function(e){return new t([0|e],e<0?-1:0)})):new t([0|e],e<0?-1:0)}function v(e){if(isNaN(e)||!isFinite(e))return i;if(e<0)return x(v(-e));const r=[];let s=1;for(let i=0;e>=s;i++)r[i]=e/s|0,s*=4294967296;return new t(r,0)}var i=u(0),s=u(1),o=u(16777216);function C(e){if(0!=e.h)return!1;for(let r=0;r<e.g.length;r++)if(0!=e.g[r])return!1;return!0}function B(e){return-1==e.h}function x(e){const r=e.g.length,i=[];for(let s=0;s<r;s++)i[s]=~e.g[s];return new t(i,~e.h).add(s)}function F(e,r){return e.add(x(r))}function G(e,r){for(;(65535&e[r])!=e[r];)e[r+1]+=e[r]>>>16,e[r]&=65535,r++}function H(e,r){this.g=e,this.h=r}function D(e,r){if(C(r))throw Error("division by zero");if(C(e))return new H(i,i);if(B(e))return r=D(x(e),r),new H(x(r.g),x(r.h));if(B(r))return r=D(e,x(r)),new H(x(r.g),r.h);if(e.g.length>30){if(B(e)||B(r))throw Error("slowDivide_ only works with positive integers.");for(var o=s,a=r;a.l(e)<=0;)o=I(o),a=I(a);var _=J(o,1),h=J(a,1);for(a=J(a,2),o=J(o,2);!C(a);){var d=h.add(a);d.l(e)<=0&&(_=_.add(o),h=d),a=J(a,1),o=J(o,1)}return r=F(e,_.j(r)),new H(_,r)}for(_=i;e.l(r)>=0;){for(o=Math.max(1,Math.floor(e.m()/r.m())),a=(a=Math.ceil(Math.log(o)/Math.LN2))<=48?1:Math.pow(2,a-48),d=(h=v(o)).j(r);B(d)||d.l(e)>0;)d=(h=v(o-=a)).j(r);C(h)&&(h=s),_=_.add(h),e=F(e,d)}return new H(_,e)}function I(e){const r=e.g.length+1,i=[];for(let s=0;s<r;s++)i[s]=e.i(s)<<1|e.i(s-1)>>>31;return new t(i,e.h)}function J(e,r){const i=r>>5;r%=32;const s=e.g.length-i,o=[];for(let a=0;a<s;a++)o[a]=r>0?e.i(a+i)>>>r|e.i(a+i+1)<<32-r:e.i(a+i);return new t(o,e.h)}(e=t.prototype).m=function(){if(B(this))return-x(this).m();let e=0,r=1;for(let i=0;i<this.g.length;i++){const s=this.i(i);e+=(s>=0?s:4294967296+s)*r,r*=4294967296}return e},e.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(C(this))return"0";if(B(this))return"-"+x(this).toString(e);const r=v(Math.pow(e,6));var i=this;let s="";for(;;){const o=D(i,r).g;let a=(((i=F(i,o.j(r))).g.length>0?i.g[0]:i.h)>>>0).toString(e);if(C(i=o))return a+s;for(;a.length<6;)a="0"+a;s=a+s}},e.i=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},e.l=function(e){return B(e=F(this,e))?-1:C(e)?0:1},e.abs=function(){return B(this)?x(this):this},e.add=function(e){const r=Math.max(this.g.length,e.g.length),i=[];let s=0;for(let o=0;o<=r;o++){let r=s+(65535&this.i(o))+(65535&e.i(o)),a=(r>>>16)+(this.i(o)>>>16)+(e.i(o)>>>16);s=a>>>16,r&=65535,a&=65535,i[o]=a<<16|r}return new t(i,-2147483648&i[i.length-1]?-1:0)},e.j=function(e){if(C(this)||C(e))return i;if(B(this))return B(e)?x(this).j(x(e)):x(x(this).j(e));if(B(e))return x(this.j(x(e)));if(this.l(o)<0&&e.l(o)<0)return v(this.m()*e.m());const r=this.g.length+e.g.length,s=[];for(var a=0;a<2*r;a++)s[a]=0;for(a=0;a<this.g.length;a++)for(let r=0;r<e.g.length;r++){const i=this.i(a)>>>16,o=65535&this.i(a),_=e.i(r)>>>16,h=65535&e.i(r);s[2*a+2*r]+=o*h,G(s,2*a+2*r),s[2*a+2*r+1]+=i*h,G(s,2*a+2*r+1),s[2*a+2*r+1]+=o*_,G(s,2*a+2*r+1),s[2*a+2*r+2]+=i*_,G(s,2*a+2*r+2)}for(e=0;e<r;e++)s[e]=s[2*e+1]<<16|s[2*e];for(e=r;e<2*r;e++)s[e]=0;return new t(s,0)},e.B=function(e){return D(this,e).h},e.and=function(e){const r=Math.max(this.g.length,e.g.length),i=[];for(let s=0;s<r;s++)i[s]=this.i(s)&e.i(s);return new t(i,this.h&e.h)},e.or=function(e){const r=Math.max(this.g.length,e.g.length),i=[];for(let s=0;s<r;s++)i[s]=this.i(s)|e.i(s);return new t(i,this.h|e.h)},e.xor=function(e){const r=Math.max(this.g.length,e.g.length),i=[];for(let s=0;s<r;s++)i[s]=this.i(s)^e.i(s);return new t(i,this.h^e.h)},m.prototype.digest=m.prototype.A,m.prototype.reset=m.prototype.u,m.prototype.update=m.prototype.v,t.prototype.add=t.prototype.add,t.prototype.multiply=t.prototype.j,t.prototype.modulo=t.prototype.B,t.prototype.compare=t.prototype.l,t.prototype.toNumber=t.prototype.m,t.prototype.toString=t.prototype.toString,t.prototype.getBits=t.prototype.i,t.fromNumber=v,t.fromString=function y(e,r){if(0==e.length)throw Error("number format error: empty string");if((r=r||10)<2||36<r)throw Error("radix out of range: "+r);if("-"==e.charAt(0))return x(y(e.substring(1),r));if(e.indexOf("-")>=0)throw Error('number format error: interior "-" character');const s=v(Math.pow(r,8));let o=i;for(let i=0;i<e.length;i+=8){var a=Math.min(8,e.length-i);const _=parseInt(e.substring(i,i+a),r);a<8?(a=v(Math.pow(r,a)),o=o.j(a).add(v(_))):(o=o.j(s),o=o.add(v(_)))}return o},T=t}).apply(void 0!==A?A:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});class User{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}User.UNAUTHENTICATED=new User(null),User.GOOGLE_CREDENTIALS=new User("google-credentials-uid"),User.FIRST_PARTY=new User("first-party-uid"),User.MOCK_USER=new User("mock-user");let V="12.15.0";const P=new class Logger{constructor(e){this.name=e,this._logLevel=g,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in d))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?f[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,d.DEBUG,...e),this._logHandler(this,d.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,d.VERBOSE,...e),this._logHandler(this,d.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,d.INFO,...e),this._logHandler(this,d.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,d.WARN,...e),this._logHandler(this,d.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,d.ERROR,...e),this._logHandler(this,d.ERROR,...e)}}("@firebase/firestore");function setLogLevel(e){P.setLogLevel(e)}function __PRIVATE_logDebug(e,...r){if(P.logLevel<=d.DEBUG){const i=r.map(__PRIVATE_argToString);P.debug(`Firestore (${V}): ${e}`,...i)}}function __PRIVATE_logError(e,...r){if(P.logLevel<=d.ERROR){const i=r.map(__PRIVATE_argToString);P.error(`Firestore (${V}): ${e}`,...i)}}function __PRIVATE_logWarn(e,...r){if(P.logLevel<=d.WARN){const i=r.map(__PRIVATE_argToString);P.warn(`Firestore (${V}): ${e}`,...i)}}function __PRIVATE_argToString(e){if("string"==typeof e)return e;try{return function __PRIVATE_formatJSON(e){return JSON.stringify(e)}(e)}catch(r){return e}}function fail(e,r,i){let s="Unexpected state";"string"==typeof r?s=r:i=r,__PRIVATE__fail(e,s,i)}function __PRIVATE__fail(e,r,i){let s=`FIRESTORE (${V}) INTERNAL ASSERTION FAILED: ${r} (ID: ${e.toString(16)})`;if(void 0!==i)try{s+=" CONTEXT: "+JSON.stringify(i)}catch(e){s+=" CONTEXT: "+i}throw __PRIVATE_logError(s),new Error(s)}function __PRIVATE_hardAssert(e,r,i,s){let o="Unexpected state";"string"==typeof i?o=i:s=i,e||__PRIVATE__fail(r,o,s)}function __PRIVATE_debugCast(e,r){return e}const R="ok",w="cancelled",S="unknown",b="invalid-argument",N="deadline-exceeded",O="not-found",M="already-exists",L="permission-denied",q="unauthenticated",U="resource-exhausted",j="failed-precondition",$="aborted",z="out-of-range",Q="unimplemented",W="internal",K="unavailable",Y="data-loss";class FirestoreError extends FirebaseError{constructor(e,r){super(e,r),this.code=e,this.message=r,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class __PRIVATE_OAuthToken{constructor(e,r){this.user=r,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class __PRIVATE_EmptyAuthCredentialsProvider{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,r){e.enqueueRetryable((()=>r(User.UNAUTHENTICATED)))}shutdown(){}}class __PRIVATE_EmulatorAuthCredentialsProvider{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,r){this.changeListener=r,e.enqueueRetryable((()=>r(this.token.user)))}shutdown(){this.changeListener=null}}class __PRIVATE_LiteAuthCredentialsProvider{constructor(e){this.auth=null,e.onInit((e=>{this.auth=e}))}getToken(){return this.auth?this.auth.getToken().then((e=>e?(__PRIVATE_hardAssert("string"==typeof e.accessToken,42297,{t:e}),new __PRIVATE_OAuthToken(e.accessToken,new User(this.auth.getUid()))):null)):Promise.resolve(null)}invalidateToken(){}start(e,r){}shutdown(){}}class __PRIVATE_FirstPartyToken{constructor(e,r,i){this.i=e,this.o=r,this.u=i,this.type="FirstParty",this.user=User.FIRST_PARTY,this.l=new Map}h(){return this.u?this.u():null}get headers(){this.l.set("X-Goog-AuthUser",this.i);const e=this.h();return e&&this.l.set("Authorization",e),this.o&&this.l.set("X-Goog-Iam-Authorization-Token",this.o),this.l}}class __PRIVATE_FirstPartyAuthCredentialsProvider{constructor(e,r,i){this.i=e,this.o=r,this.u=i}getToken(){return Promise.resolve(new __PRIVATE_FirstPartyToken(this.i,this.o,this.u))}start(e,r){e.enqueueRetryable((()=>r(User.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class AppCheckToken{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class __PRIVATE_LiteAppCheckTokenProvider{constructor(r,i){this.m=i,this.appCheck=null,this.T=null,e(r)&&r.settings.appCheckToken&&(this.T=r.settings.appCheckToken),i.onInit((e=>{this.appCheck=e}))}getToken(){return this.T?Promise.resolve(new AppCheckToken(this.T)):this.appCheck?this.appCheck.getToken().then((e=>e?(__PRIVATE_hardAssert("string"==typeof e.token,3470,{tokenResult:e}),new AppCheckToken(e.token)):null)):Promise.resolve(null)}invalidateToken(){}start(e,r){}shutdown(){}}class DatabaseInfo{constructor(e,r,i,s,o,a,_,h,d,f,g){this.databaseId=e,this.appId=r,this.persistenceKey=i,this.host=s,this.ssl=o,this.forceLongPolling=a,this.autoDetectLongPolling=_,this.longPollingOptions=h,this.useFetchStreams=d,this.isUsingEmulator=f,this.apiKey=g}}const X="(default)";class DatabaseId{constructor(e,r){this.projectId=e,this.database=r||X}static empty(){return new DatabaseId("","")}get isDefaultDatabase(){return this.database===X}isEqual(e){return e instanceof DatabaseId&&e.projectId===this.projectId&&e.database===this.database}}function __PRIVATE_randomBytes(e){const r="undefined"!=typeof self&&(self.crypto||self.msCrypto),i=new Uint8Array(e);if(r&&"function"==typeof r.getRandomValues)r.getRandomValues(i);else for(let r=0;r<e;r++)i[r]=Math.floor(256*Math.random());return i}class __PRIVATE_AutoId{static newId(){const e=62*Math.floor(256/62);let r="";for(;r.length<20;){const i=__PRIVATE_randomBytes(40);for(let s=0;s<i.length;++s)r.length<20&&i[s]<e&&(r+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(i[s]%62))}return r}}function __PRIVATE_primitiveComparator(e,r){return e<r?-1:e>r?1:0}function __PRIVATE_compareUtf8Strings(e,r){const i=Math.min(e.length,r.length);for(let s=0;s<i;s++){const i=e.charAt(s),o=r.charAt(s);if(i!==o)return __PRIVATE_isSurrogate(i)===__PRIVATE_isSurrogate(o)?__PRIVATE_primitiveComparator(i,o):__PRIVATE_isSurrogate(i)?1:-1}return __PRIVATE_primitiveComparator(e.length,r.length)}const Z=55296,ee=57343;function __PRIVATE_isSurrogate(e){const r=e.charCodeAt(0);return r>=Z&&r<=ee}function __PRIVATE_arrayEquals(e,r,i){return e.length===r.length&&e.every(((e,s)=>i(e,r[s])))}const te="__name__";class BasePath{constructor(e,r,i){void 0===r?r=0:r>e.length&&fail(637,{offset:r,range:e.length}),void 0===i?i=e.length-r:i>e.length-r&&fail(1746,{length:i,range:e.length-r}),this.segments=e,this.offset=r,this.len=i}get length(){return this.len}isEqual(e){return 0===BasePath.comparator(this,e)}child(e){const r=this.segments.slice(this.offset,this.limit());return e instanceof BasePath?e.forEach((e=>{r.push(e)})):r.push(e),this.construct(r)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let r=0;r<this.length;r++)if(this.get(r)!==e.get(r))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let r=0;r<this.length;r++)if(this.get(r)!==e.get(r))return!1;return!0}forEach(e){for(let r=this.offset,i=this.limit();r<i;r++)e(this.segments[r])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,r){const i=Math.min(e.length,r.length);for(let s=0;s<i;s++){const i=BasePath.compareSegments(e.get(s),r.get(s));if(0!==i)return i}return __PRIVATE_primitiveComparator(e.length,r.length)}static compareSegments(e,r){const i=BasePath.isNumericId(e),s=BasePath.isNumericId(r);return i&&!s?-1:!i&&s?1:i&&s?BasePath.extractNumericId(e).compare(BasePath.extractNumericId(r)):__PRIVATE_compareUtf8Strings(e,r)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return T.fromString(e.substring(4,e.length-2))}}class ResourcePath extends BasePath{construct(e,r,i){return new ResourcePath(e,r,i)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toStringWithLeadingSlash(){return`/${this.canonicalString()}`}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const r=[];for(const i of e){if(i.indexOf("//")>=0)throw new FirestoreError(b,`Invalid segment (${i}). Paths must not contain // in them.`);r.push(...i.split("/").filter((e=>e.length>0)))}return new ResourcePath(r)}static emptyPath(){return new ResourcePath([])}}const re=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class FieldPath$1 extends BasePath{construct(e,r,i){return new FieldPath$1(e,r,i)}static isValidIdentifier(e){return re.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),FieldPath$1.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===te}static keyField(){return new FieldPath$1([te])}static fromServerFormat(e){const r=[];let i="",s=0;const __PRIVATE_addCurrentSegment=()=>{if(0===i.length)throw new FirestoreError(b,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);r.push(i),i=""};let o=!1;for(;s<e.length;){const r=e[s];if("\\"===r){if(s+1===e.length)throw new FirestoreError(b,"Path has trailing escape character: "+e);const r=e[s+1];if("\\"!==r&&"."!==r&&"`"!==r)throw new FirestoreError(b,"Path has invalid escape sequence: "+e);i+=r,s+=2}else"`"===r?(o=!o,s++):"."!==r||o?(i+=r,s++):(__PRIVATE_addCurrentSegment(),s++)}if(__PRIVATE_addCurrentSegment(),o)throw new FirestoreError(b,"Unterminated ` in path: "+e);return new FieldPath$1(r)}static emptyPath(){return new FieldPath$1([])}}class DocumentKey{constructor(e){this.path=e}static fromPath(e){return new DocumentKey(ResourcePath.fromString(e))}static fromName(e){return new DocumentKey(ResourcePath.fromString(e).popFirst(5))}static empty(){return new DocumentKey(ResourcePath.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===ResourcePath.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,r){return ResourcePath.comparator(e.path,r.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new DocumentKey(new ResourcePath(e.slice()))}}function __PRIVATE_validateNonEmptyArgument(e,r,i){if(!i)throw new FirestoreError(b,`Function ${e}() cannot be called with an empty ${r}.`)}function __PRIVATE_validateDocumentPath(e){if(!DocumentKey.isDocumentKey(e))throw new FirestoreError(b,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_validateCollectionPath(e){if(DocumentKey.isDocumentKey(e))throw new FirestoreError(b,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_isPlainObject(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function __PRIVATE_valueDescription(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const r=function __PRIVATE_tryGetCustomObjectType(e){return e.constructor?e.constructor.name:null}(e);return r?`a custom ${r} object`:"an object"}}return"function"==typeof e?"a function":fail(12329,{type:typeof e})}function __PRIVATE_cast(e,r){if("_delegate"in e&&(e=e._delegate),!(e instanceof r)){if(r.name===e.constructor.name)throw new FirestoreError(b,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const i=__PRIVATE_valueDescription(e);throw new FirestoreError(b,`Expected type '${r.name}', but it was: ${i}`)}}return e}function __PRIVATE_validatePositiveNumber(e,r){if(r<=0)throw new FirestoreError(b,`Function ${e}() requires a positive number, but it was: ${r}.`)}function __PRIVATE_cloneLongPollingOptions(e){const r={};return void 0!==e.timeoutSeconds&&(r.timeoutSeconds=e.timeoutSeconds),r}let ne=null;function __PRIVATE_isNullOrUndefined(e){return null==e}function __PRIVATE_isNegativeZero(e){return 0===e&&1/e==-1/0}const ie="RestConnection",se={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery",ExecutePipeline:"executePipeline"};class __PRIVATE_RestConnection{get P(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const r=e.ssl?"https":"http",i=encodeURIComponent(this.databaseId.projectId),s=encodeURIComponent(this.databaseId.database);this.V=r+"://"+e.host,this.R=`projects/${i}/databases/${s}`,this.A=this.databaseId.database===X?`project_id=${i}`:`project_id=${i}&database_id=${s}`}I(e,r,i,s,o){const a=function __PRIVATE_generateUniqueDebugId(){return null===ne?ne=function __PRIVATE_generateInitialUniqueDebugId(){return 268435456+Math.round(2147483648*Math.random())}():ne++,"0x"+ne.toString(16)}(),_=this.p(e,r.toUriEncodedString());__PRIVATE_logDebug(ie,`Sending RPC '${e}' ${a}:`,_,i);const h={"google-cloud-resource-prefix":this.R,"x-goog-request-params":this.A};this.F(h,s,o);const{host:d}=new URL(_),f=isCloudWorkstation(d);return this.v(e,_,h,i,f).then((r=>(__PRIVATE_logDebug(ie,`Received RPC '${e}' ${a}: `,r),r)),(r=>{throw __PRIVATE_logWarn(ie,`RPC '${e}' ${a} failed with error: `,r,"url: ",_,"request:",i),r}))}D(e,r,i,s,o,a){return this.I(e,r,i,s,o)}F(e,r,i){e["X-Goog-Api-Client"]=function __PRIVATE_getGoogApiClientValue(){return"gl-js/ fire/"+V}(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),r&&r.headers.forEach(((r,i)=>e[i]=r)),i&&i.headers.forEach(((r,i)=>e[i]=r))}p(e,r){const i=se[e];let s=`${this.V}/v1/${r}:${i}`;return this.databaseInfo.apiKey&&(s=`${s}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`),s}terminate(){}}var oe,ae;function __PRIVATE_mapCodeFromHttpStatus(e){if(void 0===e)return __PRIVATE_logError("RPC_ERROR","HTTP error has no status"),S;switch(e){case 200:return R;case 400:return j;case 401:return q;case 403:return L;case 404:return O;case 409:return $;case 416:return z;case 429:return U;case 499:return w;case 500:return S;case 501:return Q;case 503:return K;case 504:return N;default:return e>=200&&e<300?R:e>=400&&e<500?j:e>=500&&e<600?W:S}}(ae=oe||(oe={}))[ae.OK=0]="OK",ae[ae.CANCELLED=1]="CANCELLED",ae[ae.UNKNOWN=2]="UNKNOWN",ae[ae.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",ae[ae.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",ae[ae.NOT_FOUND=5]="NOT_FOUND",ae[ae.ALREADY_EXISTS=6]="ALREADY_EXISTS",ae[ae.PERMISSION_DENIED=7]="PERMISSION_DENIED",ae[ae.UNAUTHENTICATED=16]="UNAUTHENTICATED",ae[ae.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",ae[ae.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",ae[ae.ABORTED=10]="ABORTED",ae[ae.OUT_OF_RANGE=11]="OUT_OF_RANGE",ae[ae.UNIMPLEMENTED=12]="UNIMPLEMENTED",ae[ae.INTERNAL=13]="INTERNAL",ae[ae.UNAVAILABLE=14]="UNAVAILABLE",ae[ae.DATA_LOSS=15]="DATA_LOSS";class __PRIVATE_FetchConnection extends __PRIVATE_RestConnection{N(e,r){throw new Error("Not supported by FetchConnection")}async v(e,r,i,s,o){const a=JSON.stringify(s);let _;try{const e={method:"POST",headers:i,body:a};o&&(e.credentials="include"),_=await fetch(r,e)}catch(e){const r=e;throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(r.status),"Request failed with error: "+r.statusText)}if(!_.ok){let e=await _.json();Array.isArray(e)&&(e=e[0]);const r=e?.error?.message;throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(_.status),`Request failed with error: ${r??_.statusText}`)}return _.json()}}function __PRIVATE_objectSize(e){let r=0;for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&r++;return r}function forEach(e,r){for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&r(i,e[i])}class __PRIVATE_Base64DecodeError extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class ByteString{constructor(e){this.binaryString=e}static fromBase64String(e){const r=function __PRIVATE_decodeBase64(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new __PRIVATE_Base64DecodeError("Invalid base64 string: "+e):e}}(e);return new ByteString(r)}static fromUint8Array(e){const r=function __PRIVATE_binaryStringFromUint8Array(e){let r="";for(let i=0;i<e.length;++i)r+=String.fromCharCode(e[i]);return r}(e);return new ByteString(r)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return function __PRIVATE_encodeBase64(e){return btoa(e)}(this.binaryString)}toUint8Array(){return function __PRIVATE_uint8ArrayFromBinaryString(e){const r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i);return r}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return __PRIVATE_primitiveComparator(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ByteString.EMPTY_BYTE_STRING=new ByteString("");const ue=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function __PRIVATE_normalizeTimestamp(e){if(__PRIVATE_hardAssert(!!e,39018),"string"==typeof e){let r=0;const i=ue.exec(e);if(__PRIVATE_hardAssert(!!i,46558,{timestamp:e}),i[1]){let e=i[1];e=(e+"000000000").substr(0,9),r=Number(e)}const s=new Date(e);return{seconds:Math.floor(s.getTime()/1e3),nanos:r}}return{seconds:__PRIVATE_normalizeNumber(e.seconds),nanos:__PRIVATE_normalizeNumber(e.nanos)}}function __PRIVATE_normalizeNumber(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function __PRIVATE_normalizeByteString(e){return"string"==typeof e?ByteString.fromBase64String(e):ByteString.fromUint8Array(e)}function property(e,r){const i={typeString:e};return r&&(i.value=r),i}function __PRIVATE_validateJSON(e,r){if(!__PRIVATE_isPlainObject(e))throw new FirestoreError(b,"JSON must be an object");let i;for(const s in r)if(r[s]){const o=r[s].typeString,a="value"in r[s]?{value:r[s].value}:void 0;if(!(s in e)){i=`JSON missing required field: '${s}'`;break}const _=e[s];if(o&&typeof _!==o){i=`JSON field '${s}' must be a ${o}.`;break}if(void 0!==a&&_!==a.value){i=`Expected '${s}' field to equal '${a.value}'`;break}}if(i)throw new FirestoreError(b,i);return!0}const le=-62135596800,ce=1e6;class Timestamp{static now(){return Timestamp.fromMillis(Date.now())}static fromDate(e){return Timestamp.fromMillis(e.getTime())}static fromMillis(e){const r=Math.floor(e/1e3),i=Math.floor((e-1e3*r)*ce);return new Timestamp(r,i)}constructor(e,r){if(this.seconds=e,this.nanoseconds=r,r<0)throw new FirestoreError(b,"Timestamp nanoseconds out of range: "+r);if(r>=1e9)throw new FirestoreError(b,"Timestamp nanoseconds out of range: "+r);if(e<le)throw new FirestoreError(b,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new FirestoreError(b,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/ce}_compareTo(e){return this.seconds===e.seconds?__PRIVATE_primitiveComparator(this.nanoseconds,e.nanoseconds):__PRIVATE_primitiveComparator(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:Timestamp._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(__PRIVATE_validateJSON(e,Timestamp._jsonSchema))return new Timestamp(e.seconds,e.nanoseconds)}valueOf(){const e=this.seconds-le;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}function __PRIVATE_isServerTimestamp(e){const r=(e?.mapValue?.fields||{}).__type__?.stringValue;return"server_timestamp"===r}function __PRIVATE_getPreviousValue(e){const r=e.mapValue.fields.__previous_value__;return __PRIVATE_isServerTimestamp(r)?__PRIVATE_getPreviousValue(r):r}function __PRIVATE_getLocalWriteTime(e){const r=__PRIVATE_normalizeTimestamp(e.mapValue.fields.__local_write_time__.timestampValue);return new Timestamp(r.seconds,r.nanos)}Timestamp._jsonSchemaVersion="firestore/timestamp/1.0",Timestamp._jsonSchema={type:property("string",Timestamp._jsonSchemaVersion),seconds:property("number"),nanoseconds:property("number")};const _e="__type__",he="__max__",de={fields:{__type__:{stringValue:he}}},fe="__vector__",me="value";function __PRIVATE_typeOrder(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?__PRIVATE_isServerTimestamp(e)?4:function __PRIVATE_isMaxValue(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===he}(e)?9007199254740991:function __PRIVATE_isVectorValue(e){const r=(e?.mapValue?.fields||{})[_e]?.stringValue;return r===fe}(e)?10:11:fail(28295,{value:e})}function __PRIVATE_valueEquals(e,r,i){if(e===r)return!0;const s=__PRIVATE_typeOrder(e);if(s!==__PRIVATE_typeOrder(r))return!1;switch(s){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===r.booleanValue;case 4:return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(r));case 3:return function __PRIVATE_timestampEquals(e,r){if("string"==typeof e.timestampValue&&"string"==typeof r.timestampValue&&e.timestampValue.length===r.timestampValue.length)return e.timestampValue===r.timestampValue;const i=__PRIVATE_normalizeTimestamp(e.timestampValue),s=__PRIVATE_normalizeTimestamp(r.timestampValue);return i.seconds===s.seconds&&i.nanos===s.nanos}(e,r);case 5:return e.stringValue===r.stringValue;case 6:return function __PRIVATE_blobEquals(e,r){return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(r.bytesValue))}(e,r);case 7:return e.referenceValue===r.referenceValue;case 8:return function __PRIVATE_geoPointEquals(e,r){return __PRIVATE_normalizeNumber(e.geoPointValue.latitude)===__PRIVATE_normalizeNumber(r.geoPointValue.latitude)&&__PRIVATE_normalizeNumber(e.geoPointValue.longitude)===__PRIVATE_normalizeNumber(r.geoPointValue.longitude)}(e,r);case 2:return function __PRIVATE_numberEquals(e,r,i){if("integerValue"in e&&"integerValue"in r)return __PRIVATE_normalizeNumber(e.integerValue)===__PRIVATE_normalizeNumber(r.integerValue);let s,o;if("doubleValue"in e&&"doubleValue"in r)s=__PRIVATE_normalizeNumber(e.doubleValue),o=__PRIVATE_normalizeNumber(r.doubleValue);else{if(!i?.S)return!1;s=__PRIVATE_normalizeNumber(e.integerValue??e.doubleValue),o=__PRIVATE_normalizeNumber(r.integerValue??r.doubleValue)}return s===o?!!i?.C||__PRIVATE_isNegativeZero(s)===__PRIVATE_isNegativeZero(o):!(void 0!==i&&!i.O)&&isNaN(s)&&isNaN(o)}(e,r,i);case 9:return __PRIVATE_arrayEquals(e.arrayValue.values||[],r.arrayValue.values||[],((e,r)=>__PRIVATE_valueEquals(e,r,i)));case 10:case 11:return function __PRIVATE_objectEquals(e,r,i){const s=e.mapValue.fields||{},o=r.mapValue.fields||{};if(__PRIVATE_objectSize(s)!==__PRIVATE_objectSize(o))return!1;for(const e in s)if(s.hasOwnProperty(e)&&(void 0===o[e]||!__PRIVATE_valueEquals(s[e],o[e],i)))return!1;return!0}(e,r,i);default:return fail(52216,{left:e})}}function __PRIVATE_arrayValueContains(e,r){return void 0!==(e.values||[]).find((e=>__PRIVATE_valueEquals(e,r)))}function __PRIVATE_valueCompare(e,r){if(e===r)return 0;const i=__PRIVATE_typeOrder(e),s=__PRIVATE_typeOrder(r);if(i!==s)return __PRIVATE_primitiveComparator(i,s);switch(i){case 0:case 9007199254740991:return 0;case 1:return __PRIVATE_primitiveComparator(e.booleanValue,r.booleanValue);case 2:return function __PRIVATE_compareNumbers(e,r){const i=__PRIVATE_normalizeNumber(e.integerValue||e.doubleValue),s=__PRIVATE_normalizeNumber(r.integerValue||r.doubleValue);return i<s?-1:i>s?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1}(e,r);case 3:return __PRIVATE_compareTimestamps(e.timestampValue,r.timestampValue);case 4:return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e),__PRIVATE_getLocalWriteTime(r));case 5:return __PRIVATE_compareUtf8Strings(e.stringValue,r.stringValue);case 6:return function __PRIVATE_compareBlobs(e,r){const i=__PRIVATE_normalizeByteString(e),s=__PRIVATE_normalizeByteString(r);return i.compareTo(s)}(e.bytesValue,r.bytesValue);case 7:return function __PRIVATE_compareReferences(e,r){const i=e.split("/"),s=r.split("/");for(let e=0;e<i.length&&e<s.length;e++){const r=__PRIVATE_primitiveComparator(i[e],s[e]);if(0!==r)return r}return __PRIVATE_primitiveComparator(i.length,s.length)}(e.referenceValue,r.referenceValue);case 8:return function __PRIVATE_compareGeoPoints(e,r){const i=__PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(r.latitude));return 0!==i?i:__PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude),__PRIVATE_normalizeNumber(r.longitude))}(e.geoPointValue,r.geoPointValue);case 9:return __PRIVATE_compareArrays(e.arrayValue,r.arrayValue);case 10:return function __PRIVATE_compareVectors(e,r){const i=e.fields||{},s=r.fields||{},o=i[me]?.arrayValue,a=s[me]?.arrayValue,_=__PRIVATE_primitiveComparator(o?.values?.length||0,a?.values?.length||0);return 0!==_?_:__PRIVATE_compareArrays(o,a)}(e.mapValue,r.mapValue);case 11:return function __PRIVATE_compareMaps(e,r){if(e===de&&r===de)return 0;if(e===de)return 1;if(r===de)return-1;const i=e.fields||{},s=Object.keys(i),o=r.fields||{},a=Object.keys(o);s.sort(),a.sort();for(let e=0;e<s.length&&e<a.length;++e){const r=__PRIVATE_compareUtf8Strings(s[e],a[e]);if(0!==r)return r;const _=__PRIVATE_valueCompare(i[s[e]],o[a[e]]);if(0!==_)return _}return __PRIVATE_primitiveComparator(s.length,a.length)}(e.mapValue,r.mapValue);default:throw fail(23264,{q:i})}}function __PRIVATE_compareTimestamps(e,r){if("string"==typeof e&&"string"==typeof r&&e.length===r.length)return __PRIVATE_primitiveComparator(e,r);const i=__PRIVATE_normalizeTimestamp(e),s=__PRIVATE_normalizeTimestamp(r),o=__PRIVATE_primitiveComparator(i.seconds,s.seconds);return 0!==o?o:__PRIVATE_primitiveComparator(i.nanos,s.nanos)}function __PRIVATE_compareArrays(e,r){const i=e.values||[],s=r.values||[];for(let e=0;e<i.length&&e<s.length;++e){const r=__PRIVATE_valueCompare(i[e],s[e]);if(void 0!==r&&0!==r)return r}return __PRIVATE_primitiveComparator(i.length,s.length)}function __PRIVATE_refValue(e,r){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${r.path.canonicalString()}`}}function isArray(e){return!!e&&"arrayValue"in e}function __PRIVATE_isNullValue(e){return!!e&&"nullValue"in e}function __PRIVATE_isNanValue(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function __PRIVATE_isMapValue(e){return!!e&&"mapValue"in e}function __PRIVATE_deepClone(e){if(e.geoPointValue)return{geoPointValue:{...e.geoPointValue}};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:{...e.timestampValue}};if(e.mapValue){const r={mapValue:{fields:{}}};return forEach(e.mapValue.fields,((e,i)=>r.mapValue.fields[e]=__PRIVATE_deepClone(i))),r}if(e.arrayValue){const r={arrayValue:{values:[]}};for(let i=0;i<(e.arrayValue.values||[]).length;++i)r.arrayValue.values[i]=__PRIVATE_deepClone(e.arrayValue.values[i]);return r}return{...e}}class Bound{constructor(e,r){this.position=e,this.inclusive=r}}function __PRIVATE_boundEquals(e,r){if(null===e)return null===r;if(null===r)return!1;if(e.inclusive!==r.inclusive||e.position.length!==r.position.length)return!1;for(let i=0;i<e.position.length;i++)if(!__PRIVATE_valueEquals(e.position[i],r.position[i]))return!1;return!0}class Filter{}class FieldFilter extends Filter{constructor(e,r,i){super(),this.field=e,this.op=r,this.value=i}static create(e,r,i){return e.isKeyField()?"in"===r||"not-in"===r?this.createKeyFieldInFilter(e,r,i):new __PRIVATE_KeyFieldFilter(e,r,i):"array-contains"===r?new __PRIVATE_ArrayContainsFilter(e,i):"in"===r?new __PRIVATE_InFilter(e,i):"not-in"===r?new __PRIVATE_NotInFilter(e,i):"array-contains-any"===r?new __PRIVATE_ArrayContainsAnyFilter(e,i):new FieldFilter(e,r,i)}static createKeyFieldInFilter(e,r,i){return"in"===r?new __PRIVATE_KeyFieldInFilter(e,i):new __PRIVATE_KeyFieldNotInFilter(e,i)}matches(e){const r=e.data.field(this.field);return"!="===this.op?null!==r&&void 0===r.nullValue&&this.matchesComparison(__PRIVATE_valueCompare(r,this.value)):null!==r&&__PRIVATE_typeOrder(this.value)===__PRIVATE_typeOrder(r)&&this.matchesComparison(__PRIVATE_valueCompare(r,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return fail(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class CompositeFilter extends Filter{constructor(e,r){super(),this.filters=e,this.op=r,this.L=null}static create(e,r){return new CompositeFilter(e,r)}matches(e){return function __PRIVATE_compositeFilterIsConjunction(e){return"and"===e.op}(this)?void 0===this.filters.find((r=>!r.matches(e))):void 0!==this.filters.find((r=>r.matches(e)))}getFlattenedFilters(){return null!==this.L||(this.L=this.filters.reduce(((e,r)=>e.concat(r.getFlattenedFilters())),[])),this.L}getFilters(){return Object.assign([],this.filters)}}function __PRIVATE_filterEquals(e,r){return e instanceof FieldFilter?function __PRIVATE_fieldFilterEquals(e,r){return r instanceof FieldFilter&&e.op===r.op&&e.field.isEqual(r.field)&&__PRIVATE_valueEquals(e.value,r.value)}(e,r):e instanceof CompositeFilter?function __PRIVATE_compositeFilterEquals(e,r){return r instanceof CompositeFilter&&e.op===r.op&&e.filters.length===r.filters.length&&e.filters.reduce(((e,i,s)=>e&&__PRIVATE_filterEquals(i,r.filters[s])),!0)}(e,r):void fail(19439)}class __PRIVATE_KeyFieldFilter extends FieldFilter{constructor(e,r,i){super(e,r,i),this.key=DocumentKey.fromName(i.referenceValue)}matches(e){const r=DocumentKey.comparator(e.key,this.key);return this.matchesComparison(r)}}class __PRIVATE_KeyFieldInFilter extends FieldFilter{constructor(e,r){super(e,"in",r),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue("in",r)}matches(e){return this.keys.some((r=>r.isEqual(e.key)))}}class __PRIVATE_KeyFieldNotInFilter extends FieldFilter{constructor(e,r){super(e,"not-in",r),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue("not-in",r)}matches(e){return!this.keys.some((r=>r.isEqual(e.key)))}}function __PRIVATE_extractDocumentKeysFromArrayValue(e,r){return(r.arrayValue?.values||[]).map((e=>DocumentKey.fromName(e.referenceValue)))}class __PRIVATE_ArrayContainsFilter extends FieldFilter{constructor(e,r){super(e,"array-contains",r)}matches(e){const r=e.data.field(this.field);return isArray(r)&&__PRIVATE_arrayValueContains(r.arrayValue,this.value)}}class __PRIVATE_InFilter extends FieldFilter{constructor(e,r){super(e,"in",r)}matches(e){const r=e.data.field(this.field);return null!==r&&__PRIVATE_arrayValueContains(this.value.arrayValue,r)}}class __PRIVATE_NotInFilter extends FieldFilter{constructor(e,r){super(e,"not-in",r)}matches(e){if(__PRIVATE_arrayValueContains(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const r=e.data.field(this.field);return null!==r&&void 0===r.nullValue&&!__PRIVATE_arrayValueContains(this.value.arrayValue,r)}}class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter{constructor(e,r){super(e,"array-contains-any",r)}matches(e){const r=e.data.field(this.field);return!(!isArray(r)||!r.arrayValue.values)&&r.arrayValue.values.some((e=>__PRIVATE_arrayValueContains(this.value.arrayValue,e)))}}class OrderBy{constructor(e,r="asc"){this.field=e,this.dir=r}}function __PRIVATE_orderByEquals(e,r){return e.dir===r.dir&&e.field.isEqual(r.field)}class SnapshotVersion{static fromTimestamp(e){return new SnapshotVersion(e)}static min(){return new SnapshotVersion(new Timestamp(0,0))}static max(){return new SnapshotVersion(new Timestamp(253402300799,999999999))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class SortedMap{constructor(e,r){this.comparator=e,this.root=r||LLRBNode.EMPTY}insert(e,r){return new SortedMap(this.comparator,this.root.insert(e,r,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}remove(e){return new SortedMap(this.comparator,this.root.remove(e,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}get(e){let r=this.root;for(;!r.isEmpty();){const i=this.comparator(e,r.key);if(0===i)return r.value;i<0?r=r.left:i>0&&(r=r.right)}return null}indexOf(e){let r=0,i=this.root;for(;!i.isEmpty();){const s=this.comparator(e,i.key);if(0===s)return r+i.left.size;s<0?i=i.left:(r+=i.left.size+1,i=i.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((r,i)=>(e(r,i),!1)))}toString(){const e=[];return this.inorderTraversal(((r,i)=>(e.push(`${r}:${i}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new SortedMapIterator(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!1)}getReverseIterator(){return new SortedMapIterator(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!0)}}class SortedMapIterator{constructor(e,r,i,s){this.isReverse=s,this.nodeStack=[];let o=1;for(;!e.isEmpty();)if(o=r?i(e.key,r):1,r&&s&&(o*=-1),o<0)e=this.isReverse?e.left:e.right;else{if(0===o){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const r={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return r}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class LLRBNode{constructor(e,r,i,s,o){this.key=e,this.value=r,this.color=null!=i?i:LLRBNode.RED,this.left=null!=s?s:LLRBNode.EMPTY,this.right=null!=o?o:LLRBNode.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,r,i,s,o){return new LLRBNode(null!=e?e:this.key,null!=r?r:this.value,null!=i?i:this.color,null!=s?s:this.left,null!=o?o:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,r,i){let s=this;const o=i(e,s.key);return s=o<0?s.copy(null,null,null,s.left.insert(e,r,i),null):0===o?s.copy(null,r,null,null,null):s.copy(null,null,null,null,s.right.insert(e,r,i)),s.fixUp()}removeMin(){if(this.left.isEmpty())return LLRBNode.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,r){let i,s=this;if(r(e,s.key)<0)s.left.isEmpty()||s.left.isRed()||s.left.left.isRed()||(s=s.moveRedLeft()),s=s.copy(null,null,null,s.left.remove(e,r),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),0===r(e,s.key)){if(s.right.isEmpty())return LLRBNode.EMPTY;i=s.right.min(),s=s.copy(i.key,i.value,null,null,s.right.removeMin())}s=s.copy(null,null,null,null,s.right.remove(e,r))}return s.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,LLRBNode.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,LLRBNode.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),r=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,r)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw fail(43730,{key:this.key,value:this.value});if(this.right.isRed())throw fail(14113,{key:this.key,value:this.value});const e=this.left.check();if(e!==this.right.check())throw fail(27949);return e+(this.isRed()?0:1)}}LLRBNode.EMPTY=null,LLRBNode.RED=!0,LLRBNode.BLACK=!1,LLRBNode.EMPTY=new class LLRBEmptyNode{constructor(){this.size=0}get key(){throw fail(57766)}get value(){throw fail(16141)}get color(){throw fail(16727)}get left(){throw fail(29726)}get right(){throw fail(36894)}copy(e,r,i,s,o){return this}insert(e,r,i){return new LLRBNode(e,r)}remove(e,r){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class SortedSet{constructor(e){this.comparator=e,this.data=new SortedMap(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal(((r,i)=>(e(r),!1)))}forEachInRange(e,r){const i=this.data.getIteratorFrom(e[0]);for(;i.hasNext();){const s=i.getNext();if(this.comparator(s.key,e[1])>=0)return;r(s.key)}}forEachWhile(e,r){let i;for(i=void 0!==r?this.data.getIteratorFrom(r):this.data.getIterator();i.hasNext();)if(!e(i.getNext().key))return}firstAfterOrEqual(e){const r=this.data.getIteratorFrom(e);return r.hasNext()?r.getNext().key:null}getIterator(){return new SortedSetIterator(this.data.getIterator())}getIteratorFrom(e){return new SortedSetIterator(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let r=this;return r.size<e.size&&(r=e,e=this),e.forEach((e=>{r=r.add(e)})),r}isEqual(e){if(!(e instanceof SortedSet))return!1;if(this.size!==e.size)return!1;const r=this.data.getIterator(),i=e.data.getIterator();for(;r.hasNext();){const e=r.getNext().key,s=i.getNext().key;if(0!==this.comparator(e,s))return!1}return!0}toArray(){const e=[];return this.forEach((r=>{e.push(r)})),e}toString(){const e=[];return this.forEach((r=>e.push(r))),"SortedSet("+e.toString()+")"}copy(e){const r=new SortedSet(this.comparator);return r.data=e,r}}class SortedSetIterator{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class FieldMask{constructor(e){this.fields=e,e.sort(FieldPath$1.comparator)}static empty(){return new FieldMask([])}unionWith(e){let r=new SortedSet(FieldPath$1.comparator);for(const e of this.fields)r=r.add(e);for(const i of e)r=r.add(i);return new FieldMask(r.toArray())}covers(e){for(const r of this.fields)if(r.isPrefixOf(e))return!0;return!1}isEqual(e){return __PRIVATE_arrayEquals(this.fields,e.fields,((e,r)=>e.isEqual(r)))}}class ObjectValue{constructor(e){this.value=e}static empty(){return new ObjectValue({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let r=this.value;for(let i=0;i<e.length-1;++i)if(r=(r.mapValue.fields||{})[e.get(i)],!__PRIVATE_isMapValue(r))return null;return r=(r.mapValue.fields||{})[e.lastSegment()],r||null}}set(e,r){this.getFieldsMap(e.popLast())[e.lastSegment()]=__PRIVATE_deepClone(r)}setAll(e){let r=FieldPath$1.emptyPath(),i={},s=[];e.forEach(((e,o)=>{if(!r.isImmediateParentOf(o)){const e=this.getFieldsMap(r);this.applyChanges(e,i,s),i={},s=[],r=o.popLast()}e?i[o.lastSegment()]=__PRIVATE_deepClone(e):s.push(o.lastSegment())}));const o=this.getFieldsMap(r);this.applyChanges(o,i,s)}delete(e){const r=this.field(e.popLast());__PRIVATE_isMapValue(r)&&r.mapValue.fields&&delete r.mapValue.fields[e.lastSegment()]}isEqual(e){return __PRIVATE_valueEquals(this.value,e.value)}getFieldsMap(e){let r=this.value;r.mapValue.fields||(r.mapValue={fields:{}});for(let i=0;i<e.length;++i){let s=r.mapValue.fields[e.get(i)];__PRIVATE_isMapValue(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},r.mapValue.fields[e.get(i)]=s),r=s}return r.mapValue.fields}applyChanges(e,r,i){forEach(r,((r,i)=>e[r]=i));for(const r of i)delete e[r]}clone(){return new ObjectValue(__PRIVATE_deepClone(this.value))}}class MutableDocument{constructor(e,r,i,s,o,a,_){this.key=e,this.documentType=r,this.version=i,this.readTime=s,this.createTime=o,this.data=a,this.documentState=_}static newInvalidDocument(e){return new MutableDocument(e,0,SnapshotVersion.min(),SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),0)}static newFoundDocument(e,r,i,s){return new MutableDocument(e,1,r,SnapshotVersion.min(),i,s,0)}static newNoDocument(e,r){return new MutableDocument(e,2,r,SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),0)}static newUnknownDocument(e,r){return new MutableDocument(e,3,r,SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),2)}convertToFoundDocument(e,r){return!this.createTime.isEqual(SnapshotVersion.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=r,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=ObjectValue.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ObjectValue.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=SnapshotVersion.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof MutableDocument&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new MutableDocument(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class __PRIVATE_TargetImpl{constructor(e,r=null,i=[],s=[],o=null,a=null,_=null){this.path=e,this.collectionGroup=r,this.orderBy=i,this.filters=s,this.limit=o,this.startAt=a,this.endAt=_,this.$=null}}function __PRIVATE_newTarget(e,r=null,i=[],s=[],o=null,a=null,_=null){return new __PRIVATE_TargetImpl(e,r,i,s,o,a,_)}class __PRIVATE_QueryImpl{constructor(e,r=null,i=[],s=[],o=null,a="F",_=null,h=null){this.path=e,this.collectionGroup=r,this.explicitOrderBy=i,this.filters=s,this.limit=o,this.limitType=a,this.startAt=_,this.endAt=h,this.B=null,this.M=null,this.U=null,this.startAt,this.endAt}}function __PRIVATE_isCollectionGroupQuery(e){return null!==e.collectionGroup}function __PRIVATE_queryNormalizedOrderBy(e){const r=__PRIVATE_debugCast(e);if(null===r.B){r.B=[];const e=new Set;for(const i of r.explicitOrderBy)r.B.push(i),e.add(i.field.canonicalString());const i=r.explicitOrderBy.length>0?r.explicitOrderBy[r.explicitOrderBy.length-1].dir:"asc",s=function __PRIVATE_getInequalityFilterFields(e){let r=new SortedSet(FieldPath$1.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(r=r.add(e.field))}))})),r}(r);s.forEach((s=>{e.has(s.canonicalString())||s.isKeyField()||r.B.push(new OrderBy(s,i))})),e.has(FieldPath$1.keyField().canonicalString())||r.B.push(new OrderBy(FieldPath$1.keyField(),i))}return r.B}function __PRIVATE_queryToTarget(e){const r=__PRIVATE_debugCast(e);return r.M||(r.M=__PRIVATE__queryToTarget(r,__PRIVATE_queryNormalizedOrderBy(e))),r.M}function __PRIVATE__queryToTarget(e,r){if("F"===e.limitType)return __PRIVATE_newTarget(e.path,e.collectionGroup,r,e.filters,e.limit,e.startAt,e.endAt);{r=r.map((e=>{const r="desc"===e.dir?"asc":"desc";return new OrderBy(e.field,r)}));const i=e.endAt?new Bound(e.endAt.position,e.endAt.inclusive):null,s=e.startAt?new Bound(e.startAt.position,e.startAt.inclusive):null;return __PRIVATE_newTarget(e.path,e.collectionGroup,r,e.filters,e.limit,i,s)}}function __PRIVATE_queryWithAddedFilter(e,r){const i=e.filters.concat([r]);return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),i,e.limit,e.limitType,e.startAt,e.endAt)}function __PRIVATE_toDouble(e,r){if(e.useProto3Json){if(isNaN(r))return{doubleValue:"NaN"};if(r===1/0)return{doubleValue:"Infinity"};if(r===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:__PRIVATE_isNegativeZero(r)?"-0":r}}function toNumber(e,r,i){return Number.isInteger(r)&&i?.preferIntegers||function isSafeInteger(e){return"number"==typeof e&&Number.isInteger(e)&&!__PRIVATE_isNegativeZero(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}(r)?function __PRIVATE_toInteger(e){return{integerValue:""+e}}(r):__PRIVATE_toDouble(e,r)}class TransformOperation{constructor(){this._=void 0}}class __PRIVATE_ServerTimestampTransform extends TransformOperation{}class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}}class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}}class __PRIVATE_NumericTransformOperation extends TransformOperation{constructor(e,r){super(),this.serializer=e,this.k=r}}class __PRIVATE_NumericIncrementTransformOperation extends __PRIVATE_NumericTransformOperation{}class __PRIVATE_NumericMinimumTransformOperation extends __PRIVATE_NumericTransformOperation{}class __PRIVATE_NumericMaximumTransformOperation extends __PRIVATE_NumericTransformOperation{}class FieldTransform{constructor(e,r){this.field=e,this.transform=r}}class Precondition{constructor(e,r){this.updateTime=e,this.exists=r}static none(){return new Precondition}static exists(e){return new Precondition(void 0,e)}static updateTime(e){return new Precondition(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}class Mutation{}class __PRIVATE_SetMutation extends Mutation{constructor(e,r,i,s=[]){super(),this.key=e,this.value=r,this.precondition=i,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}}class __PRIVATE_PatchMutation extends Mutation{constructor(e,r,i,s,o=[]){super(),this.key=e,this.data=r,this.fieldMask=i,this.precondition=s,this.fieldTransforms=o,this.type=1}getFieldMask(){return this.fieldMask}}class __PRIVATE_DeleteMutation extends Mutation{constructor(e,r){super(),this.key=e,this.precondition=r,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class __PRIVATE_VerifyMutation extends Mutation{constructor(e,r){super(),this.key=e,this.precondition=r,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}const pe={asc:"ASCENDING",desc:"DESCENDING"},ge={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},Ee={and:"AND",or:"OR"};class JsonProtoSerializer{constructor(e,r){this.databaseId=e,this.useProto3Json=r}}function toTimestamp(e,r){return e.useProto3Json?`${new Date(1e3*r.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+r.nanoseconds).slice(-9)}Z`:{seconds:""+r.seconds,nanos:r.nanoseconds}}function __PRIVATE_toBytes(e,r){return e.useProto3Json?r.toBase64():r.toUint8Array()}function __PRIVATE_toVersion(e,r){return toTimestamp(e,r.toTimestamp())}function __PRIVATE_fromVersion(e){return __PRIVATE_hardAssert(!!e,49232),SnapshotVersion.fromTimestamp(function fromTimestamp(e){const r=__PRIVATE_normalizeTimestamp(e);return new Timestamp(r.seconds,r.nanos)}(e))}function __PRIVATE_toResourceName(e,r){return __PRIVATE_toResourcePath(e,r).canonicalString()}function __PRIVATE_toResourcePath(e,r){const i=function __PRIVATE_fullyQualifiedPrefixPath(e){return new ResourcePath(["projects",e.projectId,"databases",e.database])}(e).child("documents");return void 0===r?i:i.child(r)}function __PRIVATE_toName(e,r){return __PRIVATE_toResourceName(e.databaseId,r.path)}function fromName(e,r){const i=function __PRIVATE_fromResourceName(e){const r=ResourcePath.fromString(e);return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(r),10190,{key:r.toString()}),r}(r);if(i.get(1)!==e.databaseId.projectId)throw new FirestoreError(b,"Tried to deserialize key from different project: "+i.get(1)+" vs "+e.databaseId.projectId);if(i.get(3)!==e.databaseId.database)throw new FirestoreError(b,"Tried to deserialize key from different database: "+i.get(3)+" vs "+e.databaseId.database);return new DocumentKey(function __PRIVATE_extractLocalPathFromResourceName(e){return __PRIVATE_hardAssert(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}(i))}function __PRIVATE_toMutationDocument(e,r,i){return{name:__PRIVATE_toName(e,r),fields:i.value.mapValue.fields}}function __PRIVATE_toQueryTarget(e,r){const i={structuredQuery:{}},s=r.path;let o;null!==r.collectionGroup?(o=s,i.structuredQuery.from=[{collectionId:r.collectionGroup,allDescendants:!0}]):(o=s.popLast(),i.structuredQuery.from=[{collectionId:s.lastSegment()}]),i.parent=function __PRIVATE_toQueryPath(e,r){return __PRIVATE_toResourceName(e.databaseId,r)}(e,o);const a=function __PRIVATE_toFilters(e){if(0!==e.length)return __PRIVATE_toFilter(CompositeFilter.create(e,"and"))}(r.filters);a&&(i.structuredQuery.where=a);const _=function __PRIVATE_toOrder(e){if(0!==e.length)return e.map((e=>function __PRIVATE_toPropertyOrder(e){return{field:__PRIVATE_toFieldPathReference(e.field),direction:__PRIVATE_toDirection(e.dir)}}(e)))}(r.orderBy);_&&(i.structuredQuery.orderBy=_);const h=function __PRIVATE_toInt32Proto(e,r){return e.useProto3Json||__PRIVATE_isNullOrUndefined(r)?r:{value:r}}(e,r.limit);return null!==h&&(i.structuredQuery.limit=h),r.startAt&&(i.structuredQuery.startAt=function __PRIVATE_toStartAtCursor(e){return{before:e.inclusive,values:e.position}}(r.startAt)),r.endAt&&(i.structuredQuery.endAt=function __PRIVATE_toEndAtCursor(e){return{before:!e.inclusive,values:e.position}}(r.endAt)),{K:i,parent:o}}function __PRIVATE_toDirection(e){return pe[e]}function __PRIVATE_toOperatorName(e){return ge[e]}function __PRIVATE_toCompositeOperatorName(e){return Ee[e]}function __PRIVATE_toFieldPathReference(e){return{fieldPath:e.canonicalString()}}function __PRIVATE_toFilter(e){return e instanceof FieldFilter?function __PRIVATE_toUnaryOrFieldFilter(e){if("=="===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NAN"}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NOT_NAN"}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:__PRIVATE_toOperatorName(e.op),value:e.value}}}(e):e instanceof CompositeFilter?function __PRIVATE_toCompositeFilter(e){const r=e.getFilters().map((e=>__PRIVATE_toFilter(e)));return 1===r.length?r[0]:{compositeFilter:{op:__PRIVATE_toCompositeOperatorName(e.op),filters:r}}}(e):fail(54877,{filter:e})}function __PRIVATE_toDocumentMask(e){const r=[];return e.fields.forEach((e=>r.push(e.canonicalString()))),{fieldPaths:r}}function __PRIVATE_isValidResourceName(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function __PRIVATE_isProtoValueSerializable(e){return!!e&&"function"==typeof e._toProto&&"ProtoValue"===e._protoValueType}function __PRIVATE_newSerializer(e){return new JsonProtoSerializer(e,!0)}class Datastore{}class __PRIVATE_DatastoreImpl extends Datastore{constructor(e,r,i,s){super(),this.authCredentials=e,this.appCheckCredentials=r,this.connection=i,this.serializer=s,this.G=!1}W(){if(this.G)throw new FirestoreError(j,"The client has already been terminated.")}I(e,r,i,s){return this.W(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([o,a])=>this.connection.I(e,__PRIVATE_toResourcePath(r,i),s,o,a))).catch((e=>{throw"FirebaseError"===e.name?(e.code===q&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FirestoreError(S,e.toString())}))}D(e,r,i,s,o){return this.W(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([a,_])=>this.connection.D(e,__PRIVATE_toResourcePath(r,i),s,a,_,o))).catch((e=>{throw"FirebaseError"===e.name?(e.code===q&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FirestoreError(S,e.toString())}))}terminate(){this.G=!0,this.connection.terminate()}}async function __PRIVATE_invokeCommitRpc(e,r){const i=__PRIVATE_debugCast(e),s={writes:r.map((e=>function toMutation(e,r){let i;if(r instanceof __PRIVATE_SetMutation)i={update:__PRIVATE_toMutationDocument(e,r.key,r.value)};else if(r instanceof __PRIVATE_DeleteMutation)i={delete:__PRIVATE_toName(e,r.key)};else if(r instanceof __PRIVATE_PatchMutation)i={update:__PRIVATE_toMutationDocument(e,r.key,r.data),updateMask:__PRIVATE_toDocumentMask(r.fieldMask)};else{if(!(r instanceof __PRIVATE_VerifyMutation))return fail(16599,{j:r.type});i={verify:__PRIVATE_toName(e,r.key)}}return r.fieldTransforms.length>0&&(i.updateTransforms=r.fieldTransforms.map((e=>function __PRIVATE_toFieldTransform(e,r){const i=r.transform;if(i instanceof __PRIVATE_ServerTimestampTransform)return{fieldPath:r.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(i instanceof __PRIVATE_ArrayUnionTransformOperation)return{fieldPath:r.field.canonicalString(),appendMissingElements:{values:i.elements}};if(i instanceof __PRIVATE_ArrayRemoveTransformOperation)return{fieldPath:r.field.canonicalString(),removeAllFromArray:{values:i.elements}};if(i instanceof __PRIVATE_NumericIncrementTransformOperation)return{fieldPath:r.field.canonicalString(),increment:i.k};if(i instanceof __PRIVATE_NumericMinimumTransformOperation)return{fieldPath:r.field.canonicalString(),minimum:i.k};if(i instanceof __PRIVATE_NumericMaximumTransformOperation)return{fieldPath:r.field.canonicalString(),maximum:i.k};throw fail(20930,{transform:r.transform})}(0,e)))),r.precondition.isNone||(i.currentDocument=function __PRIVATE_toPrecondition(e,r){return void 0!==r.updateTime?{updateTime:__PRIVATE_toVersion(e,r.updateTime)}:void 0!==r.exists?{exists:r.exists}:fail(27497)}(e,r.precondition)),i}(i.serializer,e)))};await i.I("Commit",i.serializer.databaseId,ResourcePath.emptyPath(),s)}async function __PRIVATE_invokeBatchGetDocumentsRpc(e,r){const i=__PRIVATE_debugCast(e),s={documents:r.map((e=>__PRIVATE_toName(i.serializer,e)))},o=await i.D("BatchGetDocuments",i.serializer.databaseId,ResourcePath.emptyPath(),s,r.length),a=new Map;o.forEach((e=>{const r=function __PRIVATE_fromBatchGetDocumentsResponse(e,r){return"found"in r?function __PRIVATE_fromFound(e,r){__PRIVATE_hardAssert(!!r.found,43571),r.found.name,r.found.updateTime;const i=fromName(e,r.found.name),s=__PRIVATE_fromVersion(r.found.updateTime),o=r.found.createTime?__PRIVATE_fromVersion(r.found.createTime):SnapshotVersion.min(),a=new ObjectValue({mapValue:{fields:r.found.fields}});return MutableDocument.newFoundDocument(i,s,o,a)}(e,r):"missing"in r?function __PRIVATE_fromMissing(e,r){__PRIVATE_hardAssert(!!r.missing,3894),__PRIVATE_hardAssert(!!r.readTime,22933);const i=fromName(e,r.missing),s=__PRIVATE_fromVersion(r.readTime);return MutableDocument.newNoDocument(i,s)}(e,r):fail(7234,{result:r})}(i.serializer,e);a.set(r.key.toString(),r)}));const _=[];return r.forEach((e=>{const r=a.get(e.toString());__PRIVATE_hardAssert(!!r,55234,{key:e}),_.push(r)})),_}const Te="ComponentProvider",ye=new Map;function __PRIVATE_getDatastore(e){if(e._terminated)throw new FirestoreError(j,"The client has already been terminated.");if(!ye.has(e)){__PRIVATE_logDebug(Te,"Initializing Datastore");const r=function __PRIVATE_newConnection(e){return new __PRIVATE_FetchConnection(e)}(function __PRIVATE_makeDatabaseInfo(e,r,i,s,o){return new DatabaseInfo(e,r,i,o.host,o.ssl,o.experimentalForceLongPolling,o.experimentalAutoDetectLongPolling,__PRIVATE_cloneLongPollingOptions(o.experimentalLongPollingOptions),o.useFetchStreams,o.isUsingEmulator,s)}(e._databaseId,e.app.options.appId||"",e._persistenceKey,e.app.options.apiKey,e._freezeSettings())),i=__PRIVATE_newSerializer(e._databaseId),s=function __PRIVATE_newDatastore(e,r,i,s){return new __PRIVATE_DatastoreImpl(e,r,i,s)}(e._authCredentials,e._appCheckCredentials,r,i);ye.set(e,s)}return ye.get(e)}const Ae="firestore.googleapis.com",Ve=!0;class FirestoreSettingsImpl{constructor(e){if(void 0===e.host){if(void 0!==e.ssl)throw new FirestoreError(b,"Can't provide ssl option if host option is not set");this.host=Ae,this.ssl=Ve}else this.host=e.host,this.ssl=e.ssl??Ve;if(this.isUsingEmulator=void 0!==e.emulatorOptions,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new FirestoreError(b,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}!function __PRIVATE_validateIsNotUsedTogether(e,r,i,s){if(!0===r&&!0===s)throw new FirestoreError(b,`${e} and ${i} cannot be used together.`)}("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=__PRIVATE_cloneLongPollingOptions(e.experimentalLongPollingOptions??{}),function __PRIVATE_validateLongPollingOptions(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new FirestoreError(b,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new FirestoreError(b,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new FirestoreError(b,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&function __PRIVATE_longPollingOptionsEqual(e,r){return e.timeoutSeconds===r.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Firestore{constructor(e,r,i,s){this._authCredentials=e,this._appCheckCredentials=r,this._databaseId=i,this._app=s,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new FirestoreSettingsImpl({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new FirestoreError(j,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new FirestoreError(j,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new FirestoreSettingsImpl(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function __PRIVATE_makeAuthCredentialsProvider(e){if(!e)return new __PRIVATE_EmptyAuthCredentialsProvider;switch(e.type){case"firstParty":return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new FirestoreError(b,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function __PRIVATE_removeComponents(e){const r=ye.get(e);r&&(__PRIVATE_logDebug(Te,"Removing Datastore"),ye.delete(e),r.terminate())}(this),Promise.resolve()}}function initializeFirestore(e,r,i){i||(i=X);const s=_getProvider(e,"firestore/lite");if(s.isInitialized(i))throw new FirestoreError(j,"Firestore can only be initialized once per app.");return s.initialize({options:r,instanceIdentifier:i})}function getFirestore(e,i){const s="object"==typeof e?e:r(),o="string"==typeof e?e:i||"(default)",a=_getProvider(s,"firestore/lite").getImmediate({identifier:o});if(!a._initialized){const e=getDefaultEmulatorHostnameAndPort("firestore");e&&connectFirestoreEmulator(a,...e)}return a}function connectFirestoreEmulator(e,r,i,s={}){e=__PRIVATE_cast(e,Firestore);const o=isCloudWorkstation(r),a=e._getSettings(),_={...a,emulatorOptions:e._getEmulatorOptions()},h=`${r}:${i}`;o&&async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(`https://${h}`),a.host!==Ae&&a.host!==h&&__PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");const d={...a,host:h,ssl:o,emulatorOptions:s};if(!deepEqual(d,_)&&(e._setSettings(d),s.mockUserToken)){let r,i;if("string"==typeof s.mockUserToken)r=s.mockUserToken,i=User.MOCK_USER;else{r=function createMockUserToken(e,r){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const i=r||"demo-project",s=e.iat||0,o=e.sub||e.user_id;if(!o)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const a={iss:`https://securetoken.google.com/${i}`,aud:i,iat:s,exp:s+3600,auth_time:s,sub:o,user_id:o,firebase:{sign_in_provider:"custom",identities:{}},...e};return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(a)),""].join(".")}(s.mockUserToken,e._app?.options.projectId);const o=s.mockUserToken.sub||s.mockUserToken.user_id;if(!o)throw new FirestoreError(b,"mockUserToken must contain 'sub' or 'user_id' field!");i=new User(o)}e._authCredentials=new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(r,i))}}function terminate(e){return e=__PRIVATE_cast(e,Firestore),i(e.app,"firestore/lite"),e._delete()}class Query{constructor(e,r,i){this.converter=r,this._query=i,this.type="query",this.firestore=e}withConverter(e){return new Query(this.firestore,e,this._query)}}class DocumentReference{constructor(e,r,i){this.converter=r,this._key=i,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new CollectionReference(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new DocumentReference(this.firestore,e,this._key)}toJSON(){return{type:DocumentReference._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,r,i){if(__PRIVATE_validateJSON(r,DocumentReference._jsonSchema))return new DocumentReference(e,i||null,new DocumentKey(ResourcePath.fromString(r.referencePath)))}}DocumentReference._jsonSchemaVersion="firestore/documentReference/1.0",DocumentReference._jsonSchema={type:property("string",DocumentReference._jsonSchemaVersion),referencePath:property("string")};class CollectionReference extends Query{constructor(e,r,i){super(e,r,function __PRIVATE_newQueryForPath(e){return new __PRIVATE_QueryImpl(e)}(i)),this._path=i,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new DocumentReference(this.firestore,null,new DocumentKey(e))}withConverter(e){return new CollectionReference(this.firestore,e,this._path)}}function collection(e,r,...i){if(e=getModularInstance(e),__PRIVATE_validateNonEmptyArgument("collection","path",r),e instanceof Firestore){const s=ResourcePath.fromString(r,...i);return __PRIVATE_validateCollectionPath(s),new CollectionReference(e,null,s)}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new FirestoreError(b,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const s=e._path.child(ResourcePath.fromString(r,...i));return __PRIVATE_validateCollectionPath(s),new CollectionReference(e.firestore,null,s)}}function collectionGroup(e,r){if(e=__PRIVATE_cast(e,Firestore),__PRIVATE_validateNonEmptyArgument("collectionGroup","collection id",r),r.indexOf("/")>=0)throw new FirestoreError(b,`Invalid collection ID '${r}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Query(e,null,function __PRIVATE_newQueryForCollectionGroup(e){return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(),e)}(r))}function doc(e,r,...i){if(e=getModularInstance(e),1===arguments.length&&(r=__PRIVATE_AutoId.newId()),__PRIVATE_validateNonEmptyArgument("doc","path",r),e instanceof Firestore){const s=ResourcePath.fromString(r,...i);return __PRIVATE_validateDocumentPath(s),new DocumentReference(e,null,new DocumentKey(s))}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new FirestoreError(b,"Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const s=e._path.child(ResourcePath.fromString(r,...i));return __PRIVATE_validateDocumentPath(s),new DocumentReference(e.firestore,e instanceof CollectionReference?e.converter:null,new DocumentKey(s))}}function refEqual(e,r){return e=getModularInstance(e),r=getModularInstance(r),(e instanceof DocumentReference||e instanceof CollectionReference)&&(r instanceof DocumentReference||r instanceof CollectionReference)&&e.firestore===r.firestore&&e.path===r.path&&e.converter===r.converter}function queryEqual(e,r){return e=getModularInstance(e),r=getModularInstance(r),e instanceof Query&&r instanceof Query&&e.firestore===r.firestore&&function __PRIVATE_queryEquals(e,r){return function __PRIVATE_targetEquals(e,r){if(e.limit!==r.limit)return!1;if(e.orderBy.length!==r.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++)if(!__PRIVATE_orderByEquals(e.orderBy[i],r.orderBy[i]))return!1;if(e.filters.length!==r.filters.length)return!1;for(let i=0;i<e.filters.length;i++)if(!__PRIVATE_filterEquals(e.filters[i],r.filters[i]))return!1;return e.collectionGroup===r.collectionGroup&&!!e.path.isEqual(r.path)&&!!__PRIVATE_boundEquals(e.startAt,r.startAt)&&__PRIVATE_boundEquals(e.endAt,r.endAt)}(__PRIVATE_queryToTarget(e),__PRIVATE_queryToTarget(r))&&e.limitType===r.limitType}(e._query,r._query)&&e.converter===r.converter}class Bytes{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Bytes(ByteString.fromBase64String(e))}catch(e){throw new FirestoreError(b,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Bytes(ByteString.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:Bytes._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(__PRIVATE_validateJSON(e,Bytes._jsonSchema))return Bytes.fromBase64String(e.bytes)}}Bytes._jsonSchemaVersion="firestore/bytes/1.0",Bytes._jsonSchema={type:property("string",Bytes._jsonSchemaVersion),bytes:property("string")};class FieldPath{constructor(...e){for(let r=0;r<e.length;++r)if(0===e[r].length)throw new FirestoreError(b,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new FieldPath$1(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}function documentId(){return new FieldPath(te)}class FieldValue{constructor(e){this._methodName=e}}class GeoPoint{constructor(e,r){if(!isFinite(e)||e<-90||e>90)throw new FirestoreError(b,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(r)||r<-180||r>180)throw new FirestoreError(b,"Longitude must be a number between -180 and 180, but was: "+r);this._lat=e,this._long=r}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return __PRIVATE_primitiveComparator(this._lat,e._lat)||__PRIVATE_primitiveComparator(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:GeoPoint._jsonSchemaVersion}}static fromJSON(e){if(__PRIVATE_validateJSON(e,GeoPoint._jsonSchema))return new GeoPoint(e.latitude,e.longitude)}}GeoPoint._jsonSchemaVersion="firestore/geoPoint/1.0",GeoPoint._jsonSchema={type:property("string",GeoPoint._jsonSchemaVersion),latitude:property("number"),longitude:property("number")};class VectorValue{constructor(e){this._values=(e||[]).map((e=>e))}toArray(){return this._values.map((e=>e))}isEqual(e){return function __PRIVATE_isPrimitiveArrayEqual(e,r){if(e.length!==r.length)return!1;for(let i=0;i<e.length;++i)if(e[i]!==r[i])return!1;return!0}(this._values,e._values)}toJSON(){return{type:VectorValue._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(__PRIVATE_validateJSON(e,VectorValue._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every((e=>"number"==typeof e)))return new VectorValue(e.vectorValues);throw new FirestoreError(b,"Expected 'vectorValues' field to be a number array")}}}VectorValue._jsonSchemaVersion="firestore/vectorValue/1.0",VectorValue._jsonSchema={type:property("string",VectorValue._jsonSchemaVersion),vectorValues:property("object")};const Ie=/^__.*__$/;class ParsedSetData{constructor(e,r,i){this.data=e,this.fieldMask=r,this.fieldTransforms=i}toMutation(e,r){return null!==this.fieldMask?new __PRIVATE_PatchMutation(e,this.data,this.fieldMask,r,this.fieldTransforms):new __PRIVATE_SetMutation(e,this.data,r,this.fieldTransforms)}}class ParsedUpdateData{constructor(e,r,i){this.data=e,this.fieldMask=r,this.fieldTransforms=i}toMutation(e,r){return new __PRIVATE_PatchMutation(e,this.data,this.fieldMask,r,this.fieldTransforms)}}function __PRIVATE_isWrite(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw fail(40011,{dataSource:e})}}class ParseContextImpl{constructor(e,r,i,s,o,a){this.settings=e,this.databaseId=r,this.serializer=i,this.ignoreUndefinedProperties=s,void 0===o&&this.validatePath(),this.fieldTransforms=o||[],this.fieldMask=a||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}contextWith(e){return new ParseContextImpl({...this.settings,...e},this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}childContextForField(e){const r=this.path?.child(e),i=this.contextWith({path:r,arrayElement:!1});return i.validatePathSegment(e),i}childContextForFieldPath(e){const r=this.path?.child(e),i=this.contextWith({path:r,arrayElement:!1});return i.validatePath(),i}childContextForArray(e){return this.contextWith({path:void 0,arrayElement:!0})}createError(e){return createError(e,this.settings.methodName,this.settings.hasConverter||!1,this.path,this.settings.targetDoc)}contains(e){return void 0!==this.fieldMask.find((r=>e.isPrefixOf(r)))||void 0!==this.fieldTransforms.find((r=>e.isPrefixOf(r.field)))}validatePath(){if(this.path)for(let e=0;e<this.path.length;e++)this.validatePathSegment(this.path.get(e))}validatePathSegment(e){if(0===e.length)throw this.createError("Document fields must not be empty");if(__PRIVATE_isWrite(this.dataSource)&&Ie.test(e))throw this.createError('Document fields cannot begin and end with "__"')}}class UserDataReader{constructor(e,r,i){this.databaseId=e,this.ignoreUndefinedProperties=r,this.serializer=i||__PRIVATE_newSerializer(e)}createContext(e,r,i,s=!1){return new ParseContextImpl({dataSource:e,methodName:r,targetDoc:i,path:FieldPath$1.emptyPath(),arrayElement:!1,hasConverter:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function __PRIVATE_newUserDataReader(e){const r=e._freezeSettings(),i=__PRIVATE_newSerializer(e._databaseId);return new UserDataReader(e._databaseId,!!r.ignoreUndefinedProperties,i)}function __PRIVATE_parseSetData(e,r,i,s,o,a={}){const _=e.createContext(a.merge||a.mergeFields?2:0,r,i,o);__PRIVATE_validatePlainObject("Data must be an object, but it was:",_,s);const h=__PRIVATE_parseObject(s,_);let d,f;if(a.merge)d=new FieldMask(_.fieldMask),f=_.fieldTransforms;else if(a.mergeFields){const e=[];for(const s of a.mergeFields){const o=__PRIVATE_fieldPathFromArgument(r,s,i);if(!_.contains(o))throw new FirestoreError(b,`Field '${o}' is specified in your field mask but missing from your input data.`);__PRIVATE_fieldMaskContains(e,o)||e.push(o)}d=new FieldMask(e),f=_.fieldTransforms.filter((e=>d.covers(e.field)))}else d=null,f=_.fieldTransforms;return new ParsedSetData(new ObjectValue(h),d,f)}class __PRIVATE_DeleteFieldValueImpl extends FieldValue{_toFieldTransform(e){if(2!==e.dataSource)throw 1===e.dataSource?e.createError(`${this._methodName}() can only appear at the top level of your update data`):e.createError(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof __PRIVATE_DeleteFieldValueImpl}}function __PRIVATE_createSentinelChildContext(e,r,i){return new ParseContextImpl({dataSource:3,targetDoc:r.settings.targetDoc,methodName:e._methodName,arrayElement:i},r.databaseId,r.serializer,r.ignoreUndefinedProperties)}class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue{_toFieldTransform(e){return new FieldTransform(e.path,new __PRIVATE_ServerTimestampTransform)}isEqual(e){return e instanceof __PRIVATE_ServerTimestampFieldValueImpl}}class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue{constructor(e,r){super(e),this.H=r}_toFieldTransform(e){const r=__PRIVATE_createSentinelChildContext(this,e,!0),i=this.H.map((e=>__PRIVATE_parseData(e,r))),s=new __PRIVATE_ArrayUnionTransformOperation(i);return new FieldTransform(e.path,s)}isEqual(e){return e instanceof __PRIVATE_ArrayUnionFieldValueImpl&&deepEqual(this.H,e.H)}}class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue{constructor(e,r){super(e),this.H=r}_toFieldTransform(e){const r=__PRIVATE_createSentinelChildContext(this,e,!0),i=this.H.map((e=>__PRIVATE_parseData(e,r))),s=new __PRIVATE_ArrayRemoveTransformOperation(i);return new FieldTransform(e.path,s)}isEqual(e){return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl&&deepEqual(this.H,e.H)}}class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue{constructor(e,r){super(e),this.Y=r}_toFieldTransform(e){const r=new __PRIVATE_NumericIncrementTransformOperation(e.serializer,toNumber(e.serializer,this.Y));return new FieldTransform(e.path,r)}isEqual(e){return e instanceof __PRIVATE_NumericIncrementFieldValueImpl&&(this.Y===e.Y||Number.isNaN(this.Y)&&Number.isNaN(e.Y))}}class __PRIVATE_NumericMinimumFieldValueImpl extends FieldValue{constructor(e,r){super(e),this.Y=r}_toFieldTransform(e){const r=new __PRIVATE_NumericMinimumTransformOperation(e.serializer,toNumber(e.serializer,this.Y));return new FieldTransform(e.path,r)}isEqual(e){return e instanceof __PRIVATE_NumericMinimumFieldValueImpl&&(this.Y===e.Y||Number.isNaN(this.Y)&&Number.isNaN(e.Y))}}class __PRIVATE_NumericMaximumFieldValueImpl extends FieldValue{constructor(e,r){super(e),this.Y=r}_toFieldTransform(e){const r=new __PRIVATE_NumericMaximumTransformOperation(e.serializer,toNumber(e.serializer,this.Y));return new FieldTransform(e.path,r)}isEqual(e){return e instanceof __PRIVATE_NumericMaximumFieldValueImpl&&(this.Y===e.Y||Number.isNaN(this.Y)&&Number.isNaN(e.Y))}}function __PRIVATE_parseUpdateData(e,r,i,s){const o=e.createContext(1,r,i);__PRIVATE_validatePlainObject("Data must be an object, but it was:",o,s);const a=[],_=ObjectValue.empty();forEach(s,((e,s)=>{const h=__PRIVATE_fieldPathFromDotSeparatedString(r,e,i);s=getModularInstance(s);const d=o.childContextForFieldPath(h);if(s instanceof __PRIVATE_DeleteFieldValueImpl)a.push(h);else{const e=__PRIVATE_parseData(s,d);null!=e&&(a.push(h),_.set(h,e))}}));const h=new FieldMask(a);return new ParsedUpdateData(_,h,o.fieldTransforms)}function __PRIVATE_parseUpdateVarargs(e,r,i,s,o,a){const _=e.createContext(1,r,i),h=[__PRIVATE_fieldPathFromArgument(r,s,i)],d=[o];if(a.length%2!=0)throw new FirestoreError(b,`Function ${r}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<a.length;e+=2)h.push(__PRIVATE_fieldPathFromArgument(r,a[e])),d.push(a[e+1]);const f=[],g=ObjectValue.empty();for(let e=h.length-1;e>=0;--e)if(!__PRIVATE_fieldMaskContains(f,h[e])){const r=h[e];let i=d[e];i=getModularInstance(i);const s=_.childContextForFieldPath(r);if(i instanceof __PRIVATE_DeleteFieldValueImpl)f.push(r);else{const e=__PRIVATE_parseData(i,s);null!=e&&(f.push(r),g.set(r,e))}}const E=new FieldMask(f);return new ParsedUpdateData(g,E,_.fieldTransforms)}function __PRIVATE_parseQueryValue(e,r,i,s=!1){return __PRIVATE_parseData(i,e.createContext(s?4:3,r))}function __PRIVATE_parseData(e,r,i){if(__PRIVATE_looksLikeJsonObject(e=getModularInstance(e)))return __PRIVATE_validatePlainObject("Unsupported field value:",r,e),__PRIVATE_parseObject(e,r);if(e instanceof FieldValue)return function __PRIVATE_parseSentinelFieldValue(e,r){if(!__PRIVATE_isWrite(r.dataSource))throw r.createError(`${e._methodName}() can only be used with update() and set()`);if(!r.path)throw r.createError(`${e._methodName}() is not currently supported inside arrays`);const i=e._toFieldTransform(r);i&&r.fieldTransforms.push(i)}(e,r),null;if(void 0===e&&r.ignoreUndefinedProperties)return null;if(r.path&&r.fieldMask.push(r.path),e instanceof Array){if(r.settings.arrayElement&&4!==r.dataSource)throw r.createError("Nested arrays are not supported");return function __PRIVATE_parseArray(e,r){const i=[];let s=0;for(const o of e){let e=__PRIVATE_parseData(o,r.childContextForArray(s));null==e&&(e={nullValue:"NULL_VALUE"}),i.push(e),s++}return{arrayValue:{values:i}}}(e,r)}return function __PRIVATE_parseScalarValue(e,r,i){if(null===(e=getModularInstance(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return toNumber(r.serializer,e,i);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const i=Timestamp.fromDate(e);return{timestampValue:toTimestamp(r.serializer,i)}}if(e instanceof Timestamp){const i=new Timestamp(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:toTimestamp(r.serializer,i)}}if(e instanceof GeoPoint)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Bytes)return{bytesValue:__PRIVATE_toBytes(r.serializer,e._byteString)};if(e instanceof DocumentReference){const i=r.databaseId,s=e.firestore._databaseId;if(!s.isEqual(i))throw r.createError(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:__PRIVATE_toResourceName(e.firestore._databaseId||r.databaseId,e._key.path)}}if(e instanceof VectorValue)return function __PRIVATE_parseVectorValue(e,r){const i=e instanceof VectorValue?e.toArray():e,s={fields:{[_e]:{stringValue:fe},[me]:{arrayValue:{values:i.map((e=>{if("number"!=typeof e)throw r.createError("VectorValues must only contain numeric values.");return __PRIVATE_toDouble(r.serializer,e)}))}}}};return{mapValue:s}}(e,r);if(__PRIVATE_isProtoValueSerializable(e))return e._toProto(r.serializer);throw r.createError(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`)}(e,r,i)}function __PRIVATE_parseObject(e,r){const i={};return function isEmpty(e){for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r))return!1;return!0}(e)?r.path&&r.path.length>0&&r.fieldMask.push(r.path):forEach(e,((e,s)=>{const o=__PRIVATE_parseData(s,r.childContextForField(e));null!=o&&(i[e]=o)})),{mapValue:{fields:i}}}function __PRIVATE_looksLikeJsonObject(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Timestamp||e instanceof GeoPoint||e instanceof Bytes||e instanceof DocumentReference||e instanceof FieldValue||e instanceof VectorValue||__PRIVATE_isProtoValueSerializable(e))}function __PRIVATE_validatePlainObject(e,r,i){if(!__PRIVATE_looksLikeJsonObject(i)||!__PRIVATE_isPlainObject(i)){const s=__PRIVATE_valueDescription(i);throw"an object"===s?r.createError(e+" a custom object"):r.createError(e+" "+s)}}function __PRIVATE_fieldPathFromArgument(e,r,i){if((r=getModularInstance(r))instanceof FieldPath)return r._internalPath;if("string"==typeof r)return __PRIVATE_fieldPathFromDotSeparatedString(e,r);throw createError("Field path arguments must be of type string or ",e,!1,void 0,i)}const Pe=new RegExp("[~\\*/\\[\\]]");function __PRIVATE_fieldPathFromDotSeparatedString(e,r,i){if(r.search(Pe)>=0)throw createError(`Invalid field path (${r}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,i);try{return new FieldPath(...r.split("."))._internalPath}catch(s){throw createError(`Invalid field path (${r}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,i)}}function createError(e,r,i,s,o){const a=s&&!s.isEmpty(),_=void 0!==o;let h=`Function ${r}() called with invalid data`;i&&(h+=" (via `toFirestore()`)"),h+=". ";let d="";return(a||_)&&(d+=" (found",a&&(d+=` in field ${s}`),_&&(d+=` in document ${o}`),d+=")"),new FirestoreError(b,h+e+d)}function __PRIVATE_fieldMaskContains(e,r){return e.some((e=>e.isEqual(r)))}class DocumentSnapshot{constructor(e,r,i,s,o){this._firestore=e,this._userDataWriter=r,this._key=i,this._document=s,this._converter=o}get id(){return this._key.path.lastSegment()}get ref(){return new DocumentReference(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new QueryDocumentSnapshot(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}_fieldsProto(){return this._document?.data.clone().value.mapValue.fields??void 0}get(e){if(this._document){const r=this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get",e));if(null!==r)return this._userDataWriter.convertValue(r)}}}class QueryDocumentSnapshot extends DocumentSnapshot{data(){return super.data()}}class QuerySnapshot{constructor(e,r){this._docs=r,this.query=e}get docs(){return[...this._docs]}get size(){return this.docs.length}get empty(){return 0===this.docs.length}forEach(e,r){this._docs.forEach(e,r)}}function snapshotEqual(e,r){return e=getModularInstance(e),r=getModularInstance(r),e instanceof DocumentSnapshot&&r instanceof DocumentSnapshot?e._firestore===r._firestore&&e._key.isEqual(r._key)&&(null===e._document?null===r._document:e._document.isEqual(r._document))&&e._converter===r._converter:e instanceof QuerySnapshot&&r instanceof QuerySnapshot&&queryEqual(e.query,r.query)&&__PRIVATE_arrayEquals(e.docs,r.docs,snapshotEqual)}class AppliableConstraint{}class QueryConstraint extends AppliableConstraint{}function query(e,r,...i){let s=[];r instanceof AppliableConstraint&&s.push(r),s=s.concat(i),function __PRIVATE_validateQueryConstraintArray(e){const r=e.filter((e=>e instanceof QueryCompositeFilterConstraint)).length,i=e.filter((e=>e instanceof QueryFieldFilterConstraint)).length;if(r>1||r>0&&i>0)throw new FirestoreError(b,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(s);for(const r of s)e=r._apply(e);return e}class QueryFieldFilterConstraint extends QueryConstraint{constructor(e,r,i){super(),this._field=e,this._op=r,this._value=i,this.type="where"}static _create(e,r,i){return new QueryFieldFilterConstraint(e,r,i)}_apply(e){const r=this._parse(e);return __PRIVATE_validateNewFieldFilter(e._query,r),new Query(e.firestore,e.converter,__PRIVATE_queryWithAddedFilter(e._query,r))}_parse(e){const r=__PRIVATE_newUserDataReader(e.firestore),i=function __PRIVATE_newQueryFilter(e,r,i,s,o,a,_){let h;if(o.isKeyField()){if("array-contains"===a||"array-contains-any"===a)throw new FirestoreError(b,`Invalid Query. You can't perform '${a}' queries on documentId().`);if("in"===a||"not-in"===a){__PRIVATE_validateDisjunctiveFilterElements(_,a);const r=[];for(const i of _)r.push(__PRIVATE_parseDocumentIdValue(s,e,i));h={arrayValue:{values:r}}}else h=__PRIVATE_parseDocumentIdValue(s,e,_)}else"in"!==a&&"not-in"!==a&&"array-contains-any"!==a||__PRIVATE_validateDisjunctiveFilterElements(_,a),h=__PRIVATE_parseQueryValue(i,r,_,"in"===a||"not-in"===a);return FieldFilter.create(o,a,h)}(e._query,"where",r,e.firestore._databaseId,this._field,this._op,this._value);return i}}function where(e,r,i){const s=r,o=__PRIVATE_fieldPathFromArgument("where",e);return QueryFieldFilterConstraint._create(o,s,i)}class QueryCompositeFilterConstraint extends AppliableConstraint{constructor(e,r){super(),this.type=e,this._queryConstraints=r}static _create(e,r){return new QueryCompositeFilterConstraint(e,r)}_parse(e){const r=this._queryConstraints.map((r=>r._parse(e))).filter((e=>e.getFilters().length>0));return 1===r.length?r[0]:CompositeFilter.create(r,this._getOperator())}_apply(e){const r=this._parse(e);return 0===r.getFilters().length?e:(function __PRIVATE_validateNewFilter(e,r){let i=e;const s=r.getFlattenedFilters();for(const e of s)__PRIVATE_validateNewFieldFilter(i,e),i=__PRIVATE_queryWithAddedFilter(i,e)}(e._query,r),new Query(e.firestore,e.converter,__PRIVATE_queryWithAddedFilter(e._query,r)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}function or(...e){return e.forEach((e=>__PRIVATE_validateQueryFilterConstraint("or",e))),QueryCompositeFilterConstraint._create("or",e)}function and(...e){return e.forEach((e=>__PRIVATE_validateQueryFilterConstraint("and",e))),QueryCompositeFilterConstraint._create("and",e)}class QueryOrderByConstraint extends QueryConstraint{constructor(e,r){super(),this._field=e,this._direction=r,this.type="orderBy"}static _create(e,r){return new QueryOrderByConstraint(e,r)}_apply(e){const r=function __PRIVATE_newQueryOrderBy(e,r,i){if(null!==e.startAt)throw new FirestoreError(b,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new FirestoreError(b,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new OrderBy(r,i)}(e._query,this._field,this._direction);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithAddedOrderBy(e,r){const i=e.explicitOrderBy.concat([r]);return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,i,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,r))}}function orderBy(e,r="asc"){const i=r,s=__PRIVATE_fieldPathFromArgument("orderBy",e);return QueryOrderByConstraint._create(s,i)}class QueryLimitConstraint extends QueryConstraint{constructor(e,r,i){super(),this.type=e,this._limit=r,this._limitType=i}static _create(e,r,i){return new QueryLimitConstraint(e,r,i)}_apply(e){return new Query(e.firestore,e.converter,function __PRIVATE_queryWithLimit(e,r,i){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),r,i,e.startAt,e.endAt)}(e._query,this._limit,this._limitType))}}function limit(e){return __PRIVATE_validatePositiveNumber("limit",e),QueryLimitConstraint._create("limit",e,"F")}function limitToLast(e){return __PRIVATE_validatePositiveNumber("limitToLast",e),QueryLimitConstraint._create("limitToLast",e,"L")}class QueryStartAtConstraint extends QueryConstraint{constructor(e,r,i){super(),this.type=e,this._docOrFields=r,this._inclusive=i}static _create(e,r,i){return new QueryStartAtConstraint(e,r,i)}_apply(e){const r=__PRIVATE_newQueryBoundFromDocOrFields(e,this.type,this._docOrFields,this._inclusive);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithStartAt(e,r){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,r,e.endAt)}(e._query,r))}}function startAt(...e){return QueryStartAtConstraint._create("startAt",e,!0)}function startAfter(...e){return QueryStartAtConstraint._create("startAfter",e,!1)}class QueryEndAtConstraint extends QueryConstraint{constructor(e,r,i){super(),this.type=e,this._docOrFields=r,this._inclusive=i}static _create(e,r,i){return new QueryEndAtConstraint(e,r,i)}_apply(e){const r=__PRIVATE_newQueryBoundFromDocOrFields(e,this.type,this._docOrFields,this._inclusive);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithEndAt(e,r){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,r)}(e._query,r))}}function endBefore(...e){return QueryEndAtConstraint._create("endBefore",e,!1)}function endAt(...e){return QueryEndAtConstraint._create("endAt",e,!0)}function __PRIVATE_newQueryBoundFromDocOrFields(e,r,i,s){if(i[0]=getModularInstance(i[0]),i[0]instanceof DocumentSnapshot)return function __PRIVATE_newQueryBoundFromDocument(e,r,i,s,o){if(!s)throw new FirestoreError(O,`Can't use a DocumentSnapshot that doesn't exist for ${i}().`);const a=[];for(const i of __PRIVATE_queryNormalizedOrderBy(e))if(i.field.isKeyField())a.push(__PRIVATE_refValue(r,s.key));else{const e=s.data.field(i.field);if(__PRIVATE_isServerTimestamp(e))throw new FirestoreError(b,'Invalid query. You are trying to start or end a query using a document for which the field "'+i.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=i.field.canonicalString();throw new FirestoreError(b,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}a.push(e)}return new Bound(a,o)}(e._query,e.firestore._databaseId,r,i[0]._document,s);{const o=__PRIVATE_newUserDataReader(e.firestore);return function __PRIVATE_newQueryBoundFromFields(e,r,i,s,o,a){const _=e.explicitOrderBy;if(o.length>_.length)throw new FirestoreError(b,`Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const h=[];for(let a=0;a<o.length;a++){const d=o[a];if(_[a].field.isKeyField()){if("string"!=typeof d)throw new FirestoreError(b,`Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof d}`);if(!__PRIVATE_isCollectionGroupQuery(e)&&-1!==d.indexOf("/"))throw new FirestoreError(b,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${s}() must be a plain document ID, but '${d}' contains a slash.`);const i=e.path.child(ResourcePath.fromString(d));if(!DocumentKey.isDocumentKey(i))throw new FirestoreError(b,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${s}() must result in a valid document path, but '${i}' is not because it contains an odd number of segments.`);const o=new DocumentKey(i);h.push(__PRIVATE_refValue(r,o))}else{const e=__PRIVATE_parseQueryValue(i,s,d);h.push(e)}}return new Bound(h,a)}(e._query,e.firestore._databaseId,o,r,i,s)}}function __PRIVATE_parseDocumentIdValue(e,r,i){if("string"==typeof(i=getModularInstance(i))){if(""===i)throw new FirestoreError(b,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!__PRIVATE_isCollectionGroupQuery(r)&&-1!==i.indexOf("/"))throw new FirestoreError(b,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${i}' contains a '/' character.`);const s=r.path.child(ResourcePath.fromString(i));if(!DocumentKey.isDocumentKey(s))throw new FirestoreError(b,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);return __PRIVATE_refValue(e,new DocumentKey(s))}if(i instanceof DocumentReference)return __PRIVATE_refValue(e,i._key);throw new FirestoreError(b,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(i)}.`)}function __PRIVATE_validateDisjunctiveFilterElements(e,r){if(!Array.isArray(e)||0===e.length)throw new FirestoreError(b,`Invalid Query. A non-empty array is required for '${r.toString()}' filters.`)}function __PRIVATE_validateNewFieldFilter(e,r){const i=function __PRIVATE_findOpInsideFilters(e,r){for(const i of e)for(const e of i.getFlattenedFilters())if(r.indexOf(e.op)>=0)return e.op;return null}(e.filters,function __PRIVATE_conflictingOps(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(r.op));if(null!==i)throw i===r.op?new FirestoreError(b,`Invalid query. You cannot use more than one '${r.op.toString()}' filter.`):new FirestoreError(b,`Invalid query. You cannot use '${r.op.toString()}' filters with '${i.toString()}' filters.`)}function __PRIVATE_validateQueryFilterConstraint(e,r){if(!(r instanceof QueryFieldFilterConstraint||r instanceof QueryCompositeFilterConstraint))throw new FirestoreError(b,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class AbstractUserDataWriter{convertValue(e,r="none"){switch(__PRIVATE_typeOrder(e)){case 0:return null;case 1:return e.booleanValue;case 2:return __PRIVATE_normalizeNumber(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,r);case 5:return e.stringValue;case 6:return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,r);case 11:return this.convertObject(e.mapValue,r);case 10:return this.convertVectorValue(e.mapValue);default:throw fail(62114,{value:e})}}convertObject(e,r){return this.convertObjectMap(e.fields,r)}convertObjectMap(e,r="none"){const i={};return forEach(e,((e,s)=>{i[e]=this.convertValue(s,r)})),i}convertVectorValue(e){const r=e.fields?.[me].arrayValue?.values?.map((e=>__PRIVATE_normalizeNumber(e.doubleValue)));return new VectorValue(r)}convertGeoPoint(e){return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(e.longitude))}convertArray(e,r){return(e.values||[]).map((e=>this.convertValue(e,r)))}convertServerTimestamp(e,r){switch(r){case"previous":const i=__PRIVATE_getPreviousValue(e);return null==i?null:this.convertValue(i,r);case"estimate":return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));default:return null}}convertTimestamp(e){const r=__PRIVATE_normalizeTimestamp(e);return new Timestamp(r.seconds,r.nanos)}convertDocumentKey(e,r){const i=ResourcePath.fromString(e);__PRIVATE_hardAssert(__PRIVATE_isValidResourceName(i),9688,{name:e});const s=new DatabaseId(i.get(1),i.get(3)),o=new DocumentKey(i.popFirst(5));return s.isEqual(r)||__PRIVATE_logError(`Document ${o} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${r.projectId}/${r.database}) instead.`),o}}function __PRIVATE_applyFirestoreDataConverter(e,r,i){let s;return s=e?i&&(i.merge||i.mergeFields)?e.toFirestore(r,i):e.toFirestore(r):r,s}class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter{constructor(e){super(),this.firestore=e}convertBytes(e){return new Bytes(e)}convertReference(e){const r=this.convertDocumentKey(e,this.firestore._databaseId);return new DocumentReference(this.firestore,null,r)}}function getDoc(e){const r=__PRIVATE_getDatastore((e=__PRIVATE_cast(e,DocumentReference)).firestore),i=new __PRIVATE_LiteUserDataWriter(e.firestore);return __PRIVATE_invokeBatchGetDocumentsRpc(r,[e._key]).then((r=>{__PRIVATE_hardAssert(1===r.length,15618);const s=r[0];return new DocumentSnapshot(e.firestore,i,e._key,s.isFoundDocument()?s:null,e.converter)}))}function getDocs(e){!function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new FirestoreError(Q,"limitToLast() queries require specifying at least one orderBy() clause")}((e=__PRIVATE_cast(e,Query))._query);const r=__PRIVATE_getDatastore(e.firestore),i=new __PRIVATE_LiteUserDataWriter(e.firestore);return async function __PRIVATE_invokeRunQueryRpc(e,r){const i=__PRIVATE_debugCast(e),{K:s,parent:o}=__PRIVATE_toQueryTarget(i.serializer,__PRIVATE_queryToTarget(r));return(await i.D("RunQuery",i.serializer.databaseId,o,{structuredQuery:s.structuredQuery})).filter((e=>!!e.document)).map((e=>function fromDocument(e,r,i){const s=fromName(e,r.name),o=__PRIVATE_fromVersion(r.updateTime),a=r.createTime?__PRIVATE_fromVersion(r.createTime):SnapshotVersion.min(),_=new ObjectValue({mapValue:{fields:r.fields}}),h=MutableDocument.newFoundDocument(s,o,a,_);return i&&h.setHasCommittedMutations(),i?h.setHasCommittedMutations():h}(i.serializer,e.document,void 0)))}(r,e._query).then((r=>{const s=r.map((r=>new QueryDocumentSnapshot(e.firestore,i,r.key,r,e.converter)));return"L"===e._query.limitType&&s.reverse(),new QuerySnapshot(e,s)}))}function setDoc(e,r,i){const s=__PRIVATE_applyFirestoreDataConverter((e=__PRIVATE_cast(e,DocumentReference)).converter,r,i),o=__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore),"setDoc",e._key,s,null!==e.converter,i);return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(e.firestore),[o.toMutation(e._key,Precondition.none())])}function updateDoc(e,r,i,...s){const o=__PRIVATE_newUserDataReader((e=__PRIVATE_cast(e,DocumentReference)).firestore);let a;return a="string"==typeof(r=getModularInstance(r))||r instanceof FieldPath?__PRIVATE_parseUpdateVarargs(o,"updateDoc",e._key,r,i,s):__PRIVATE_parseUpdateData(o,"updateDoc",e._key,r),__PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(e.firestore),[a.toMutation(e._key,Precondition.exists(!0))])}function deleteDoc(e){return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore((e=__PRIVATE_cast(e,DocumentReference)).firestore),[new __PRIVATE_DeleteMutation(e._key,Precondition.none())])}function addDoc(e,r){const i=doc(e=__PRIVATE_cast(e,CollectionReference)),s=__PRIVATE_applyFirestoreDataConverter(e.converter,r),o=__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore),"addDoc",i._key,s,null!==i.converter,{});return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(e.firestore),[o.toMutation(i._key,Precondition.exists(!1))]).then((()=>i))}function deleteField(){return new __PRIVATE_DeleteFieldValueImpl("deleteField")}function serverTimestamp(){return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp")}function arrayUnion(...e){return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion",e)}function arrayRemove(...e){return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove",e)}function increment(e){return new __PRIVATE_NumericIncrementFieldValueImpl("increment",e)}function minimum(e){return new __PRIVATE_NumericMinimumFieldValueImpl("minimum",e)}function maximum(e){return new __PRIVATE_NumericMaximumFieldValueImpl("maximum",e)}function vector(e){return new VectorValue(e)}const Re="4.16.0";class __PRIVATE_Deferred{constructor(){this.promise=new Promise(((e,r)=>{this.resolve=e,this.reject=r}))}}class __PRIVATE_AggregateImpl{constructor(e,r,i){this.alias=e,this.aggregateType=r,this.fieldPath=i}}class __PRIVATE_ExponentialBackoff{constructor(e,r,i=1e3,s=1.5,o=6e4){this.t=e,this.timerId=r,this.i=i,this.o=s,this.h=o,this.u=0,this.l=null,this._=Date.now(),this.reset()}reset(){this.u=0}m(){this.u=this.h}A(e){this.cancel();const r=Math.floor(this.u+this.p()),i=Math.max(0,Date.now()-this._),s=Math.max(0,r-i);s>0&&__PRIVATE_logDebug("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.u} ms, delay with jitter: ${r} ms, last attempt: ${i} ms ago)`),this.l=this.t.enqueueAfterDelay(this.timerId,s,(()=>(this._=Date.now(),e()))),this.u*=this.o,this.u<this.i&&(this.u=this.i),this.u>this.h&&(this.u=this.h)}T(){null!==this.l&&(this.l.skipDelay(),this.l=null)}cancel(){null!==this.l&&(this.l.cancel(),this.l=null)}p(){return(Math.random()-.5)*this.u}}class AggregateField{constructor(e="count",r){this._internalFieldPath=r,this.type="AggregateField",this.aggregateType=e}}class AggregateQuerySnapshot{constructor(e,r,i){this._userDataWriter=r,this._data=i,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}_fieldsProto(){return new ObjectValue({mapValue:{fields:this._data}}).clone().value.mapValue.fields}}function getCount(e){return getAggregate(e,{count:count()})}function getAggregate(e,r){const i=__PRIVATE_cast(e.firestore,Firestore),s=__PRIVATE_getDatastore(i),o=function __PRIVATE_mapToArray(e,r){const i=[];for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(r(e[s],s,e));return i}(r,((e,r)=>new __PRIVATE_AggregateImpl(r,e.aggregateType,e._internalFieldPath)));return async function __PRIVATE_invokeRunAggregationQueryRpc(e,r,i){const s=__PRIVATE_debugCast(e),{request:o,J:a,parent:_}=function __PRIVATE_toRunAggregationQueryRequest(e,r,i,s){const{K:o,parent:a}=__PRIVATE_toQueryTarget(e,r),_={},h=[];let d=0;return i.forEach((e=>{const r=s?e.alias:"aggregate_"+d++;_[r]=e.alias,"count"===e.aggregateType?h.push({alias:r,count:{}}):"avg"===e.aggregateType?h.push({alias:r,avg:{field:__PRIVATE_toFieldPathReference(e.fieldPath)}}):"sum"===e.aggregateType&&h.push({alias:r,sum:{field:__PRIVATE_toFieldPathReference(e.fieldPath)}})})),{request:{structuredAggregationQuery:{aggregations:h,structuredQuery:o.structuredQuery},parent:o.parent},J:_,parent:a}}(s.serializer,function __PRIVATE_queryToAggregateTarget(e){const r=__PRIVATE_debugCast(e);return r.U||(r.U=__PRIVATE__queryToTarget(r,e.explicitOrderBy)),r.U}(r),i);s.connection.P||delete o.parent;const h=(await s.D("RunAggregationQuery",s.serializer.databaseId,_,o,1)).filter((e=>!!e.result));__PRIVATE_hardAssert(1===h.length,64727);const d=h[0].result?.aggregateFields;return Object.keys(d).reduce(((e,r)=>(e[a[r]]=d[r],e)),{})}(s,e._query,o).then((r=>function __PRIVATE_convertToAggregateQuerySnapshot(e,r,i){const s=new __PRIVATE_LiteUserDataWriter(e);return new AggregateQuerySnapshot(r,s,i)}(i,e,r)))}function sum(e){return new AggregateField("sum",__PRIVATE_fieldPathFromArgument("sum",e))}function average(e){return new AggregateField("avg",__PRIVATE_fieldPathFromArgument("average",e))}function count(){return new AggregateField("count")}function aggregateFieldEqual(e,r){return e instanceof AggregateField&&r instanceof AggregateField&&e.aggregateType===r.aggregateType&&e._internalFieldPath?.canonicalString()===r._internalFieldPath?.canonicalString()}function aggregateQuerySnapshotEqual(e,r){return queryEqual(e.query,r.query)&&deepEqual(e.data(),r.data())}class WriteBatch{constructor(e,r){this._firestore=e,this._commitHandler=r,this._mutations=[],this._committed=!1,this._dataReader=__PRIVATE_newUserDataReader(e)}set(e,r,i){this._verifyNotCommitted();const s=__PRIVATE_validateReference(e,this._firestore),o=__PRIVATE_applyFirestoreDataConverter(s.converter,r,i),a=__PRIVATE_parseSetData(this._dataReader,"WriteBatch.set",s._key,o,null!==s.converter,i);return this._mutations.push(a.toMutation(s._key,Precondition.none())),this}update(e,r,i,...s){this._verifyNotCommitted();const o=__PRIVATE_validateReference(e,this._firestore);let a;return a="string"==typeof(r=getModularInstance(r))||r instanceof FieldPath?__PRIVATE_parseUpdateVarargs(this._dataReader,"WriteBatch.update",o._key,r,i,s):__PRIVATE_parseUpdateData(this._dataReader,"WriteBatch.update",o._key,r),this._mutations.push(a.toMutation(o._key,Precondition.exists(!0))),this}delete(e){this._verifyNotCommitted();const r=__PRIVATE_validateReference(e,this._firestore);return this._mutations=this._mutations.concat(new __PRIVATE_DeleteMutation(r._key,Precondition.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new FirestoreError(j,"A write batch can no longer be used after commit() has been called.")}}function __PRIVATE_validateReference(e,r){if((e=getModularInstance(e)).firestore!==r)throw new FirestoreError(b,"Provided document reference is from a different Firestore instance.");return e}function writeBatch(e){const r=__PRIVATE_getDatastore(e=__PRIVATE_cast(e,Firestore));return new WriteBatch(e,(e=>__PRIVATE_invokeCommitRpc(r,e)))}class Transaction$1{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new FirestoreError(b,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;const r=await __PRIVATE_invokeBatchGetDocumentsRpc(this.datastore,e);return r.forEach((e=>this.recordVersion(e))),r}set(e,r){this.write(r.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,r){try{this.write(r.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new __PRIVATE_DeleteMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;const e=this.readVersions;this.mutations.forEach((r=>{e.delete(r.key.toString())})),e.forEach(((e,r)=>{const i=DocumentKey.fromPath(r);this.mutations.push(new __PRIVATE_VerifyMutation(i,this.precondition(i)))})),await __PRIVATE_invokeCommitRpc(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let r;if(e.isFoundDocument())r=e.version;else{if(!e.isNoDocument())throw fail(50498,{R:e.constructor.name});r=SnapshotVersion.min()}const i=this.readVersions.get(e.key.toString());if(i){if(!r.isEqual(i))throw new FirestoreError($,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),r)}precondition(e){const r=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&r?r.isEqual(SnapshotVersion.min())?Precondition.exists(!1):Precondition.updateTime(r):Precondition.none()}preconditionForUpdate(e){const r=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&r){if(r.isEqual(SnapshotVersion.min()))throw new FirestoreError(b,"Can't update a document that doesn't exist.");return Precondition.updateTime(r)}return Precondition.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}const ve={maxAttempts:5};class __PRIVATE_TransactionRunner{constructor(e,r,i,s,o){this.asyncQueue=e,this.datastore=r,this.options=i,this.updateFunction=s,this.deferred=o,this.I=i.maxAttempts,this.P=new __PRIVATE_ExponentialBackoff(this.asyncQueue,"transaction_retry")}V(){this.I-=1,this.D()}D(){this.P.A((async()=>{const e=new Transaction$1(this.datastore),r=this.F(e);r&&r.then((r=>{this.asyncQueue.enqueueAndForget((()=>e.commit().then((()=>{this.deferred.resolve(r)})).catch((e=>{this.v(e)}))))})).catch((e=>{this.v(e)}))}))}F(e){try{const r=this.updateFunction(e);return!__PRIVATE_isNullOrUndefined(r)&&r.catch&&r.then?r:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}v(e){this.I>0&&this.B(e)?(this.I-=1,this.asyncQueue.enqueueAndForget((()=>(this.D(),Promise.resolve())))):this.deferred.reject(e)}B(e){if("FirebaseError"===e?.name){const r=e.code;return"aborted"===r||"failed-precondition"===r||"already-exists"===r||!function __PRIVATE_isPermanentError(e){switch(e){case R:return fail(64938);case w:case S:case N:case U:case W:case K:case q:return!1;case b:case O:case M:case L:case j:case $:case z:case Q:case Y:return!0;default:return fail(15467,{code:e})}}(r)}return!1}}function getDocument(){return"undefined"!=typeof document?document:null}class DelayedOperation{constructor(e,r,i,s,o){this.asyncQueue=e,this.timerId=r,this.targetTimeMs=i,this.op=s,this.removalCallback=o,this.deferred=new __PRIVATE_Deferred,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(e,r,i,s,o){const a=Date.now()+i,_=new DelayedOperation(e,r,a,s,o);return _.start(i),_}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new FirestoreError(w,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((e=>this.deferred.resolve(e)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}const we="AsyncQueue";class __PRIVATE_AsyncQueueImpl{constructor(e=Promise.resolve()){this.k=[],this.q=!1,this.O=[],this.S=null,this.C=!1,this.M=!1,this.N=[],this.P=new __PRIVATE_ExponentialBackoff(this,"async_queue_retry"),this.L=()=>{const e=getDocument();e&&__PRIVATE_logDebug(we,"Visibility state changed to "+e.visibilityState),this.P.T()},this.W=e;const r=getDocument();r&&"function"==typeof r.addEventListener&&r.addEventListener("visibilitychange",this.L)}get isShuttingDown(){return this.q}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.U(),this.$(e)}enterRestrictedMode(e){if(!this.q){this.q=!0,this.M=e||!1;const r=getDocument();r&&"function"==typeof r.removeEventListener&&r.removeEventListener("visibilitychange",this.L)}}enqueue(e){if(this.U(),this.q)return new Promise((()=>{}));const r=new __PRIVATE_Deferred;return this.$((()=>this.q&&this.M?Promise.resolve():(e().then(r.resolve,r.reject),r.promise))).then((()=>r.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.k.push(e),this.j())))}async j(){if(0!==this.k.length){try{await this.k[0](),this.k.shift(),this.P.reset()}catch(e){if(!function __PRIVATE_isIndexedDbTransactionError(e){return"IndexedDbTransactionError"===e.name}(e))throw e;__PRIVATE_logDebug(we,"Operation failed with retryable error: "+e)}this.k.length>0&&this.P.A((()=>this.j()))}}$(e){const r=this.W.then((()=>(this.C=!0,e().catch((e=>{this.S=e,this.C=!1;throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ",__PRIVATE_getMessageOrStack(e)),e})).then((e=>(this.C=!1,e))))));return this.W=r,r}enqueueAfterDelay(e,r,i){this.U(),this.N.indexOf(e)>-1&&(r=0);const s=DelayedOperation.createAndSchedule(this,e,r,i,(e=>this.G(e)));return this.O.push(s),s}U(){this.S&&fail(47125,{H:__PRIVATE_getMessageOrStack(this.S)})}verifyOperationInProgress(){}async J(){let e;do{e=this.W,await e}while(e!==this.W)}K(e){for(const r of this.O)if(r.timerId===e)return!0;return!1}X(e){return this.J().then((()=>{this.O.sort(((e,r)=>e.targetTimeMs-r.targetTimeMs));for(const r of this.O)if(r.skipDelay(),"all"!==e&&r.timerId===e)break;return this.J()}))}Y(e){this.N.push(e)}G(e){const r=this.O.indexOf(e);this.O.splice(r,1)}}function __PRIVATE_getMessageOrStack(e){let r=e.message||"";return e.stack&&(r=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),r}class Transaction{constructor(e,r){this._firestore=e,this._transaction=r,this._dataReader=__PRIVATE_newUserDataReader(e)}get(e){const r=__PRIVATE_validateReference(e,this._firestore),i=new __PRIVATE_LiteUserDataWriter(this._firestore);return this._transaction.lookup([r._key]).then((e=>{if(!e||1!==e.length)return fail(24041);const s=e[0];if(s.isFoundDocument())return new DocumentSnapshot(this._firestore,i,s.key,s,r.converter);if(s.isNoDocument())return new DocumentSnapshot(this._firestore,i,r._key,null,r.converter);throw fail(18433,{doc:s})}))}set(e,r,i){const s=__PRIVATE_validateReference(e,this._firestore),o=__PRIVATE_applyFirestoreDataConverter(s.converter,r,i),a=__PRIVATE_parseSetData(this._dataReader,"Transaction.set",s._key,o,null!==s.converter,i);return this._transaction.set(s._key,a),this}update(e,r,i,...s){const o=__PRIVATE_validateReference(e,this._firestore);let a;return a="string"==typeof(r=getModularInstance(r))||r instanceof FieldPath?__PRIVATE_parseUpdateVarargs(this._dataReader,"Transaction.update",o._key,r,i,s):__PRIVATE_parseUpdateData(this._dataReader,"Transaction.update",o._key,r),this._transaction.update(o._key,a),this}delete(e){const r=__PRIVATE_validateReference(e,this._firestore);return this._transaction.delete(r._key),this}}function runTransaction(e,r,i){const s=__PRIVATE_getDatastore(e=__PRIVATE_cast(e,Firestore)),o={...ve,...i};!function __PRIVATE_validateTransactionOptions(e){if(e.maxAttempts<1)throw new FirestoreError(b,"Max attempts must be at least 1")}(o);const a=new __PRIVATE_Deferred;return new __PRIVATE_TransactionRunner(function __PRIVATE_newAsyncQueue(){return new __PRIVATE_AsyncQueueImpl}(),s,o,(i=>r(new Transaction(e,i))),a).V(),a.promise}!function __PRIVATE_registerFirestore(){(function __PRIVATE_setSDKVersion(e){V=e})(`${a}_lite`),s(new Component("firestore/lite",((e,{instanceIdentifier:r,options:i})=>{const s=e.getProvider("app").getImmediate(),o=new Firestore(new __PRIVATE_LiteAuthCredentialsProvider(e.getProvider("auth-internal")),new __PRIVATE_LiteAppCheckTokenProvider(s,e.getProvider("app-check-internal")),function __PRIVATE_databaseIdFromApp(e,r){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new FirestoreError(b,'"projectId" not provided in firebase.initializeApp.');return new DatabaseId(e.options.projectId,r)}(s,r),s);return i&&o._setSettings(i),o}),"PUBLIC").setMultipleInstances(!0)),o("firestore-lite",Re,""),o("firestore-lite",Re,"esm2020")}();export{AggregateField,AggregateQuerySnapshot,Bytes,CollectionReference,DocumentReference,DocumentSnapshot,FieldPath,FieldValue,Firestore,FirestoreError,GeoPoint,Query,QueryCompositeFilterConstraint,QueryConstraint,QueryDocumentSnapshot,QueryEndAtConstraint,QueryFieldFilterConstraint,QueryLimitConstraint,QueryOrderByConstraint,QuerySnapshot,QueryStartAtConstraint,Timestamp,Transaction,VectorValue,WriteBatch,addDoc,aggregateFieldEqual,aggregateQuerySnapshotEqual,and,arrayRemove,arrayUnion,average,collection,collectionGroup,connectFirestoreEmulator,count,deleteDoc,deleteField,doc,documentId,endAt,endBefore,getAggregate,getCount,getDoc,getDocs,getFirestore,increment,initializeFirestore,limit,limitToLast,maximum,minimum,or,orderBy,query,queryEqual,refEqual,runTransaction,serverTimestamp,setDoc,setLogLevel,snapshotEqual,startAfter,startAt,sum,terminate,updateDoc,vector,where,writeBatch};
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import{_registerComponent as e,registerVersion as t,_getProvider,getApp as n,_isFirebaseServerApp as r}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";const o={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const o=e[t],s=t+1<e.length,a=s?e[t+1]:0,i=t+2<e.length,c=i?e[t+2]:0,u=o>>2,l=(3&o)<<4|a>>4;let h=(15&a)<<2|c>>6,d=63&c;i||(d=64,s||(h=64)),r.push(n[u],n[l],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=63&o|128):55296==(64512&o)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++r)),t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=63&o|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=63&o|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const o=e[n++];if(o<128)t[r++]=String.fromCharCode(o);else if(o>191&&o<224){const s=e[n++];t[r++]=String.fromCharCode((31&o)<<6|63&s)}else if(o>239&&o<365){const s=((7&o)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],a=e[n++];t[r++]=String.fromCharCode((15&o)<<12|(63&s)<<6|63&a)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const o=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0;++t;const a=t<e.length?n[e.charAt(t)]:64;++t;const i=t<e.length?n[e.charAt(t)]:64;if(++t,null==o||null==s||null==a||null==i)throw new DecodeBase64StringError;const c=o<<2|s>>4;if(r.push(c),64!==a){const e=s<<4&240|a>>2;if(r.push(e),64!==i){const e=a<<6&192|i;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&function(e){try{return o.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>getDefaults()?.emulatorHosts?.[e])(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]};class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,o=this.errors[e],a=o?function replaceTemplate(e,t){return e.replace(s,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",i=`${this.serviceName}: ${a} (${r}).`;return new FirebaseError(r,i,n)}}const s=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}function mapValues(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function encode(e){if(null==e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map((e=>encode(e)));if("function"==typeof e||"object"==typeof e)return mapValues(e,(e=>encode(e)));throw new Error("Data cannot be encoded in JSON: "+e)}function decode(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case"type.googleapis.com/google.protobuf.Int64Value":case"type.googleapis.com/google.protobuf.UInt64Value":{const t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t}default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map((e=>decode(e))):"function"==typeof e||"object"==typeof e?mapValues(e,(e=>decode(e))):e}const a="functions",i={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class FunctionsError extends FirebaseError{constructor(e,t,n){super(`${a}/${e}`,t||""),this.details=n,Object.setPrototypeOf(this,FunctionsError.prototype)}}function _errorForResponse(e,t){let n,r=function codeForHTTPStatus(e){if(e>=200&&e<300)return"ok";switch(e){case 0:case 500:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),o=r;try{const e=t&&t.error;if(e){const t=e.status;if("string"==typeof t){if(!i[t])return new FunctionsError("internal","internal");r=i[t],o=t}const s=e.message;"string"==typeof s&&(o=s),n=e.details,void 0!==n&&(n=decode(n))}}catch(e){}return"ok"===r?null:new FunctionsError(r,o,n)}class ContextProvider{constructor(e,t,n,o){this.app=e,this.auth=null,this.messaging=null,this.appCheck=null,this.serverAppAppCheckToken=null,r(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.auth=t.getImmediate({optional:!0}),this.messaging=n.getImmediate({optional:!0}),this.auth||t.get().then((e=>this.auth=e),(()=>{})),this.messaging||n.get().then((e=>this.messaging=e),(()=>{})),this.appCheck||o?.get().then((e=>this.appCheck=e),(()=>{}))}async getAuthToken(){if(this.auth)try{const e=await this.auth.getToken();return e?.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){return}}async getAppCheckToken(e){if(this.serverAppAppCheckToken)return this.serverAppAppCheckToken;if(this.appCheck){const t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}const c="us-central1",u=/^data: (.*?)(?:\n|$)/;class FunctionsService{constructor(e,t,n,r,o=c,s=(...e)=>fetch(...e)){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new ContextProvider(e,t,n,r),this.cancelAllRequests=new Promise((e=>{this.deleteService=()=>Promise.resolve(e())}));try{const e=new URL(o);this.customDomain=e.origin+("/"===e.pathname?"":e.pathname),this.region=c}catch(e){this.customDomain=null,this.region=o}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;if(null!==this.emulatorOrigin){return`${this.emulatorOrigin}/${t}/${this.region}/${e}`}return null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}function connectFunctionsEmulator$1(e,t,n){const r=isCloudWorkstation(t);e.emulatorOrigin=`http${r?"s":""}://${t}:${n}`,r&&async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(e.emulatorOrigin+"/backends")}function httpsCallable$1(e,t,n){const callable=r=>function call(e,t,n,r){const o=e._url(t);return callAtURL(e,o,n,r)}(e,t,r,n||{});return callable.stream=(n,r)=>function stream(e,t,n,r){const o=e._url(t);return streamAtURL(e,o,n,r||{})}(e,t,n,r),callable}function getCredentials(e){return e.emulatorOrigin&&isCloudWorkstation(e.emulatorOrigin)?"include":void 0}async function postJSON(e,t,n,r,o){let s;n["Content-Type"]="application/json";try{s=await r(e,{method:"POST",body:JSON.stringify(t),headers:n,credentials:getCredentials(o)})}catch(e){return{status:0,json:null}}let a=null;try{a=await s.json()}catch(e){}return{status:s.status,json:a}}async function makeAuthHeaders(e,t){const n={},r=await e.contextProvider.getContext(t.limitedUseAppCheckTokens);return r.authToken&&(n.Authorization="Bearer "+r.authToken),r.messagingToken&&(n["Firebase-Instance-ID-Token"]=r.messagingToken),null!==r.appCheckToken&&(n["X-Firebase-AppCheck"]=r.appCheckToken),n}async function callAtURL(e,t,n,r){const o={data:n=encode(n)},s=await makeAuthHeaders(e,r),a=function failAfter(e){let t=null;return{promise:new Promise(((n,r)=>{t=setTimeout((()=>{r(new FunctionsError("deadline-exceeded","deadline-exceeded"))}),e)})),cancel:()=>{t&&clearTimeout(t)}}}(r.timeout||7e4),i=await Promise.race([postJSON(t,o,s,e.fetchImpl,e),a.promise,e.cancelAllRequests]);if(a.cancel(),!i)throw new FunctionsError("cancelled","Firebase Functions instance was deleted.");const c=_errorForResponse(i.status,i.json);if(c)throw c;if(!i.json)throw new FunctionsError("internal","Response is not valid JSON object.");let u=i.json.data;if(void 0===u&&(u=i.json.result),void 0===u)throw new FunctionsError("internal","Response is missing data field.");return{data:decode(u)}}async function streamAtURL(e,t,n,r){const o={data:n=encode(n)},s=await makeAuthHeaders(e,r);let a,i,c;s["Content-Type"]="application/json",s.Accept="text/event-stream";try{a=await e.fetchImpl(t,{method:"POST",body:JSON.stringify(o),headers:s,signal:r?.signal,credentials:getCredentials(e)})}catch(e){if(e instanceof Error&&"AbortError"===e.name){const e=new FunctionsError("cancelled","Request was cancelled.");return{data:Promise.reject(e),stream:{[Symbol.asyncIterator]:()=>({next:()=>Promise.reject(e)})}}}const t=_errorForResponse(0,null);return{data:Promise.reject(t),stream:{[Symbol.asyncIterator]:()=>({next:()=>Promise.reject(t)})}}}const l=new Promise(((e,t)=>{i=e,c=t}));r?.signal?.addEventListener("abort",(()=>{const e=new FunctionsError("cancelled","Request was cancelled.");c(e)}));const h=function createResponseStream(e,t,n,r){const processLine=(e,r)=>{const o=e.match(u);if(!o)return;const s=o[1];try{const e=JSON.parse(s);if("result"in e)return void t(decode(e.result));if("message"in e)return void r.enqueue(decode(e.message));if("error"in e){const t=_errorForResponse(0,e);return r.error(t),void n(t)}}catch(e){if(e instanceof FunctionsError)return r.error(e),void n(e)}},o=new TextDecoder;return new ReadableStream({start(t){let s="";return pump();async function pump(){if(r?.aborted){const e=new FunctionsError("cancelled","Request was cancelled");return t.error(e),n(e),Promise.resolve()}try{const{value:a,done:i}=await e.read();if(i)return s.trim()&&processLine(s.trim(),t),void t.close();if(r?.aborted){const r=new FunctionsError("cancelled","Request was cancelled");return t.error(r),n(r),void await e.cancel()}s+=o.decode(a,{stream:!0});const c=s.split("\n");s=c.pop()||"";for(const e of c)e.trim()&&processLine(e.trim(),t);return pump()}catch(e){const r=e instanceof FunctionsError?e:_errorForResponse(0,null);t.error(r),n(r)}}},cancel:()=>e.cancel()})}(a.body.getReader(),i,c,r?.signal);return{stream:{[Symbol.asyncIterator](){const e=h.getReader();return{async next(){const{value:t,done:n}=await e.read();return{value:t,done:n}},return:async()=>(await e.cancel(),{done:!0,value:void 0})}}},data:l}}const l="@firebase/functions",h="0.13.5";function getFunctions(e=n(),t=c){const r=_getProvider(getModularInstance(e),a).getImmediate({identifier:t}),o=getDefaultEmulatorHostnameAndPort("functions");return o&&connectFunctionsEmulator(r,...o),r}function connectFunctionsEmulator(e,t,n){connectFunctionsEmulator$1(getModularInstance(e),t,n)}function httpsCallable(e,t,n){return httpsCallable$1(getModularInstance(e),t,n)}function httpsCallableFromURL(e,t,n){return function httpsCallableFromURL$1(e,t,n){const callable=r=>callAtURL(e,t,r,n||{});return callable.stream=(n,r)=>streamAtURL(e,t,n,r||{}),callable}(getModularInstance(e),t,n)}!function registerFunctions(n){e(new Component(a,((e,{instanceIdentifier:t})=>{const n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),o=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new FunctionsService(n,r,o,s,t)}),"PUBLIC").setMultipleInstances(!0)),t(l,h,n),t(l,h,"esm2020")}();export{FunctionsError,connectFunctionsEmulator,getFunctions,httpsCallable,httpsCallableFromURL};
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,s=()=>{try{return o()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&i(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},c=()=>s()?.config
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as r,_isFirebaseServerApp as n,SDK_VERSION as o}from"https://www.gstatic.com/firebasejs/12.15.0/firebase-app.js";const stringToByteArray$1=function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=63&o|128):55296==(64512&o)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++n)),t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=63&o|128)}return t},s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const o=e[t],s=t+1<e.length,i=s?e[t+1]:0,a=t+2<e.length,l=a?e[t+2]:0,c=o>>2,u=(3&o)<<4|i>>4;let h=(15&i)<<2|l>>6,d=63&l;a||(d=64,s||(h=64)),n.push(r[c],r[u],r[h],r[d])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(stringToByteArray$1(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const o=e[r++];if(o<128)t[n++]=String.fromCharCode(o);else if(o>191&&o<224){const s=e[r++];t[n++]=String.fromCharCode((31&o)<<6|63&s)}else if(o>239&&o<365){const s=((7&o)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{const s=e[r++],i=e[r++];t[n++]=String.fromCharCode((15&o)<<12|(63&s)<<6|63&i)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const o=r[e.charAt(t++)],s=t<e.length?r[e.charAt(t)]:0;++t;const i=t<e.length?r[e.charAt(t)]:64;++t;const a=t<e.length?r[e.charAt(t)]:64;if(++t,null==o||null==s||null==i||null==a)throw new DecodeBase64StringError;const l=o<<2|s>>4;if(n.push(l),64!==i){const e=s<<4&240|i>>2;if(n.push(e),64!==a){const e=i<<6&192|a;n.push(e)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64urlEncodeWithoutPadding=function(e){return function(e){const t=stringToByteArray$1(e);return s.encodeByteArray(t,!0)}(e).replace(/\./g,"")};const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>getDefaults()?.emulatorHosts?.[e])(e);if(!t)return;const r=t.lastIndexOf(":");if(r<=0||r+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const n=parseInt(t.substring(r+1),10);return"["===t[0]?[t.substring(1,r-1),n]:[t.substring(0,r),n]};class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,o=this.errors[e],s=o?function replaceTemplate(e,t){return e.replace(i,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(o,r):"Error",a=`${this.serviceName}: ${s} (${n}).`;return new FirebaseError(n,a,r)}}const i=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const a="firebasestorage.googleapis.com",l="storageBucket";class StorageError extends FirebaseError{constructor(e,t,r=0){super(prependCode(e),`Firebase Storage: ${t} (${prependCode(e)})`),this.status_=r,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,StorageError.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return prependCode(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}var c,u;function prependCode(e){return"storage/"+e}function unknown(){return new StorageError(c.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function retryLimitExceeded(){return new StorageError(c.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function canceled(){return new StorageError(c.CANCELED,"User canceled the upload/download.")}function cannotSliceBlob(){return new StorageError(c.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function invalidArgument(e){return new StorageError(c.INVALID_ARGUMENT,e)}function appDeleted(){return new StorageError(c.APP_DELETED,"The Firebase app was deleted.")}function invalidRootOperation(e){return new StorageError(c.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function invalidFormat(e,t){return new StorageError(c.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function internalError(e){throw new StorageError(c.INTERNAL_ERROR,"Internal error: "+e)}!function(e){e.UNKNOWN="unknown",e.OBJECT_NOT_FOUND="object-not-found",e.BUCKET_NOT_FOUND="bucket-not-found",e.PROJECT_NOT_FOUND="project-not-found",e.QUOTA_EXCEEDED="quota-exceeded",e.UNAUTHENTICATED="unauthenticated",e.UNAUTHORIZED="unauthorized",e.UNAUTHORIZED_APP="unauthorized-app",e.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",e.INVALID_CHECKSUM="invalid-checksum",e.CANCELED="canceled",e.INVALID_EVENT_NAME="invalid-event-name",e.INVALID_URL="invalid-url",e.INVALID_DEFAULT_BUCKET="invalid-default-bucket",e.NO_DEFAULT_BUCKET="no-default-bucket",e.CANNOT_SLICE_BLOB="cannot-slice-blob",e.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",e.NO_DOWNLOAD_URL="no-download-url",e.INVALID_ARGUMENT="invalid-argument",e.INVALID_ARGUMENT_COUNT="invalid-argument-count",e.APP_DELETED="app-deleted",e.INVALID_ROOT_OPERATION="invalid-root-operation",e.INVALID_FORMAT="invalid-format",e.INTERNAL_ERROR="internal-error",e.UNSUPPORTED_ENVIRONMENT="unsupported-environment"}(c||(c={}));class Location{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,t){let r;try{r=Location.makeFromUrl(e,t)}catch(t){return new Location(e,"")}if(""===r.path)return r;throw function invalidDefaultBucket(e){return new StorageError(c.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}(e)}static makeFromUrl(e,t){let r=null;const n="([A-Za-z0-9.\\-_]+)";const o=new RegExp("^gs://"+n+"(/(.*))?$","i");function httpModify(e){e.path_=decodeURIComponent(e.path)}const s=t.replace(/[.]/g,"\\."),i=[{regex:o,indices:{bucket:1,path:3},postModify:function gsModify(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:new RegExp(`^https?://${s}/v[A-Za-z0-9_]+/b/${n}/o(/([^?#]*).*)?$`,"i"),indices:{bucket:1,path:3},postModify:httpModify},{regex:new RegExp(`^https?://${t===a?"(?:storage.googleapis.com|storage.cloud.google.com)":t}/${n}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:httpModify}];for(let t=0;t<i.length;t++){const n=i[t],o=n.regex.exec(e);if(o){const e=o[n.indices.bucket];let t=o[n.indices.path];t||(t=""),r=new Location(e,t),n.postModify(r);break}}if(null==r)throw function invalidUrl(e){return new StorageError(c.INVALID_URL,"Invalid URL '"+e+"'.")}(e);return r}}class FailRequest{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}}function isString(e){return"string"==typeof e||e instanceof String}function isNativeBlob(e){return isNativeBlobDefined()&&e instanceof Blob}function isNativeBlobDefined(){return"undefined"!=typeof Blob}function validateNumber(e,t,r,n){if(n<t)throw invalidArgument(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n>r)throw invalidArgument(`Invalid value for '${e}'. Expected ${r} or less.`)}function makeUrl(e,t,r){let n=t;return null==r&&(n=`https://${t}`),`${r}://${n}/v0${e}`}function makeQueryString(e){const t=encodeURIComponent;let r="?";for(const n in e)if(e.hasOwnProperty(n)){r=r+(t(n)+"="+t(e[n]))+"&"}return r=r.slice(0,-1),r}function isRetryStatusCode(e,t){const r=e>=500&&e<600,n=-1!==[408,429].indexOf(e),o=-1!==t.indexOf(e);return r||n||o}!function(e){e[e.NO_ERROR=0]="NO_ERROR",e[e.NETWORK_ERROR=1]="NETWORK_ERROR",e[e.ABORT=2]="ABORT"}(u||(u={}));class NetworkRequest{constructor(e,t,r,n,o,s,i,a,l,c,u,h=!0,d=!1){this.url_=e,this.method_=t,this.headers_=r,this.body_=n,this.successCodes_=o,this.additionalRetryCodes_=s,this.callback_=i,this.errorCallback_=a,this.timeout_=l,this.progressCallback_=c,this.connectionFactory_=u,this.retry=h,this.isUsingEmulator=d,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise(((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()}))}start_(){const doTheRequest=(e,t)=>{if(t)return void e(!1,new RequestEndStatus(!1,null,!0));const r=this.connectionFactory_();this.pendingConnection_=r;const progressListener=e=>{const t=e.loaded,r=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,r)};null!==this.progressCallback_&&r.addUploadProgressListener(progressListener),r.send(this.url_,this.method_,this.isUsingEmulator,this.body_,this.headers_).then((()=>{null!==this.progressCallback_&&r.removeUploadProgressListener(progressListener),this.pendingConnection_=null;const t=r.getErrorCode()===u.NO_ERROR,n=r.getStatus();if(!t||isRetryStatusCode(n,this.additionalRetryCodes_)&&this.retry){const t=r.getErrorCode()===u.ABORT;return void e(!1,new RequestEndStatus(!1,null,t))}const o=-1!==this.successCodes_.indexOf(n);e(!0,new RequestEndStatus(o,r))}))},backoffDone=(e,t)=>{const r=this.resolve_,n=this.reject_,o=t.connection;if(t.wasSuccessCode)try{const e=this.callback_(o,o.getResponse());!function isJustDef(e){return void 0!==e}(e)?r():r(e)}catch(e){n(e)}else if(null!==o){const e=unknown();e.serverResponse=o.getErrorText(),this.errorCallback_?n(this.errorCallback_(o,e)):n(e)}else if(t.canceled){n(this.appDelete_?appDeleted():canceled())}else{n(retryLimitExceeded())}};this.canceled_?backoffDone(0,new RequestEndStatus(!1,null,!0)):this.backoffId_=function start(e,t,r){let n=1,o=null,s=null,i=!1,a=0;function canceled(){return 2===a}let l=!1;function triggerCallback(...e){l||(l=!0,t.apply(null,e))}function callWithDelay(t){o=setTimeout((()=>{o=null,e(responseHandler,canceled())}),t)}function clearGlobalTimeout(){s&&clearTimeout(s)}function responseHandler(e,...t){if(l)return void clearGlobalTimeout();if(e)return clearGlobalTimeout(),void triggerCallback.call(null,e,...t);if(canceled()||i)return clearGlobalTimeout(),void triggerCallback.call(null,e,...t);let r;n<64&&(n*=2),1===a?(a=2,r=0):r=1e3*(n+Math.random()),callWithDelay(r)}let c=!1;function stop(e){c||(c=!0,clearGlobalTimeout(),l||(null!==o?(e||(a=2),clearTimeout(o),callWithDelay(0)):e||(a=1)))}return callWithDelay(0),s=setTimeout((()=>{i=!0,stop(!0)}),r),stop}(doTheRequest,backoffDone,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&function stop(e){e(!1)}(this.backoffId_),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class RequestEndStatus{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function getBlobBuilder(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function getBlob$1(...e){const t=getBlobBuilder();if(void 0!==t){const r=new t;for(let t=0;t<e.length;t++)r.append(e[t]);return r.getBlob()}if(isNativeBlobDefined())return new Blob(e);throw new StorageError(c.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function decodeBase64(e){if("undefined"==typeof atob)throw function missingPolyFill(e){return new StorageError(c.UNSUPPORTED_ENVIRONMENT,`${e} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}("base-64");return atob(e)}const h={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class StringData{constructor(e,t){this.data=e,this.contentType=t||null}}function dataFromString(e,t){switch(e){case h.RAW:return new StringData(utf8Bytes_(t));case h.BASE64:case h.BASE64URL:return new StringData(base64Bytes_(e,t));case h.DATA_URL:return new StringData(function dataURLBytes_(e){const t=new DataURLParts(e);return t.base64?base64Bytes_(h.BASE64,t.rest):function percentEncodedBytes_(e){let t;try{t=decodeURIComponent(e)}catch(e){throw invalidFormat(h.DATA_URL,"Malformed data URL.")}return utf8Bytes_(t)}(t.rest)}(t),function dataURLContentType_(e){return new DataURLParts(e).contentType}(t))}throw unknown()}function utf8Bytes_(e){const t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n<=127)t.push(n);else if(n<=2047)t.push(192|n>>6,128|63&n);else if(55296==(64512&n)){if(r<e.length-1&&56320==(64512&e.charCodeAt(r+1))){n=65536|(1023&n)<<10|1023&e.charCodeAt(++r),t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}else t.push(239,191,189)}else 56320==(64512&n)?t.push(239,191,189):t.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(t)}function base64Bytes_(e,t){switch(e){case h.BASE64:{const r=-1!==t.indexOf("-"),n=-1!==t.indexOf("_");if(r||n){throw invalidFormat(e,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?")}break}case h.BASE64URL:{const r=-1!==t.indexOf("+"),n=-1!==t.indexOf("/");if(r||n){throw invalidFormat(e,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?")}t=t.replace(/-/g,"+").replace(/_/g,"/");break}}let r;try{r=decodeBase64(t)}catch(t){if(t.message.includes("polyfill"))throw t;throw invalidFormat(e,"Invalid character found")}const n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return n}class DataURLParts{constructor(e){this.base64=!1,this.contentType=null;const t=e.match(/^data:([^,]+)?,/);if(null===t)throw invalidFormat(h.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const r=t[1]||null;null!=r&&(this.base64=function endsWith(e,t){if(!(e.length>=t.length))return!1;return e.substring(e.length-t.length)===t}(r,";base64"),this.contentType=this.base64?r.substring(0,r.length-7):r),this.rest=e.substring(e.indexOf(",")+1)}}class FbsBlob{constructor(e,t){let r=0,n="";isNativeBlob(e)?(this.data_=e,r=e.size,n=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),r=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),r=e.length),this.size_=r,this.type_=n}size(){return this.size_}type(){return this.type_}slice(e,t){if(isNativeBlob(this.data_)){const r=function sliceBlob(e,t,r){return e.webkitSlice?e.webkitSlice(t,r):e.mozSlice?e.mozSlice(t,r):e.slice?e.slice(t,r):null}(this.data_,e,t);return null===r?null:new FbsBlob(r)}{const r=new Uint8Array(this.data_.buffer,e,t-e);return new FbsBlob(r,!0)}}static getBlob(...e){if(isNativeBlobDefined()){const t=e.map((e=>e instanceof FbsBlob?e.data_:e));return new FbsBlob(getBlob$1.apply(null,t))}{const t=e.map((e=>isString(e)?dataFromString(h.RAW,e).data:e.data_));let r=0;t.forEach((e=>{r+=e.byteLength}));const n=new Uint8Array(r);let o=0;return t.forEach((e=>{for(let t=0;t<e.length;t++)n[o++]=e[t]})),new FbsBlob(n,!0)}}uploadData(){return this.data_}}function jsonObjectOrNull(e){let t;try{t=JSON.parse(e)}catch(e){return null}return function isNonArrayObject(e){return"object"==typeof e&&!Array.isArray(e)}(t)?t:null}function lastComponent(e){const t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function noXform_(e,t){return t}class Mapping{constructor(e,t,r,n){this.server=e,this.local=t||e,this.writable=!!r,this.xform=n||noXform_}}let d=null;function getMappings(){if(d)return d;const e=[];e.push(new Mapping("bucket")),e.push(new Mapping("generation")),e.push(new Mapping("metageneration")),e.push(new Mapping("name","fullPath",!0));const t=new Mapping("name");t.xform=function mappingsXformPath(e,t){return function xformPath(e){return!isString(e)||e.length<2?e:lastComponent(e)}(t)},e.push(t);const r=new Mapping("size");return r.xform=function xformSize(e,t){return void 0!==t?Number(t):t},e.push(r),e.push(new Mapping("timeCreated")),e.push(new Mapping("updated")),e.push(new Mapping("md5Hash",null,!0)),e.push(new Mapping("cacheControl",null,!0)),e.push(new Mapping("contentDisposition",null,!0)),e.push(new Mapping("contentEncoding",null,!0)),e.push(new Mapping("contentLanguage",null,!0)),e.push(new Mapping("contentType",null,!0)),e.push(new Mapping("metadata","customMetadata",!0)),d=e,d}function fromResource(e,t,r){const n={type:"file"},o=r.length;for(let e=0;e<o;e++){const o=r[e];n[o.local]=o.xform(n,t[o.server])}return function addRef(e,t){Object.defineProperty(e,"ref",{get:function generateRef(){const r=e.bucket,n=e.fullPath,o=new Location(r,n);return t._makeStorageReference(o)}})}(n,e),n}function fromResourceString(e,t,r){const n=jsonObjectOrNull(t);if(null===n)return null;return fromResource(e,n,r)}function toResourceString(e,t){const r={},n=t.length;for(let o=0;o<n;o++){const n=t[o];n.writable&&(r[n.server]=e[n.local])}return JSON.stringify(r)}const p="prefixes",_="items";function fromResponseString(e,t,r){const n=jsonObjectOrNull(r);if(null===n)return null;return function fromBackendResponse(e,t,r){const n={prefixes:[],items:[],nextPageToken:r.nextPageToken};if(r[p])for(const o of r[p]){const r=o.replace(/\/$/,""),s=e._makeStorageReference(new Location(t,r));n.prefixes.push(s)}if(r[_])for(const o of r[_]){const r=e._makeStorageReference(new Location(t,o.name));n.items.push(r)}return n}(e,t,n)}class RequestInfo{constructor(e,t,r,n){this.url=e,this.method=t,this.handler=r,this.timeout=n,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function handlerCheck(e){if(!e)throw unknown()}function metadataHandler(e,t){return function handler(r,n){const o=fromResourceString(e,n,t);return handlerCheck(null!==o),o}}function downloadUrlHandler(e,t){return function handler(r,n){const o=fromResourceString(e,n,t);return handlerCheck(null!==o),function downloadUrlFromResourceString(e,t,r,n){const o=jsonObjectOrNull(t);if(null===o)return null;if(!isString(o.downloadTokens))return null;const s=o.downloadTokens;if(0===s.length)return null;const i=encodeURIComponent;return s.split(",").map((t=>{const o=e.bucket,s=e.fullPath;return makeUrl("/b/"+i(o)+"/o/"+i(s),r,n)+makeQueryString({alt:"media",token:t})}))[0]}(o,n,e.host,e._protocol)}}function sharedErrorHandler(e){return function errorHandler(t,r){let n;return n=401===t.getStatus()?t.getErrorText().includes("Firebase App Check token is invalid")?function unauthorizedApp(){return new StorageError(c.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}():function unauthenticated(){return new StorageError(c.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again.")}():402===t.getStatus()?function quotaExceeded(e){return new StorageError(c.QUOTA_EXCEEDED,"Quota for bucket '"+e+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}(e.bucket):403===t.getStatus()?function unauthorized(e){return new StorageError(c.UNAUTHORIZED,"User does not have permission to access '"+e+"'.")}(e.path):r,n.status=t.getStatus(),n.serverResponse=r.serverResponse,n}}function objectErrorHandler(e){const t=sharedErrorHandler(e);return function errorHandler(r,n){let o=t(r,n);return 404===r.getStatus()&&(o=function objectNotFound(e){return new StorageError(c.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist.")}(e.path)),o.serverResponse=n.serverResponse,o}}function getMetadata$2(e,t,r){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime,s=new RequestInfo(n,"GET",metadataHandler(e,r),o);return s.errorHandler=objectErrorHandler(t),s}function list$2(e,t,r,n,o){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",r&&r.length>0&&(s.delimiter=r),n&&(s.pageToken=n),o&&(s.maxResults=o);const i=makeUrl(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime,l=new RequestInfo(i,"GET",function listHandler(e,t){return function handler(r,n){const o=fromResponseString(e,t,n);return handlerCheck(null!==o),o}}(e,t.bucket),a);return l.urlParams=s,l.errorHandler=sharedErrorHandler(t),l}function getBytes$1(e,t,r){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol)+"?alt=media",o=e.maxOperationRetryTime,s=new RequestInfo(n,"GET",((e,t)=>t),o);return s.errorHandler=objectErrorHandler(t),void 0!==r&&(s.headers.Range=`bytes=0-${r}`,s.successCodes=[200,206]),s}function metadataForUpload_(e,t,r){const n=Object.assign({},r);return n.fullPath=e.path,n.size=t.size(),n.contentType||(n.contentType=function determineContentType_(e,t){return e&&e.contentType||t&&t.type()||"application/octet-stream"}(null,t)),n}function multipartUpload(e,t,r,n,o){const s=t.bucketOnlyServerUrl(),i={"X-Goog-Upload-Protocol":"multipart"};const a=function genBoundary(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();i["Content-Type"]="multipart/related; boundary="+a;const l=metadataForUpload_(t,n,o),c="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+toResourceString(l,r)+"\r\n--"+a+"\r\nContent-Type: "+l.contentType+"\r\n\r\n",u="\r\n--"+a+"--",h=FbsBlob.getBlob(c,n,u);if(null===h)throw cannotSliceBlob();const d={name:l.fullPath},p=makeUrl(s,e.host,e._protocol),_=e.maxUploadRetryTime,f=new RequestInfo(p,"POST",metadataHandler(e,r),_);return f.urlParams=d,f.headers=i,f.body=h.uploadData(),f.errorHandler=sharedErrorHandler(t),f}class ResumableUploadStatus{constructor(e,t,r,n){this.current=e,this.total=t,this.finalized=!!r,this.metadata=n||null}}function checkResumeHeader_(e,t){let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){handlerCheck(!1)}return handlerCheck(!!r&&-1!==(t||["active"]).indexOf(r)),r}const f=262144;function continueResumableUpload(e,t,r,n,o,s,i,a){const l=new ResumableUploadStatus(0,0);if(i?(l.current=i.current,l.total=i.total):(l.current=0,l.total=n.size()),n.size()!==l.total)throw function serverFileWrongSize(){return new StorageError(c.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}();const u=l.total-l.current;let h=u;o>0&&(h=Math.min(h,o));const d=l.current,p=d+h;let _="";_=0===h?"finalize":u===h?"upload, finalize":"upload";const f={"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":`${l.current}`},g=n.slice(d,p);if(null===g)throw cannotSliceBlob();const m=t.maxUploadRetryTime,b=new RequestInfo(r,"POST",(function handler(e,r){const o=checkResumeHeader_(e,["active","final"]),i=l.current+h,a=n.size();let c;return c="final"===o?metadataHandler(t,s)(e,r):null,new ResumableUploadStatus(i,a,"final"===o,c)}),m);return b.headers=f,b.body=g.uploadData(),b.progressCallback=a||null,b.errorHandler=sharedErrorHandler(e),b}const g={STATE_CHANGED:"state_changed"},m={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function taskStateFromInternalTaskState(e){switch(e){case"running":case"pausing":case"canceling":return m.RUNNING;case"paused":return m.PAUSED;case"success":return m.SUCCESS;case"canceled":return m.CANCELED;default:return m.ERROR}}class Observer{constructor(e,t,r){if(function isFunction(e){return"function"==typeof e}(e)||null!=t||null!=r)this.next=e,this.error=t??void 0,this.complete=r??void 0;else{const t=e;this.next=t.next,this.error=t.error,this.complete=t.complete}}}function async(e){return(...t)=>{Promise.resolve().then((()=>e(...t)))}}class XhrConnection{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=u.NO_ERROR,this.sendPromise_=new Promise((e=>{this.xhr_.addEventListener("abort",(()=>{this.errorCode_=u.ABORT,e()})),this.xhr_.addEventListener("error",(()=>{this.errorCode_=u.NETWORK_ERROR,e()})),this.xhr_.addEventListener("load",(()=>{e()}))}))}send(e,t,r,n,o){if(this.sent_)throw internalError("cannot .send() more than once");if(isCloudWorkstation(e)&&r&&(this.xhr_.withCredentials=!0),this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==o)for(const e in o)o.hasOwnProperty(e)&&this.xhr_.setRequestHeader(e,o[e].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw internalError("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw internalError("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw internalError("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw internalError("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}class XhrTextConnection extends XhrConnection{initXhr(){this.xhr_.responseType="text"}}function newTextConnection(){return new XhrTextConnection}class XhrBytesConnection extends XhrConnection{initXhr(){this.xhr_.responseType="arraybuffer"}}function newBytesConnection(){return new XhrBytesConnection}class XhrBlobConnection extends XhrConnection{initXhr(){this.xhr_.responseType="blob"}}function newBlobConnection(){return new XhrBlobConnection}class UploadTask{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}constructor(e,t,r=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=r,this._mappings=getMappings(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(c.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{const t=this.isExponentialBackoffExpired();if(isRetryStatusCode(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=retryLimitExceeded()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(c.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t,this._start()})),this._promise.then(null,(()=>{}))}_makeProgressCallback(){const e=this._transferred;return t=>this._updateProgress(e+t)}_shouldDoResumable(e){return e.size()>262144}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout((()=>{this.pendingTimeout=void 0,this._continueUpload()}),this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then((([t,r])=>{switch(this._state){case"running":e(t,r);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}}))}_createResumable(){this._resolveToken(((e,t)=>{const r=function createResumableUpload(e,t,r,n,o){const s=t.bucketOnlyServerUrl(),i=metadataForUpload_(t,n,o),a={name:i.fullPath},l=makeUrl(s,e.host,e._protocol),c={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n.size()}`,"X-Goog-Upload-Header-Content-Type":i.contentType,"Content-Type":"application/json; charset=utf-8"},u=toResourceString(i,r),h=e.maxUploadRetryTime,d=new RequestInfo(l,"POST",(function handler(e){let t;checkResumeHeader_(e);try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){handlerCheck(!1)}return handlerCheck(isString(t)),t}),h);return d.urlParams=a,d.headers=c,d.body=u,d.errorHandler=sharedErrorHandler(t),d}(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),n=this._ref.storage._makeRequest(r,newTextConnection,e,t);this._request=n,n.getPromise().then((e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()}),this._errorHandler)}))}_fetchStatus(){const e=this._uploadUrl;this._resolveToken(((t,r)=>{const n=function getResumableUploadStatus(e,t,r,n){const o=e.maxUploadRetryTime,s=new RequestInfo(r,"POST",(function handler(e){const t=checkResumeHeader_(e,["active","final"]);let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){handlerCheck(!1)}r||handlerCheck(!1);const o=Number(r);return handlerCheck(!isNaN(o)),new ResumableUploadStatus(o,n.size(),"final"===t)}),o);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=sharedErrorHandler(t),s}(this._ref.storage,this._ref._location,e,this._blob),o=this._ref.storage._makeRequest(n,newTextConnection,t,r);this._request=o,o.getPromise().then((e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()}),this._errorHandler)}))}_continueUpload(){const e=f*this._chunkMultiplier,t=new ResumableUploadStatus(this._transferred,this._blob.size()),r=this._uploadUrl;this._resolveToken(((n,o)=>{let s;try{s=continueResumableUpload(this._ref._location,this._ref.storage,r,this._blob,e,this._mappings,t,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const i=this._ref.storage._makeRequest(s,newTextConnection,n,o,!1);this._request=i,i.getPromise().then((e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()}),this._errorHandler)}))}_increaseMultiplier(){2*(f*this._chunkMultiplier)<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken(((e,t)=>{const r=getMetadata$2(this._ref.storage,this._ref._location,this._mappings),n=this._ref.storage._makeRequest(r,newTextConnection,e,t);this._request=n,n.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._transition("success")}),this._metadataErrorHandler)}))}_oneShotUpload(){this._resolveToken(((e,t)=>{const r=multipartUpload(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),n=this._ref.storage._makeRequest(r,newTextConnection,e,t);this._request=n,n.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")}),this._errorHandler)}))}_updateProgress(e){const t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":const t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":case"error":case"success":this._state=e,this._notifyObservers();break;case"canceled":this._error=canceled(),this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){const e=taskStateFromInternalTaskState(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,r,n){const o=new Observer(t||void 0,r||void 0,n||void 0);return this._addObserver(o),()=>{this._removeObserver(o)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){const t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();this._observers.slice().forEach((e=>{this._notifyObserver(e)}))}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(taskStateFromInternalTaskState(this._state)){case m.SUCCESS:async(this._resolve.bind(null,this.snapshot))();break;case m.CANCELED:case m.ERROR:async(this._reject.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(taskStateFromInternalTaskState(this._state)){case m.RUNNING:case m.PAUSED:e.next&&async(e.next.bind(e,this.snapshot))();break;case m.SUCCESS:e.complete&&async(e.complete.bind(e))();break;default:e.error&&async(e.error.bind(e,this._error))()}}resume(){const e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){const e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){const e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class Reference{constructor(e,t){this._service=e,this._location=t instanceof Location?t:Location.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new Reference(e,t)}get root(){const e=new Location(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return lastComponent(this._location.path)}get storage(){return this._service}get parent(){const e=function parent(e){if(0===e.length)return null;const t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;const t=new Location(this._location.bucket,e);return new Reference(this._service,t)}_throwIfRoot(e){if(""===this._location.path)throw invalidRootOperation(e)}}function uploadBytes$1(e,t,r){e._throwIfRoot("uploadBytes");const n=multipartUpload(e.storage,e._location,getMappings(),new FbsBlob(t,!0),r);return e.storage.makeRequestWithTokens(n,newTextConnection).then((t=>({metadata:t,ref:e})))}function listAll$1(e){const t={prefixes:[],items:[]};return listAllHelper(e,t).then((()=>t))}async function listAllHelper(e,t,r){const n={pageToken:r},o=await list$1(e,n);t.prefixes.push(...o.prefixes),t.items.push(...o.items),null!=o.nextPageToken&&await listAllHelper(e,t,o.nextPageToken)}function list$1(e,t){null!=t&&"number"==typeof t.maxResults&&validateNumber("options.maxResults",1,1e3,t.maxResults);const r=t||{},n=list$2(e.storage,e._location,"/",r.pageToken,r.maxResults);return e.storage.makeRequestWithTokens(n,newTextConnection)}function updateMetadata$1(e,t){e._throwIfRoot("updateMetadata");const r=function updateMetadata$2(e,t,r,n){const o=makeUrl(t.fullServerUrl(),e.host,e._protocol),s=toResourceString(r,n),i=e.maxOperationRetryTime,a=new RequestInfo(o,"PATCH",metadataHandler(e,n),i);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=objectErrorHandler(t),a}(e.storage,e._location,t,getMappings());return e.storage.makeRequestWithTokens(r,newTextConnection)}function getDownloadURL$1(e){e._throwIfRoot("getDownloadURL");const t=function getDownloadUrl(e,t,r){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime,s=new RequestInfo(n,"GET",downloadUrlHandler(e,r),o);return s.errorHandler=objectErrorHandler(t),s}(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(t,newTextConnection).then((e=>{if(null===e)throw function noDownloadURL(){return new StorageError(c.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}();return e}))}function deleteObject$1(e){e._throwIfRoot("deleteObject");const t=function deleteObject$2(e,t){const r=makeUrl(t.fullServerUrl(),e.host,e._protocol),n=e.maxOperationRetryTime,o=new RequestInfo(r,"DELETE",(function handler(e,t){}),n);return o.successCodes=[200,204],o.errorHandler=objectErrorHandler(t),o}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,newTextConnection)}function _getChild$1(e,t){const r=function child(e,t){const r=t.split("/").filter((e=>e.length>0)).join("/");return 0===e.length?r:e+"/"+r}(e._location.path,t),n=new Location(e._location.bucket,r);return new Reference(e.storage,n)}function refFromPath(e,t){if(e instanceof FirebaseStorageImpl){const r=e;if(null==r._bucket)throw function noDefaultBucket(){return new StorageError(c.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+l+"' property when initializing the app?")}();const n=new Reference(r,r._bucket);return null!=t?refFromPath(n,t):n}return void 0!==t?_getChild$1(e,t):e}function ref$1(e,t){if(t&&function isUrl(e){return/^[A-Za-z]+:\/\//.test(e)}(t)){if(e instanceof FirebaseStorageImpl)return function refFromURL(e,t){return new Reference(e,t)}(e,t);throw invalidArgument("To use ref(service, url), the first argument must be a Storage instance.")}return refFromPath(e,t)}function extractBucket(e,t){const r=t?.[l];return null==r?null:Location.makeFromBucketSpec(r,e)}function connectStorageEmulator$1(e,t,r,n={}){e.host=`${t}:${r}`;const o=isCloudWorkstation(t);o&&async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(`https://${e.host}/b`),e._isUsingEmulator=!0,e._protocol=o?"https":"http";const{mockUserToken:s}=n;s&&(e._overrideAuthToken="string"==typeof s?s:function createMockUserToken(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const r=t||"demo-project",n=e.iat||0,o=e.sub||e.user_id;if(!o)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s={iss:`https://securetoken.google.com/${r}`,aud:r,iat:n,exp:n+3600,auth_time:n,sub:o,user_id:o,firebase:{sign_in_provider:"custom",identities:{}},...e};return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(s)),""].join(".")}(s,e.app.options.projectId))}class FirebaseStorageImpl{constructor(e,t,r,n,o,s=!1){this.app=e,this._authProvider=t,this._appCheckProvider=r,this._url=n,this._firebaseVersion=o,this._isUsingEmulator=s,this._bucket=null,this._host=a,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=n?Location.makeFromBucketSpec(n,this._host):extractBucket(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=Location.makeFromBucketSpec(this._url,e):this._bucket=extractBucket(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){const t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){if(n(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const e=this._appCheckProvider.getImmediate({optional:!0});if(e){return(await e.getToken()).token}return null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach((e=>e.cancel())),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new Reference(this,e)}_makeRequest(e,t,r,n,o=!0){if(this._deleted)return new FailRequest(appDeleted());{const s=function makeRequest(e,t,r,n,o,s,i=!0,a=!1){const l=makeQueryString(e.urlParams),c=e.url+l,u=Object.assign({},e.headers);return function addGmpidHeader_(e,t){t&&(e["X-Firebase-GMPID"]=t)}(u,t),function addAuthHeader_(e,t){null!==t&&t.length>0&&(e.Authorization="Firebase "+t)}(u,r),function addVersionHeader_(e,t){e["X-Firebase-Storage-Version"]="webjs/"+(t??"AppManager")}(u,s),function addAppCheckHeader_(e,t){null!==t&&(e["X-Firebase-AppCheck"]=t)}(u,n),new NetworkRequest(c,e.method,u,e.body,e.successCodes,e.additionalRetryCodes,e.handler,e.errorHandler,e.timeout,e.progressCallback,o,i,a)}(e,this._appId,r,n,t,this._firebaseVersion,o,this._isUsingEmulator);return this._requests.add(s),s.getPromise().then((()=>this._requests.delete(s)),(()=>this._requests.delete(s))),s}}async makeRequestWithTokens(e,t){const[r,n]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,r,n).getPromise()}}const b="@firebase/storage",E="0.14.3",R="storage";function getBytes(e,t){return function getBytesInternal(e,t){e._throwIfRoot("getBytes");const r=getBytes$1(e.storage,e._location,t);return e.storage.makeRequestWithTokens(r,newBytesConnection).then((e=>void 0!==t?e.slice(0,t):e))}(e=getModularInstance(e),t)}function uploadBytes(e,t,r){return uploadBytes$1(e=getModularInstance(e),t,r)}function uploadString(e,t,r,n){return function uploadString$1(e,t,r=h.RAW,n){e._throwIfRoot("uploadString");const o=dataFromString(r,t),s={...n};return null==s.contentType&&null!=o.contentType&&(s.contentType=o.contentType),uploadBytes$1(e,o.data,s)}(e=getModularInstance(e),t,r,n)}function uploadBytesResumable(e,t,r){return function uploadBytesResumable$1(e,t,r){return e._throwIfRoot("uploadBytesResumable"),new UploadTask(e,new FbsBlob(t),r)}(e=getModularInstance(e),t,r)}function getMetadata(e){return function getMetadata$1(e){e._throwIfRoot("getMetadata");const t=getMetadata$2(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(t,newTextConnection)}(e=getModularInstance(e))}function updateMetadata(e,t){return updateMetadata$1(e=getModularInstance(e),t)}function list(e,t){return list$1(e=getModularInstance(e),t)}function listAll(e){return listAll$1(e=getModularInstance(e))}function getDownloadURL(e){return getDownloadURL$1(e=getModularInstance(e))}function deleteObject(e){return deleteObject$1(e=getModularInstance(e))}function ref(e,t){return ref$1(e=getModularInstance(e),t)}function _getChild(e,t){return _getChild$1(e,t)}function getStorage(t=e(),r){t=getModularInstance(t);const n=_getProvider(t,R).getImmediate({identifier:r}),o=getDefaultEmulatorHostnameAndPort("storage");return o&&connectStorageEmulator(n,...o),n}function connectStorageEmulator(e,t,r,n={}){connectStorageEmulator$1(e,t,r,n)}function getBlob(e,t){return function getBlobInternal(e,t){e._throwIfRoot("getBlob");const r=getBytes$1(e.storage,e._location,t);return e.storage.makeRequestWithTokens(r,newBlobConnection).then((e=>void 0!==t?e.slice(0,t):e))}(e=getModularInstance(e),t)}function getStream(e,t){throw new Error("getStream() is only supported by NodeJS builds")}function factory(e,{instanceIdentifier:t}){const r=e.getProvider("app").getImmediate(),n=e.getProvider("auth-internal"),s=e.getProvider("app-check-internal");return new FirebaseStorageImpl(r,n,s,t,o)}!function registerStorage(){t(new Component(R,factory,"PUBLIC").setMultipleInstances(!0)),r(b,E,""),r(b,E,"esm2020")}();export{StorageError,c as StorageErrorCode,h as StringFormat,FbsBlob as _FbsBlob,Location as _Location,g as _TaskEvent,m as _TaskState,UploadTask as _UploadTask,dataFromString as _dataFromString,_getChild,invalidArgument as _invalidArgument,invalidRootOperation as _invalidRootOperation,connectStorageEmulator,deleteObject,getBlob,getBytes,getDownloadURL,getMetadata,getStorage,getStream,list,listAll,ref,updateMetadata,uploadBytes,uploadBytesResumable,uploadString};
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
coveralls
npm dependency request.post({
url,
form: {
json: str
}
}, (err, response, body) => {
cb(err, response, body);
});
User/PII-bearing data flows to an external sink — the classic data-exfiltration shape.
Fix: Confirm no user identifiers reach this sink; redact/hash before sending, or remove the flow.
expand_more 114 low-confidence finding(s)
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const source = fs.readFileSync(filepath, 'utf8');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const head = fs.readFileSync(path.join(dir, '.git', 'HEAD'), 'utf-8').trim();
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return fs.readFileSync(ref, 'utf-8').trim();
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const packedRefsText = fs.readFileSync(packedRefs, 'utf-8');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
let git_commit = process.env.COVERALLS_GIT_COMMIT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
let git_branch = process.env.COVERALLS_GIT_BRANCH;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const match = (process.env.CI_PULL_REQUEST || '').match(/(\d+)$/);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.TRAVIS) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_number = process.env.TRAVIS_BUILD_NUMBER;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.TRAVIS_JOB_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_pull_request = process.env.TRAVIS_PULL_REQUEST;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.TRAVIS_BRANCH;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.DRONE) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.DRONE_BUILD_NUMBER;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_pull_request = process.env.DRONE_PULL_REQUEST;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_committer_name = process.env.DRONE_COMMIT_AUTHOR;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_committer_email = process.env.DRONE_COMMIT_AUTHOR_EMAIL;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.DRONE_COMMIT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.DRONE_BRANCH;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_message = process.env.DRONE_COMMIT_MESSAGE;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.JENKINS_URL || process.env.JENKINS_HOME) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.JENKINS_URL || process.env.JENKINS_HOME) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.BUILD_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_pull_request = process.env.CHANGE_ID || process.env.ghprbPullId;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_pull_request = process.env.CHANGE_ID || process.env.ghprbPullId;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_committer_name = process.env.CHANGE_AUTHOR;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_committer_email = process.env.CHANGE_AUTHOR_EMAIL;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.GIT_COMMIT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.CHANGE_BRANCH || process.env.GIT_BRANCH || process.env.BRANCH_NAME;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.CHANGE_BRANCH || process.env.GIT_BRANCH || process.env.BRANCH_NAME;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.CHANGE_BRANCH || process.env.GIT_BRANCH || process.env.BRANCH_NAME;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.CIRCLECI) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_number = process.env.CIRCLE_WORKFLOW_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_number = process.env.CIRCLE_BUILD_NUM;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.CI_PULL_REQUEST) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const pr = process.env.CI_PULL_REQUEST.split('/pull/');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.CIRCLE_SHA1;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.CIRCLE_BRANCH;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.CI_NAME && process.env.CI_NAME === 'codeship') {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.CI_NAME && process.env.CI_NAME === 'codeship') {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.CI_BUILD_NUMBER;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.CI_COMMIT_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.CI_BRANCH;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_committer_name = process.env.CI_COMMITTER_NAME;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_committer_email = process.env.CI_COMMITTER_EMAIL;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_message = process.env.CI_COMMIT_MESSAGE;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.WERCKER) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.WERCKER_BUILD_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.WERCKER_GIT_COMMIT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.WERCKER_GIT_BRANCH;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.GITLAB_CI) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_number = process.env.CI_BUILD_NAME;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.CI_BUILD_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_pull_request = process.env.CI_MERGE_REQUEST_IID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.CI_BUILD_REF;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.CI_BUILD_REF_NAME;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.APPVEYOR) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_number = process.env.APPVEYOR_BUILD_NUMBER;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.APPVEYOR_BUILD_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.APPVEYOR_REPO_COMMIT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.APPVEYOR_REPO_BRANCH;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.SURF_SHA1) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.SURF_SHA1;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.SURF_REF;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.BUILDKITE) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_number = process.env.BUILDKITE_BUILD_NUMBER;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.BUILDKITE_BUILD_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_pull_request = process.env.BUILDKITE_PULL_REQUEST;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.BUILDKITE_COMMIT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.BUILDKITE_BRANCH;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_committer_name = process.env.BUILDKITE_BUILD_CREATOR;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_committer_email = process.env.BUILDKITE_BUILD_CREATOR_EMAIL;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_message = process.env.BUILDKITE_MESSAGE;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.SEMAPHORE) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.SEMAPHORE_BUILD_NUMBER;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.REVISION;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.BRANCH_NAME;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.TF_BUILD) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.BUILD_BUILDID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_pull_request = process.env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.BUILD_SOURCEVERSION;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.BUILD_SOURCEBRANCHNAME;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.CF_BRANCH) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.CF_BUILD_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_pull_request = process.env.CF_PULL_REQUEST_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_commit = process.env.CF_REVISION;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_branch = process.env.CF_BRANCH;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_committer_name = process.env.CF_COMMIT_AUTHOR;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
git_message = process.env.CF_COMMIT_MESSAGE;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.run_at = process.env.COVERALLS_RUN_AT || JSON.stringify(new Date()).slice(1, -1);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.COVERALLS_SERVICE_NUMBER) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_number = process.env.COVERALLS_SERVICE_NUMBER;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.COVERALLS_SERVICE_JOB_NUMBER) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_number = process.env.COVERALLS_SERVICE_JOB_NUMBER;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.COVERALLS_SERVICE_JOB_ID) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_job_id = process.env.COVERALLS_SERVICE_JOB_ID;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.COVERALLS_PARALLEL) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return yaml.safeLoad(fs.readFileSync(yml, 'utf8'));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.COVERALLS_REPO_TOKEN) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.repo_token = process.env.COVERALLS_REPO_TOKEN;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.COVERALLS_SERVICE_NAME) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.service_name = process.env.COVERALLS_SERVICE_NAME;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.COVERALLS_FLAG_NAME) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.flag_name = process.env.COVERALLS_FLAG_NAME;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (index.options.verbose || process.env.NODE_COVERALLS_DEBUG === 1 || process.env.NODE_COVERALLS_DEBUG === '1') {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (index.options.verbose || process.env.NODE_COVERALLS_DEBUG === 1 || process.env.NODE_COVERALLS_DEBUG === '1') {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.COVERALLS_ENDPOINT) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
urlBase = process.env.COVERALLS_ENDPOINT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
@babel/core
npm dependencyexpand_more 7 low-confidence finding(s)
return fn(filepath, yield* readFile(filepath, "utf8"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const targetPath = process.env.BABEL_SHOW_CONFIG_FOR;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (typeof process !== "undefined" && process.env.BABEL_7_TO_8_DANGEROUSLY_DISABLE_VERSION_CHECK) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const code = yield* readFile(filename, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const inputMapContent = fs.readFileSync(inputMapPath, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
@date-fns/docs
npm dependencyexpand_more 5 low-confidence finding(s)
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const packageStr = await readFile(packagePath, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const markdown = await readFile(path.resolve(configDir, file.path), "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import { readFile } from "fs/promises";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const docsJSON = await readFile(jsonPath, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
@formatjs/intl
npm dependencyexpand_more 2 low-confidence finding(s)
if (process.env.NODE_ENV !== "production") console.error(error);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.NODE_ENV !== "production") console.warn(warning);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
@parcel/watcher
npm dependencyexpand_more 1 low-confidence finding(s)
if (process.env.npm_config_build_from_source === 'true') {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
@react-native/babel-preset
npm dependencyexpand_more 8 low-confidence finding(s)
const {readFileSync} = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const {readFileSync} = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
readFileSync(__filename),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
readFileSync(require.resolve('./configs/main.js')),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
readFileSync(require.resolve('./configs/hmr.js')),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
readFileSync(require.resolve('./configs/lazy-imports.js')),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
readFileSync(require.resolve('./passthrough-syntax-plugins.js')),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
readFileSync(require.resolve('./plugin-warn-on-deep-imports.js')),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
@size-limit/esbuild
npm dependencyexpand_more 1 low-confidence finding(s)
let js = await readFile(bundle)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
@swc/core
npm dependencyexpand_more 14 low-confidence finding(s)
const { readFileSync } = require('fs')
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const { readFileSync } = require('fs')
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl')
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.NAPI_RS_FORCE_WASI) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.NAPI_RS_FORCE_WASI) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const bindingsOverride = process.env["SWC_BINARY_PATH"];
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs_1 = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs_1 = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = __importStar(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const { name } = require(path.resolve(process.env.INIT_CWD, "package.json"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!!process.env["SWC_BINARY_PATH"]) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
fs.writeFileSync(path.join(installDir, "package.json"), "{}");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
fs.renameSync(installedBinPath, path.resolve(process.env.INIT_CWD, "node_modules", `@swc/wasm`));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
firebase-admin
npm dependencyexpand_more 30 low-confidence finding(s)
const fs = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return new ServiceAccount(JSON.parse(fs.readFileSync(filePath, 'utf8')));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
RefreshToken.validateFromJSON(JSON.parse(fs.readFileSync(filePath, 'utf8')));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
ImpersonatedServiceAccount.validateFromJSON(JSON.parse(fs.readFileSync(filePath, 'utf8')));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const config = process.env[exports.FIREBASE_CONFIG_VAR];
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const contents = config.startsWith('{') ? config : fs.readFileSync(config, 'utf8');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return process.env.FIREBASE_AUTH_EMULATOR_HOST;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return process.env.DATA_CONNECT_EMULATOR_HOST;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const emulatorHost = process.env.FIREBASE_DATABASE_EMULATOR_HOST;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return process.env.CLOUD_EVENTARC_EMULATOR_HOST ?? EVENTARC_API;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const source = ce.source ?? process.env.EVENTARC_CLOUD_EVENT_SOURCE;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return process.env['FIREBASE_EXT_URL'] ?? EXTENSIONS_URL;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!validator.isNonEmptyString(process.env['EXT_INSTANCE_ID'])) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
this.extensionInstanceId = process.env['EXT_INSTANCE_ID'];
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const projectId = process.env['PROJECT_ID'];
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const emulatorHost = process.env.CLOUD_TASKS_EMULATOR_HOST?.trim();
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const FIREBASE_REMOTE_CONFIG_URL_BASE = process.env.FIREBASE_REMOTE_CONFIG_URL_BASE || 'https://firebaseremoteconfig.googleapis.com';
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const endpoint = (process.env.STORAGE_EMULATOR_HOST ||
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.STORAGE_EMULATOR_HOST && process.env.FIREBASE_STORAGE_EMULATOR_HOST) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.STORAGE_EMULATOR_HOST && process.env.FIREBASE_STORAGE_EMULATOR_HOST) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const firebaseStorageEmulatorHost = process.env.FIREBASE_STORAGE_EMULATOR_HOST;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.STORAGE_EMULATOR_HOST = `http://${process.env.FIREBASE_STORAGE_EMULATOR_HOST}`;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.STORAGE_EMULATOR_HOST = `http://${process.env.FIREBASE_STORAGE_EMULATOR_HOST}`;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
quotaProjectId = process.env.GOOGLE_CLOUD_QUOTA_PROJECT || quotaProjectId;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
quotaProjectId = process.env.GOOGLE_CLOUD_QUOTA_PROJECT || quotaProjectId;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const projectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const projectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
jscodeshift
npm dependencyexpand_more 15 low-confidence finding(s)
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process: file => JSON.parse(fs.readFileSync(file)),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
fs.readFile(file, async function(err, source) {
if (err) {
updateStatus('error', file, 'File error: ' + err);
callback();
return;
}
source = source.toString();
try {
const jscodeshift = prepareJscodeshift(options);
const out = await transform(
{
path: file,
source: source,
},
{
j: jscodeshift,
jscodeshift: jscodeshift,
stats: options.dry ? stats : empty,
report: msg => report(file, msg),
},
options
);
if (!out || out === source) {
updateStatus(out ? 'nochange' : 'skip', file);
callback();
return;
}
if (options.print) {
console.log(out); // eslint-disable-line no-console
}
if (!options.dry) {
writeFileAtomic(file, out, function(err) {
if (err) {
updateStatus('error', file, 'File writer error: ' + err);
} else {
updateStatus('ok', file);
}
callback();
});
} else {
updateStatus('ok', file);
callback();
}
} catch(err) {
updateStatus(
'error',
file,
'Transformation error ('+ err.message.replace(/\n/g, ' ') + ')\n' + trimStackTrace(err.stack)
);
callback();
}
});
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const content = fs.readFileSync(config, 'utf8');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const source = fs.readFileSync(inputPath, 'utf8');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const expectedOutput = fs.readFileSync(
path.join(fixtureDir, testFilePrefix + `.output.${extension}`),
'utf8'
);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const source = fs.readFileSync(inputPath, 'utf8');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require('fs');
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return fs.readFileSync(filePath).toString();
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
metro
npm dependencyexpand_more 33 low-confidence finding(s)
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
files.map((file) => _fs.default.promises.readFile(file)),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
? _fs.default.readFileSync(assetInfo.files[0])
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return _fs.default.promises.readFile(record.files[i]);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return _fs.default.promises.readFile(lastFile);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return _fs.default.readFileSync(filePath);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
data = _fs.default.readFileSync(
_path.default.resolve(projectRoot, filename),
);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const fs = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const matches = fs
.readFileSync(filename, "utf8")
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.REACT_NATIVE_ENABLE_ASSET_CACHING === true) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
fs.readFileSync(fileAbsolute, "utf8"),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
? _fs.default.readFileSync(secureKey)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
? _fs.default.readFileSync(secureCert)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
_fs.default.readFileSync(fileName, "utf8"),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
file = _fs.default.readFileSync(this.originModulePath, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
_fs.default.readFileSync(this.originModulePath, "utf8"),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
forceColor: process.env.NODE_ENV !== "test",
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var _fs = _interopRequireDefault(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
playwright
npm dependencyexpand_more 244 low-confidence finding(s)
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const source = await import_fs.default.promises.readFile(filePath, "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const yaml2 = import_fs.default.readFileSync(import_path.default.join(__dirname, "copilot-setup-steps.yml"), "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
mcpJson = JSON.parse(import_fs.default.readFileSync(mcpJsonPath, "utf8"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs.default.promises.writeFile(filePath, content, "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const content = await import_fs.default.promises.readFile(import_path.default.join(__dirname, file), "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PWTEST_WATCH) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
pause: !!process.env.PWPAUSE,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.PWDEBUG = "1";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const shardWeights = process.env.PWTEST_SHARD_WEIGHTS;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var cacheDir = process.env.PWTEST_CACHE_DIR || (() => {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.PWDEBUGIMPL && isUnderTest() && source.includes(devSourceInfix))
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
map: JSON.parse(import_fs.default.readFileSync(sourceMapPath, "utf-8")),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const lineCount = import_fs.default.readFileSync(source, "utf8").split("\n").length;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return { cachedCode: import_fs.default.readFileSync(cache.codePath, "utf-8") };
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const cachedCode = import_fs.default.readFileSync(codePath, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs.default.writeFileSync(sourceMapPath, JSON.stringify(map), "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs.default.writeFileSync(dataPath, JSON.stringify(Object.fromEntries(data.entries()), void 0, 2), "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs.default.writeFileSync(codePath, code, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const data = JSON.parse(await import_fs.default.promises.readFile(cache.dataPath, "utf8"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs3 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs2 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PWDEBUGIMPL)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PWDEBUGIMPL)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const frame = parseStackFrame(line, import_path2.default.sep, !!process.env.PWDEBUGIMPL);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
isModule2 = JSON.parse(import_fs2.default.readFileSync(packageJsonPath, "utf8")).type === "module";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
mainField = JSON.parse(import_fs2.default.readFileSync(packageJsonPath, "utf8")).main;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var defaultReporter = process.env.CI ? "dot" : "list";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs7 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs6 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs4 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const configString = import_fs4.default.readFileSync(configFilePath, "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs5 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const code = import_fs5.default.readFileSync(filename, "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const hasPreprocessor = process.env.PW_TEST_SOURCE_TRANSFORM && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE.split(pathSeparator).some((f) => filename.startsWith(f));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const hasPreprocessor = process.env.PW_TEST_SOURCE_TRANSFORM && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE.split(pathSeparator).some((f) => filename.startsWith(f));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const hasPreprocessor = process.env.PW_TEST_SOURCE_TRANSFORM && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE.split(pathSeparator).some((f) => filename.startsWith(f));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const pluginsEpilogue = hasPreprocessor ? [[process.env.PW_TEST_SOURCE_TRANSFORM]] : [];
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.BROWSERSLIST_IGNORE_OLD_DATA = "true";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PW_DISABLE_TS_ESM)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (nodeModule.registerHooks && !process.env.PLAYWRIGHT_FORCE_ASYNC_LOADER) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const producedEnv = [...keys].filter((key) => startingEnv[key] !== process.env[key]).map((key) => [key, process.env[key] ?? null]);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const producedEnv = [...keys].filter((key) => startingEnv[key] !== process.env[key]).map((key) => [key, process.env[key] ?? null]);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var kForceExitTimeout = +(process.env.PWTEST_FORCE_EXIT_TIMEOUT || 3e4);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.JEST_WORKER_ID) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
reporter: [[process.env.CI ? "dot" : "list"]],
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
source = import_fs.default.readFileSync(errorLocation.file, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PLAYWRIGHT_DASHBOARD)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await use(process.env.PLAYWRIGHT_TEST_BASE_URL);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PW_TEST_REUSE_CONTEXT)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const wsEndpoint = process.env.PW_TEST_CONNECT_WS_ENDPOINT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const headers = process.env.PW_TEST_CONNECT_HEADERS ? JSON.parse(process.env.PW_TEST_CONNECT_HEADERS) : void 0;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const headers = process.env.PW_TEST_CONNECT_HEADERS ? JSON.parse(process.env.PW_TEST_CONNECT_HEADERS) : void 0;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
exposeNetwork: process.env.PW_TEST_CONNECT_EXPOSE_NETWORK
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PLAYWRIGHT_NO_COPY_PROMPT)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs.default.promises.writeFile(filePath, errorContextContent, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs13 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
reporter: [[process.env.CI ? "dot" : "list"]],
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.DEBUG_GIT_COMMIT_INFO)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.GITHUB_ACTIONS) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const json = JSON.parse(await fs.promises.readFile(process.env.GITHUB_EVENT_PATH, "utf8"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const json = JSON.parse(await fs.promises.readFile(process.env.GITHUB_EVENT_PATH, "utf8"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
commitHref: `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/commit/${process.env.GITHUB_SHA}`,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
commitHref: `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/commit/${process.env.GITHUB_SHA}`,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
commitHref: `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/commit/${process.env.GITHUB_SHA}`,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
commitHash: process.env.GITHUB_SHA,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
prHref: pr ? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/pull/${pr.number}` : void 0,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
prHref: pr ? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/pull/${pr.number}` : void 0,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
buildHref: `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
buildHref: `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
buildHref: `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.GITLAB_CI) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
commitHref: `${process.env.CI_PROJECT_URL}/-/commit/${process.env.CI_COMMIT_SHA}`,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
commitHref: `${process.env.CI_PROJECT_URL}/-/commit/${process.env.CI_COMMIT_SHA}`,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
commitHash: process.env.CI_COMMIT_SHA,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
buildHref: process.env.CI_JOB_URL,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
branch: process.env.CI_COMMIT_REF_NAME
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.JENKINS_URL && process.env.BUILD_URL) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.JENKINS_URL && process.env.BUILD_URL) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
commitHref: process.env.BUILD_URL,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
commitHash: process.env.GIT_COMMIT,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
branch: process.env.GIT_BRANCH
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env[key.toUpperCase()] = value;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.PLAYWRIGHT_TEST_BASE_URL = url;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PLAYWRIGHT_FORCE_TTY === "false" || process.env.PLAYWRIGHT_FORCE_TTY === "0") {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PLAYWRIGHT_FORCE_TTY === "false" || process.env.PLAYWRIGHT_FORCE_TTY === "0") {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
} else if (process.env.PLAYWRIGHT_FORCE_TTY === "true" || process.env.PLAYWRIGHT_FORCE_TTY === "1") {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
} else if (process.env.PLAYWRIGHT_FORCE_TTY === "true" || process.env.PLAYWRIGHT_FORCE_TTY === "1") {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
} else if (process.env.PLAYWRIGHT_FORCE_TTY) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const sizeMatch = process.env.PLAYWRIGHT_FORCE_TTY.match(/^(\d+)x(\d+)$/);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
ttyWidth = +process.env.PLAYWRIGHT_FORCE_TTY;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.DEBUG_COLORS === "0" || process.env.DEBUG_COLORS === "false" || process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false" || process.env.NO_COLOR !== void 0 && process.env.NO_COLOR !== "")
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.DEBUG_COLORS === "0" || process.env.DEBUG_COLORS === "false" || process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false" || process.env.NO_COLOR !== void 0 && process.env.NO_COLOR !== "")
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.DEBUG_COLORS === "0" || process.env.DEBUG_COLORS === "false" || process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false" || process.env.NO_COLOR !== void 0 && process.env.NO_COLOR !== "")
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.DEBUG_COLORS === "0" || process.env.DEBUG_COLORS === "false" || process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false" || process.env.NO_COLOR !== void 0 && process.env.NO_COLOR !== "")
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.DEBUG_COLORS === "0" || process.env.DEBUG_COLORS === "false" || process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false" || process.env.NO_COLOR !== void 0 && process.env.NO_COLOR !== "")
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.DEBUG_COLORS === "0" || process.env.DEBUG_COLORS === "false" || process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false" || process.env.NO_COLOR !== void 0 && process.env.NO_COLOR !== "")
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
else if (process.env.DEBUG_COLORS || process.env.FORCE_COLOR)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
else if (process.env.DEBUG_COLORS || process.env.FORCE_COLOR)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return parseErrorStack(stack, import_path2.default.sep, !!process.env.PWDEBUGIMPL);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const value = process.env[name];
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const reportName = process.env[`PLAYWRIGHT_${name}_OUTPUT_NAME`] ?? options.fileName ?? options.default?.fileName;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const source = import_fs.default.readFileSync(location.file, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs8 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs3 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
options.onStdErr && !process.env.PW_RUNNER_DEBUG ? "pipe" : "inherit",
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const timeout = +(process.env.PWTEST_CHILD_PROCESS_TIMEOUT || 5 * 60 * 1e3);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs2 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const content = await import_fs3.default.promises.readFile(filePath, "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs4 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
name: process.env.PWTEST_BOT_NAME,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.PWTEST_BLOB_DO_NOT_REMOVE)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.stdin.isTTY && !process.env.PW_TEST_DEBUG_REPORTERS)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return import_path7.default.relative(process.env["GITHUB_WORKSPACE"] ?? "", filePath);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs5 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
attachmentsBaseURL: process.env.PLAYWRIGHT_HTML_ATTACHMENTS_BASE_URL || this._options.attachmentsBaseURL || "data/",
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
host: process.env.PLAYWRIGHT_HTML_HOST || this._options.host,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
port: process.env.PLAYWRIGHT_HTML_PORT ? +process.env.PLAYWRIGHT_HTML_PORT : this._options.port
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
port: process.env.PLAYWRIGHT_HTML_PORT ? +process.env.PLAYWRIGHT_HTML_PORT : this._options.port
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
title: process.env.PLAYWRIGHT_HTML_TITLE || this._options.title,
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.CI || !this._buildResult)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const envValue = process.env.PLAYWRIGHT_HTML_OUTPUT_DIR || process.env.PLAYWRIGHT_HTML_REPORT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const envValue = process.env.PLAYWRIGHT_HTML_OUTPUT_DIR || process.env.PLAYWRIGHT_HTML_REPORT;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const htmlOpenEnv = process.env.PLAYWRIGHT_HTML_OPEN || process.env.PW_TEST_HTML_REPORT_OPEN;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const htmlOpenEnv = process.env.PLAYWRIGHT_HTML_OPEN || process.env.PW_TEST_HTML_REPORT_OPEN;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const value = process.env[name];
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const html = await import_fs5.default.promises.readFile(import_path8.default.join(appFolder, "index.html"), "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs5.default.promises.writeFile(reportIndexFile, html),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
let html = await import_fs5.default.promises.readFile(import_path8.default.join(appFolder, "index.html"), "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs5.default.promises.readFile(import_path8.default.join(appFolder, "report.js"), "utf-8"),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs5.default.promises.readFile(import_path8.default.join(appFolder, "report.css"), "utf-8")
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs5.default.promises.writeFile(reportIndexFile, html);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const buffer = import_fs5.default.readFileSync(a.path);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs5.default.writeFileSync(import_path8.default.join(this._reportFolder, "data", sha1), buffer);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs5.default.writeFileSync(import_path8.default.join(this._reportFolder, "data", sha1), a.body);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
source = import_fs5.default.readFileSync(file, "utf-8") + "\n//";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
source = import_fs5.default.readFileSync(location.file, "utf-8") + "\n//";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs6 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs6.default.promises.writeFile(resolvedOutputFile, reportString);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs7 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
id: process.env[`PLAYWRIGHT_JUNIT_SUITE_ID`] || "",
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
name: process.env[`PLAYWRIGHT_JUNIT_SUITE_NAME`] || "",
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs7.default.promises.writeFile(this.resolvedOutputFile, reportString);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.PW_TEST_DEBUG_REPORTERS)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.stdin.isTTY && !process.env.PW_TEST_DEBUG_REPORTERS)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.PW_TEST_DEBUG_REPORTERS)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.PW_TEST_DEBUG_REPORTERS)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PW_TEST_DEBUG_REPORTERS)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.PW_TEST_DEBUG_REPORTERS && this._didBegin)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.PW_TEST_DEBUG_REPORTERS && this._didBegin)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var DOES_NOT_SUPPORT_UTF8_IN_TERMINAL = process.platform === "win32" && process.env.TERM_PROGRAM !== "vscode" && !process.env.WT_SESSION;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var DOES_NOT_SUPPORT_UTF8_IN_TERMINAL = process.platform === "win32" && process.env.TERM_PROGRAM !== "vscode" && !process.env.WT_SESSION;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.stdin.isTTY && !process.env.PW_TEST_DEBUG_REPORTERS)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PW_TEST_DEBUG_REPORTERS) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PW_TEST_DEBUG_REPORTERS)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PW_TEST_REPORTER) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const name = process.env.PW_TEST_REPORTER;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
reporters.unshift(!process.env.CI ? new line_default() : new dot_default());
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
command.testList = calculateSha13(import_fs8.default.readFileSync(runOptions.testList));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
command.testListInvert = calculateSha13(import_fs8.default.readFileSync(runOptions.testListInvert));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs11 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs9 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const source = await import_fs9.default.promises.readFile(fileName, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs9.default.promises.writeFile(fileName, result);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs9.default.promises.writeFile(fileName, applyPatchWithConflictMarkers(source, result));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs9.default.promises.writeFile(patchFile, patches.join("\n"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs10 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
DEBUG_COLORS: process.env.DEBUG_COLORS === void 0 ? "1" : process.env.DEBUG_COLORS
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
DEBUG_COLORS: process.env.DEBUG_COLORS === void 0 ? "1" : process.env.DEBUG_COLORS
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs12 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const override = lastFailedFileOverride ?? process.env.PLAYWRIGHT_LAST_RUN_OUTPUT_FILE;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const lastRunInfo = JSON.parse(await import_fs12.default.promises.readFile(this._lastRunFile, "utf8"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs12.default.promises.writeFile(this._lastRunFile, JSON.stringify(lastRunInfo, void 0, 2));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (this._startingEnv[key] !== process.env[key])
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
env.push([key, process.env[key] ?? null]);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PWTEST_DEBUG)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
headless: isUnderTest() && process.env.PWTEST_HEADED_FOR_TEST !== "1",
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs14 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const reportJsonl = await import_fs14.default.promises.readFile(reportFile);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs14.default.promises.writeFile(reportFile, content);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
fs7 = require("fs");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
contents = fs7.readFileSync(path7, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
contents = fs7.readFileSync(source, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
r = process.env.DEBUG;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
let val = process.env[key];
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.DEBUG = namespaces;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
delete process.env.DEBUG;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return process.env.DEBUG;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs6 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
let value = process.env[name];
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
value = value === void 0 ? process.env[`npm_config_${name.toLowerCase()}`] : value;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
value = value === void 0 ? process.env[`npm_package_config_${name.toLowerCase()}`] : value;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var cacheDir = process.env.PWTEST_CACHE_DIR || (() => {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.PWDEBUGIMPL && isUnderTest() && source.includes(devSourceInfix))
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
map: JSON.parse(import_fs.default.readFileSync(sourceMapPath, "utf-8")),
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const lineCount = import_fs.default.readFileSync(source, "utf8").split("\n").length;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return { cachedCode: import_fs.default.readFileSync(cache.codePath, "utf-8") };
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const cachedCode = import_fs.default.readFileSync(codePath, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs.default.writeFileSync(sourceMapPath, JSON.stringify(map), "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs.default.writeFileSync(dataPath, JSON.stringify(Object.fromEntries(data.entries()), void 0, 2), "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
import_fs.default.writeFileSync(codePath, code, "utf8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs5 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs2 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const configString = import_fs2.default.readFileSync(configFilePath, "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs3 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
isModule2 = JSON.parse(import_fs3.default.readFileSync(packageJsonPath, "utf8")).type === "module";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
mainField = JSON.parse(import_fs3.default.readFileSync(packageJsonPath, "utf8")).main;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs4 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const code = import_fs4.default.readFileSync(filename, "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const hasPreprocessor = process.env.PW_TEST_SOURCE_TRANSFORM && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE.split(pathSeparator).some((f) => filename.startsWith(f));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const hasPreprocessor = process.env.PW_TEST_SOURCE_TRANSFORM && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE.split(pathSeparator).some((f) => filename.startsWith(f));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const hasPreprocessor = process.env.PW_TEST_SOURCE_TRANSFORM && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE && process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE.split(pathSeparator).some((f) => filename.startsWith(f));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const pluginsEpilogue = hasPreprocessor ? [[process.env.PW_TEST_SOURCE_TRANSFORM]] : [];
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.BROWSERSLIST_IGNORE_OLD_DATA = "true";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PW_DISABLE_TS_ESM)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (nodeModule.registerHooks && !process.env.PLAYWRIGHT_FORCE_ASYNC_LOADER) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const code = import_fs6.default.readFileSync(originalFilename, "utf-8");
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PWDEBUGIMPL)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PWDEBUGIMPL)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const frame = parseStackFrame(line, import_path.default.sep, !!process.env.PWDEBUGIMPL);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
isModule = JSON.parse(import_fs.default.readFileSync(packageJsonPath, "utf8")).type === "module";
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
mainField = JSON.parse(import_fs.default.readFileSync(packageJsonPath, "utf8")).main;
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PWDEBUGIMPL)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (process.env.PWDEBUGIMPL)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
const frame = parseStackFrame(line, import_path.default.sep, !!process.env.PWDEBUGIMPL);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs3 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
var import_fs2 = __toESM(require("fs"));
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
this._liveTraceFile.fs.writeFile(this._liveTraceFile.file, data);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
await import_fs2.default.promises.readFile(sourceFile, "utf8").then((source) => {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
contentPromise = import_fs2.default.promises.readFile(attachment.path).catch(() => void 0);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.TEST_WORKER_INDEX = String(params.workerIndex);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
process.env.TEST_PARALLEL_INDEX = String(params.parallelIndex);
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
if (!process.env.PW_RUNNER_DEBUG) {
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
size-limit
npm dependencyexpand_more 2 low-confidence finding(s)
await writeFile(entry, loader)
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
return JSON.parse(await readFile(filePath, 'utf8'))
Reads environment variables or the filesystem — an inventory-level capability, not a leak on its own.
Fix: Usually benign; confirm any secret read here is not later sent externally.
Skipped dependencies
Development
- oxfmt dev — dist-only: no readable source
- oxlint dev — dist-only: no readable source
- @date-fns/dev dev — registry 404
- @vitest/coverage-v8 dev — dist-only: no readable source
- cloc dev — no javascript source
- glob dev — dist-only: no readable source
- minimatch dev — dist-only: no readable source
- tinybench dev — dist-only: no readable source
- @deno/doc dev — registry 404
- tsx dev — dist-only: no readable source