From 88651e1bc19f69cb16cddd730a79e63f1d2d6a65 Mon Sep 17 00:00:00 2001 From: Jody Date: Sun, 14 Jun 2026 16:20:13 -0600 Subject: [PATCH 1/4] Deploy --- dist/.DS_Store | Bin 0 -> 6148 bytes .../{index-BEzP6REc.js => index-HXjiAoNO.js} | 6 +++--- dist/index.html | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) create mode 100644 dist/.DS_Store rename dist/assets/{index-BEzP6REc.js => index-HXjiAoNO.js} (92%) diff --git a/dist/.DS_Store b/dist/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..c133dc5bbdbf6cadd9693a5e0dacb9c39cd34757 GIT binary patch literal 6148 zcmeHKO-@2F5S~$Dnz&)92k)OAz}z7!>m}g4osy50LnGG2z2QsBqtgs!>kAo zgf$hYscbCf8+q`gjI_k#~PMj2db_Se*E(6!P?92H-#$Tq| zSI85sBhS6(lT literal 0 HcmV?d00001 diff --git a/dist/assets/index-BEzP6REc.js b/dist/assets/index-HXjiAoNO.js similarity index 92% rename from dist/assets/index-BEzP6REc.js rename to dist/assets/index-HXjiAoNO.js index 320c850..5dba374 100644 --- a/dist/assets/index-BEzP6REc.js +++ b/dist/assets/index-HXjiAoNO.js @@ -64,7 +64,7 @@ Error generating stack: `+s.message+` * LICENSE.md file in the root directory of this source tree. * * @license MIT - */const uC="6";try{window.__reactRouterVersion=uC}catch{}const cC="startTransition",bf=i0[cC];function dC(t){let{basename:e,children:n,future:r,window:i}=t,s=C.useRef();s.current==null&&(s.current=gS({window:i,v5Compat:!0}));let o=s.current,[l,a]=C.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},h=C.useCallback(d=>{u&&bf?bf(()=>a(d)):a(d)},[a,u]);return C.useLayoutEffect(()=>o.listen(h),[o,h]),C.useEffect(()=>sC(r),[r]),C.createElement(lC,{basename:e,children:n,location:l.location,navigationType:l.action,navigator:o,future:r})}var Pf;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(Pf||(Pf={}));var Nf;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(Nf||(Nf={}));const hC="prof123";function fC(){const t=Sr(),[e,n]=C.useState(!1),[r,i]=C.useState(""),[s,o]=C.useState("");function l(a){a.preventDefault(),r===hC?(localStorage.setItem("role","teacher"),t("/teacher")):(o("Incorrect password."),i(""))}return c.jsxs("div",{style:Se.page,children:[c.jsxs("div",{style:Se.header,children:[c.jsx("div",{style:Se.logoMark,children:"●"}),c.jsx("span",{style:Se.logoText,children:"ClassPoll"})]}),c.jsxs("div",{style:Se.hero,className:"fade-up",children:[c.jsxs("h1",{style:Se.title,children:["Live Classroom",c.jsx("br",{}),"Polling"]}),c.jsx("p",{style:Se.sub,children:"Real-time polls, instant results, zero setup for students."})]}),c.jsxs("div",{style:Se.cards,className:"fade-up",children:[c.jsxs("button",{style:Se.roleCard,onClick:()=>t("/student"),children:[c.jsx("span",{style:Se.roleIcon,children:"πŸŽ“"}),c.jsx("span",{style:Se.roleLabel,children:"I'm a Student"}),c.jsx("span",{style:Se.roleHint,children:"Join and answer polls"})]}),e?c.jsxs("form",{style:{...Se.roleCard,gap:"0.75rem"},onSubmit:l,children:[c.jsx("span",{style:Se.roleIcon,children:"πŸ”‘"}),c.jsx("span",{style:Se.roleLabel,children:"Teacher Password"}),c.jsx("input",{className:"input",type:"password",placeholder:"Enter password",value:r,onChange:a=>{i(a.target.value),o("")},autoFocus:!0,style:{textAlign:"center"}}),s&&c.jsx("span",{style:Se.err,children:s}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{width:"100%",justifyContent:"center"},children:"Enter"}),c.jsx("button",{type:"button",className:"btn btn-secondary",style:{width:"100%",justifyContent:"center",fontSize:"0.85rem"},onClick:()=>{n(!1),o(""),i("")},children:"Cancel"})]}):c.jsxs("button",{style:Se.roleCard,onClick:()=>n(!0),children:[c.jsx("span",{style:Se.roleIcon,children:"πŸ“‹"}),c.jsx("span",{style:Se.roleLabel,children:"I'm the Teacher"}),c.jsx("span",{style:Se.roleHint,children:"Create and manage polls"})]})]}),c.jsx("a",{href:"/classroom-polling/history",style:Se.historyLink,children:"View Poll History β†’"})]})}const Se={page:{minHeight:"100vh",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"2rem 1rem",gap:"2rem",background:"var(--paper)"},header:{position:"fixed",top:0,left:0,right:0,padding:"1rem 2rem",display:"flex",alignItems:"center",gap:"0.5rem",borderBottom:"1px solid var(--border)",background:"var(--paper)"},logoMark:{color:"var(--accent)",fontSize:"1.2rem"},logoText:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem"},hero:{textAlign:"center"},title:{fontSize:"clamp(2.2rem, 6vw, 3.5rem)",lineHeight:1.1,marginBottom:"0.75rem"},sub:{color:"var(--muted)",fontSize:"1.05rem",maxWidth:"30ch",margin:"0 auto"},cards:{display:"flex",gap:"1.25rem",flexWrap:"wrap",justifyContent:"center"},roleCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:"0.5rem",padding:"2rem 2.5rem",borderRadius:"16px",border:"2px solid var(--border)",cursor:"pointer",transition:"all 0.2s",background:"white",minWidth:"200px",boxShadow:"var(--shadow)"},roleIcon:{fontSize:"2.5rem"},roleLabel:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.15rem"},roleHint:{fontSize:"0.82rem",color:"var(--muted)"},err:{color:"var(--accent)",fontSize:"0.85rem"},historyLink:{color:"var(--muted)",fontSize:"0.85rem",textDecoration:"underline",cursor:"pointer"}},pC="modulepreload",mC=function(t){return"/classroom-polling/"+t},Rf={},gC=function(e,n,r){let i=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.allSettled(n.map(a=>{if(a=mC(a),a in Rf)return;Rf[a]=!0;const u=a.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${a}"]${h}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":pC,u||(d.as="script"),d.crossOrigin="",d.href=a,l&&d.setAttribute("nonce",l),document.head.appendChild(d),u)return new Promise((f,v)=>{d.addEventListener("load",f),d.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${a}`)))})}))}function s(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&s(l.reason);return e().catch(s)})};var Af={};/** + */const uC="6";try{window.__reactRouterVersion=uC}catch{}const cC="startTransition",bf=i0[cC];function dC(t){let{basename:e,children:n,future:r,window:i}=t,s=C.useRef();s.current==null&&(s.current=gS({window:i,v5Compat:!0}));let o=s.current,[l,a]=C.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},h=C.useCallback(d=>{u&&bf?bf(()=>a(d)):a(d)},[a,u]);return C.useLayoutEffect(()=>o.listen(h),[o,h]),C.useEffect(()=>sC(r),[r]),C.createElement(lC,{basename:e,children:n,location:l.location,navigationType:l.action,navigator:o,future:r})}var Pf;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(Pf||(Pf={}));var Nf;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(Nf||(Nf={}));const hC="changeme";function fC(){const t=Sr(),[e,n]=C.useState(!1),[r,i]=C.useState(""),[s,o]=C.useState("");function l(a){a.preventDefault(),r===hC?(localStorage.setItem("role","teacher"),t("/teacher")):(o("Incorrect password."),i(""))}return c.jsxs("div",{style:Se.page,children:[c.jsxs("div",{style:Se.header,children:[c.jsx("div",{style:Se.logoMark,children:"●"}),c.jsx("span",{style:Se.logoText,children:"ClassPoll"})]}),c.jsxs("div",{style:Se.hero,className:"fade-up",children:[c.jsxs("h1",{style:Se.title,children:["Live Classroom",c.jsx("br",{}),"Polling"]}),c.jsx("p",{style:Se.sub,children:"Real-time polls, instant results, zero setup for students."})]}),c.jsxs("div",{style:Se.cards,className:"fade-up",children:[c.jsxs("button",{style:Se.roleCard,onClick:()=>t("/student"),children:[c.jsx("span",{style:Se.roleIcon,children:"πŸŽ“"}),c.jsx("span",{style:Se.roleLabel,children:"I'm a Student"}),c.jsx("span",{style:Se.roleHint,children:"Join and answer polls"})]}),e?c.jsxs("form",{style:{...Se.roleCard,gap:"0.75rem"},onSubmit:l,children:[c.jsx("span",{style:Se.roleIcon,children:"πŸ”‘"}),c.jsx("span",{style:Se.roleLabel,children:"Teacher Password"}),c.jsx("input",{className:"input",type:"password",placeholder:"Enter password",value:r,onChange:a=>{i(a.target.value),o("")},autoFocus:!0,style:{textAlign:"center"}}),s&&c.jsx("span",{style:Se.err,children:s}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{width:"100%",justifyContent:"center"},children:"Enter"}),c.jsx("button",{type:"button",className:"btn btn-secondary",style:{width:"100%",justifyContent:"center",fontSize:"0.85rem"},onClick:()=>{n(!1),o(""),i("")},children:"Cancel"})]}):c.jsxs("button",{style:Se.roleCard,onClick:()=>n(!0),children:[c.jsx("span",{style:Se.roleIcon,children:"πŸ“‹"}),c.jsx("span",{style:Se.roleLabel,children:"I'm the Teacher"}),c.jsx("span",{style:Se.roleHint,children:"Create and manage polls"})]})]}),c.jsx("a",{href:"/classroom-polling/history",style:Se.historyLink,children:"View Poll History β†’"})]})}const Se={page:{minHeight:"100vh",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"2rem 1rem",gap:"2rem",background:"var(--paper)"},header:{position:"fixed",top:0,left:0,right:0,padding:"1rem 2rem",display:"flex",alignItems:"center",gap:"0.5rem",borderBottom:"1px solid var(--border)",background:"var(--paper)"},logoMark:{color:"var(--accent)",fontSize:"1.2rem"},logoText:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem"},hero:{textAlign:"center"},title:{fontSize:"clamp(2.2rem, 6vw, 3.5rem)",lineHeight:1.1,marginBottom:"0.75rem"},sub:{color:"var(--muted)",fontSize:"1.05rem",maxWidth:"30ch",margin:"0 auto"},cards:{display:"flex",gap:"1.25rem",flexWrap:"wrap",justifyContent:"center"},roleCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:"0.5rem",padding:"2rem 2.5rem",borderRadius:"16px",border:"2px solid var(--border)",cursor:"pointer",transition:"all 0.2s",background:"white",minWidth:"200px",boxShadow:"var(--shadow)"},roleIcon:{fontSize:"2.5rem"},roleLabel:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.15rem"},roleHint:{fontSize:"0.82rem",color:"var(--muted)"},err:{color:"var(--accent)",fontSize:"0.85rem"},historyLink:{color:"var(--muted)",fontSize:"0.85rem",textDecoration:"underline",cursor:"pointer"}},pC="modulepreload",mC=function(t){return"/classroom-polling/"+t},Rf={},gC=function(e,n,r){let i=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.allSettled(n.map(a=>{if(a=mC(a),a in Rf)return;Rf[a]=!0;const u=a.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${a}"]${h}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":pC,u||(d.as="script"),d.crossOrigin="",d.href=a,l&&d.setAttribute("nonce",l),document.head.appendChild(d),u)return new Promise((f,v)=>{d.addEventListener("load",f),d.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${a}`)))})}))}function s(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&s(l.reason);return e().catch(s)})};var Af={};/** * @license * Copyright 2017 Google LLC * @@ -2722,7 +2722,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */const sb=5*60,ob=kv("authIdTokenMaxAge")||sb;let Fp=null;const lb=t=>async e=>{const n=e&&await e.getIdTokenResult(),r=n&&(new Date().getTime()-Date.parse(n.issuedAtTime))/1e3;if(r&&r>ob)return;const i=n==null?void 0:n.token;Fp!==i&&(Fp=i,await fetch(t,{method:i?"POST":"DELETE",headers:i?{Authorization:`Bearer ${i}`}:{}}))};function ab(t=Av()){const e=Ed(t,"auth");if(e.isInitialized())return e.getImmediate();const n=UT(t,{popupRedirectResolver:tb,persistence:[h1,e1,__]}),r=kv("authTokenSyncURL");if(r&&typeof isSecureContext=="boolean"&&isSecureContext){const s=new URL(r,location.origin);if(location.origin===s.origin){const o=lb(s.toString());JT(n,o,()=>o(n.currentUser)),YT(n,l=>o(l))}}const i=xv("auth");return i&&BT(n,`http://${i}`),n}function ub(){var t,e;return(e=(t=document.getElementsByTagName("head"))===null||t===void 0?void 0:t[0])!==null&&e!==void 0?e:document}LT({loadJS(t){return new Promise((e,n)=>{const r=document.createElement("script");r.setAttribute("src",t),r.onload=e,r.onerror=i=>{const s=Ut("internal-error");s.customData=i,n(s)},r.type="text/javascript",r.charset="UTF-8",ub().appendChild(r)})},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="});ib("Browser");const cb={apiKey:"AIzaSyBiZSV4Z_3-L0z8RP5yY_2xXlw5fKOy2jc",authDomain:"classroom-polling-dd344.firebaseapp.com",databaseURL:"https://classroom-polling-dd344-default-rtdb.firebaseio.com",projectId:"classroom-polling-dd344",storageBucket:"classroom-polling-dd344.firebasestorage.app",messagingSenderId:"528103899828",appId:"1:528103899828:web:f74274640de611a61d0de1"},k_=Rv(cb),re=aT(k_),db=ab(k_);GT(db).catch(console.error);function T_(t){const e=new Date().toLocaleDateString("en-CA");return on(ne(re,`session/students/${t}`),{joinedAt:Sp(),date:e}),on(ne(re,`sessionStudents/${e}_${t}`),{name:t,date:e,joinedAt:Sp()})}function vc(t){return vr(ne(re,`session/students/${t}`))}function b_(t,e,n){return sa(ne(re,"session/activePoll/responses"),{[t]:n})}function Pl({question:t,options:e,correctIndex:n,duration:r,resultPolicy:i,correctPolicy:s}){const o=`poll_${Date.now()}`;return on(ne(re,"session/activePoll"),{id:o,question:t,options:e,correctIndex:n??null,duration:r,resultPolicy:i,correctPolicy:s,startedAt:Date.now(),responses:{},ended:!1,revealResults:!1,revealCorrect:!1})}async function Do(t,e){const[n,r]=await Promise.all([Ns(ne(re,"session/activePoll")),Ns(ne(re,"session/queue"))]),i=n.val(),s=r.val();if(!i)return;const o={...i,revealResults:t,revealCorrect:e,endedAt:Date.now()};return s&&(o.setId=s.setId,o.setName=s.setName,o.setPosition=s.currentIndex,o.sessionKey=s.sessionKey),await on(ne(re,`pollHistory/${i.id}`),o),vr(ne(re,"session/activePoll"))}function P_(){return sa(ne(re,"session/activePoll"),{ended:!0})}function yc(t,e){return sa(ne(re,"session/activePoll"),{revealResults:t,revealCorrect:e})}function dh(t){const e=ne(re,"session/activePoll");return xr(e,n=>t(n.val()))}function N_(t){const e=ne(re,"session/students");return xr(e,n=>{const r=n.val()||{};t(Object.keys(r).map(i=>({name:i,...r[i]})))})}function R_(t){const e=ne(re,"pollHistory");return xr(e,n=>{const r=n.val()||{},i=Object.values(r).sort((s,o)=>(o.startedAt||0)-(s.startedAt||0));t(i)})}function A_(t){const e=ne(re,"pollSets");return xr(e,n=>{const r=n.val()||{},i=Object.entries(r).map(([s,o])=>({id:s,...o})).sort((s,o)=>(o.createdAt||0)-(s.createdAt||0));t(i)})}async function _c({name:t,defaults:e,polls:n}){const r=`set_${Date.now()}`;return await on(ne(re,`pollSets/${r}`),{id:r,name:t,createdAt:Date.now(),defaults:e,polls:n||[]}),r}function Lo(t,e){return Ns(ne(re,`pollSets/${t}`)).then(n=>{const r=n.val()||{};return on(ne(re,`pollSets/${t}`),{...r,...e})})}function O_(t){return vr(ne(re,`pollSets/${t}`))}function D_(t,e){const n=ne(re,`pollSets/${t}`);return xr(n,r=>e(r.val()))}function L_(t,e,n){const r=`run_${Date.now()}`;return on(ne(re,"session/queue"),{setId:t,setName:e,currentIndex:0,totalPolls:n,sessionKey:r})}function M_(t){return sa(ne(re,"session/queue"),{currentIndex:t})}function wc(){return vr(ne(re,"session/queue"))}function j_(t){const e=ne(re,"session/queue");return xr(e,n=>t(n.val()))}async function F_(t,e){const r=(await Ns(ne(re,"session/activePoll"))).val(),s=(await Ns(ne(re,"session/queue"))).val();if(!r)return;const o={...r,revealResults:t,revealCorrect:e,endedAt:Date.now()};return s&&(o.setId=s.setId,o.setName=s.setName,o.setPosition=s.currentIndex,o.sessionKey=s.sessionKey),await on(ne(re,`pollHistory/${r.id}`),o),vr(ne(re,"session/activePoll"))}const hb=Object.freeze(Object.defineProperty({__proto__:null,advanceQueue:M_,clearQueue:wc,closePoll:F_,createPollSet:_c,deletePollSet:O_,endPoll:Do,expirePoll:P_,joinSession:T_,launchSet:L_,leaveSession:vc,revealPollResults:yc,startPoll:Pl,submitAnswer:b_,updatePollSet:Lo,watchActivePoll:dh,watchPollHistory:R_,watchPollSet:D_,watchPollSets:A_,watchQueue:j_,watchStudents:N_},Symbol.toStringTag,{value:"Module"})),Up=60,fb=[{value:"on_submit",label:"After they submit"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}],pb=[{value:"with_results",label:"With results"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}];function mb(){var Ge;const t=Sr(),[e,n]=C.useState([]),[r,i]=C.useState(null),[s,o]=C.useState(0),[l,a]=C.useState("dashboard"),[u,h]=C.useState(null),[d,f]=C.useState(null),v=C.useRef(null),w=C.useRef(null),_=C.useRef(null),[E,g]=C.useState(""),[p,m]=C.useState(["",""]),[S,I]=C.useState(null),[P,b]=C.useState(Up),[A,q]=C.useState("on_submit"),[z,pe]=C.useState("with_results");C.useEffect(()=>{localStorage.getItem("role")!=="teacher"&&t("/")},[]),C.useEffect(()=>{const L=dh(xe=>{xe&&(_.current=xe),i(xe),xe&&!xe.ended&&o(Math.max(0,Math.round(xe.duration-(Date.now()-xe.startedAt)/1e3)))}),te=N_(n),Te=j_(xe=>{h(xe),xe!=null&&xe.setId?(w.current&&w.current(),gC(async()=>{const{watchPollSet:Ir}=await Promise.resolve().then(()=>hb);return{watchPollSet:Ir}},void 0).then(({watchPollSet:Ir})=>{w.current=Ir(xe.setId,f)})):(f(null),_.current=null,w.current&&(w.current(),w.current=null))});return()=>{L(),te(),Te()}},[]),C.useEffect(()=>(clearInterval(v.current),r&&!r.ended&&(v.current=setInterval(()=>{const L=Math.max(0,Math.round(r.duration-(Date.now()-r.startedAt)/1e3));o(L),L===0&&(clearInterval(v.current),P_())},500)),()=>clearInterval(v.current)),[r==null?void 0:r.id,r==null?void 0:r.ended]);function D(){p.length<6&&m([...p,""])}function Y(L,te){m(p.map((Te,xe)=>xe===L?te:Te))}function X(L){if(p.length<=2)return;const te=p.filter((Te,xe)=>xe!==L);m(te),S===L?I(null):S>L&&I(S-1)}function et(L){L.preventDefault();const te=p.filter(Te=>Te.trim());!E.trim()||te.length<2||(Pl({question:E.trim(),options:te,correctIndex:S,duration:P,resultPolicy:A,correctPolicy:z}),g(""),m(["",""]),I(null),b(Up),q("on_submit"),pe("with_results"),a("dashboard"))}async function Ee(){if(!u||!d)return;const L=u.currentIndex+1;if(r&&await Do(r.revealResults||!1,r.revealCorrect||!1),L>=u.totalPolls){await wc();return}await M_(L);const te=d.defaults||{},Te=(d.polls||[])[L];Te&&await Pl({question:Te.question,options:Te.options,correctIndex:Te.correctIndex??null,duration:Te.duration??te.duration??60,resultPolicy:Te.resultPolicy??te.resultPolicy??"on_submit",correctPolicy:Te.correctPolicy??te.correctPolicy??"with_results"})}async function Be(){r&&await Do(r.revealResults||!1,r.revealCorrect||!1),await wc()}const R=r?Object.keys(r.responses||{}).length:Object.keys(((Ge=_.current)==null?void 0:Ge.responses)||{}).length,U=r==null?void 0:r.ended,y=!!u,x=u&&u.currentIndex>=u.totalPolls-1,T=r||(y?_.current:null),O=!r&&T;function K(L){return L.revealResults?!0:!(L.resultPolicy==="never"||L.resultPolicy==="manual")}function tt(L){return L.revealCorrect?!0:L.correctPolicy==="never"||L.correctPolicy==="manual"?!1:!!(L.correctPolicy==="with_results"&&K(L))}return c.jsxs("div",{style:j.page,children:[c.jsxs("aside",{style:j.sidebar,children:[c.jsxs("div",{style:j.logo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsxs("nav",{style:j.nav,children:[c.jsx("button",{style:{...j.navBtn,...l==="dashboard"?j.navActive:{}},onClick:()=>a("dashboard"),children:"πŸ“Š Dashboard"}),c.jsx("button",{style:{...j.navBtn,...l==="create"?j.navActive:{},...r?j.navDisabled:{}},onClick:()=>!r&&a("create"),disabled:!!r,children:"βž• New Poll"}),c.jsx("button",{style:j.navBtn,onClick:()=>t("/pollsets"),children:"πŸ“š Poll Sets"}),c.jsx("button",{style:j.navBtn,onClick:()=>t("/history"),children:"πŸ• History"})]}),c.jsxs("div",{style:j.sidebarBottom,children:[c.jsxs("div",{style:j.studentCount,children:[c.jsx("span",{style:j.dot}),c.jsx("strong",{children:e.length})," student",e.length!==1?"s":""," online"]}),c.jsx("div",{style:j.studentList,children:e.map(L=>c.jsx("div",{style:j.studentChip,children:L.name},L.name))}),c.jsx("button",{className:"btn btn-secondary",style:{width:"100%",marginTop:"auto",fontSize:"0.8rem"},onClick:()=>{localStorage.removeItem("role"),localStorage.removeItem("historyAuth"),t("/")},children:"Exit"})]})]}),c.jsxs("main",{style:j.main,children:[l==="create"&&c.jsxs("div",{style:j.content,className:"fade-up",children:[c.jsx("h2",{style:j.pageTitle,children:"Create a Poll"}),c.jsxs("form",{onSubmit:et,style:j.form,children:[c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Question"}),c.jsx("textarea",{className:"input",rows:2,placeholder:"e.g. Which process converts sunlight into energy?",value:E,onChange:L=>g(L.target.value),style:{resize:"vertical",width:"100%"},required:!0})]}),c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Answer Options"}),c.jsx("p",{style:j.hint,children:"Click a letter circle to mark the correct answer (optional)"}),c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:p.map((L,te)=>c.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[c.jsx("button",{type:"button",style:{...j.correctBtn,...S===te?j.correctBtnActive:{}},onClick:()=>I(S===te?null:te),children:S===te?"βœ“":String.fromCharCode(65+te)}),c.jsx("input",{className:"input",style:{flex:1},placeholder:`Option ${String.fromCharCode(65+te)}`,value:L,onChange:Te=>Y(te,Te.target.value),required:!0}),c.jsx("button",{type:"button",style:j.removeBtn,onClick:()=>X(te),disabled:p.length<=2,children:"βœ•"})]},te))}),p.length<6&&c.jsx("button",{type:"button",className:"btn btn-ghost",style:{marginTop:"0.5rem",fontSize:"0.85rem"},onClick:D,children:"+ Add option"})]}),c.jsxs("div",{style:j.policySection,children:[c.jsx("label",{className:"label",children:"Show results to students"}),c.jsx("div",{style:j.policyRow,children:fb.map(L=>c.jsx("button",{type:"button",style:{...j.policyBtn,...A===L.value?j.policyBtnActive:{}},onClick:()=>q(L.value),children:c.jsx("span",{style:j.policyLabel,children:L.label})},L.value))})]}),S!=null&&c.jsxs("div",{style:j.policySection,children:[c.jsx("label",{className:"label",children:"Reveal correct answer to students"}),c.jsx("div",{style:j.policyRow,children:pb.map(L=>c.jsx("button",{type:"button",style:{...j.policyBtn,...z===L.value?j.policyBtnActive:{}},onClick:()=>pe(L.value),children:c.jsx("span",{style:j.policyLabel,children:L.label})},L.value))})]}),c.jsxs("div",{style:{display:"flex",gap:"1rem",alignItems:"flex-end"},children:[c.jsxs("div",{style:{flex:1},children:[c.jsx("label",{className:"label",children:"Duration (seconds)"}),c.jsx("input",{className:"input",type:"number",min:10,max:300,value:P,onChange:L=>b(Number(L.target.value))})]}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{padding:"0.65rem 2rem"},children:"Start Poll β†’"})]})]})]}),l==="dashboard"&&c.jsxs("div",{style:j.content,className:"fade-up",children:[y&&c.jsxs("div",{style:j.queueBanner,children:[c.jsx("span",{style:j.queueIcon,children:"πŸ“š"}),c.jsxs("div",{style:{flex:1},children:[c.jsx("div",{style:j.queueName,children:u.setName}),c.jsxs("div",{style:j.queueProgress,children:["Poll ",u.currentIndex+1," of ",u.totalPolls]})]}),c.jsx("div",{style:j.queueDots,children:Array.from({length:u.totalPolls},(L,te)=>c.jsx("div",{style:{...j.queueDot,background:tea("create"),children:"Create one β†’"})," ","or"," ",c.jsx("button",{style:j.link,onClick:()=>t("/pollsets"),children:"launch a set β†’"})]})]}),T&&c.jsxs("div",{style:j.pollCard,children:[c.jsxs("div",{style:j.timerRow,children:[r&&!U?c.jsx(gb,{timeLeft:s,total:r.duration}):c.jsx("div",{style:j.expiredBadge,children:"⏰"}),c.jsxs("div",{style:{flex:1},children:[c.jsx("div",{style:j.pollQuestion,children:T.question}),c.jsxs("div",{style:j.responseMeta,children:[R," / ",e.length," responded",(U||O)&&c.jsx("span",{style:j.expiredTag,children:O?" Β· Poll ended":" Β· Stopped accepting answers"})]})]})]}),c.jsx("div",{style:{marginTop:"1.25rem",display:"flex",flexDirection:"column",gap:"0.6rem"},children:T.options.map((L,te)=>{const Te=Object.values(T.responses||{}).filter(z_=>z_===te).length,xe=Object.keys(T.responses||{}).length,Ir=xe>0?Math.round(Te/xe*100):0,da=T.correctIndex===te;return c.jsxs("div",{style:j.optionRow,children:[c.jsxs("div",{style:{...j.optionLabel,...da?j.correctLabel:{}},children:[String.fromCharCode(65+te),da?"βœ“":""]}),c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"0.25rem"},children:[c.jsx("span",{style:{fontSize:"0.9rem"},children:L}),c.jsxs("span",{style:{fontSize:"0.85rem",color:"var(--muted)"},children:[Te," (",Ir,"%)"]})]}),c.jsx("div",{style:j.barBg,children:c.jsx("div",{style:{...j.barFill,width:`${Ir}%`,background:da?"var(--success)":"var(--accent2)"}})})]})]},te)})}),R>0&&c.jsxs("div",{style:{marginTop:"1rem"},children:[c.jsx("label",{className:"label",children:"Responded"}),c.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.4rem"},children:Object.keys(T.responses).map(L=>c.jsx("span",{style:j.answeredChip,children:L},L))})]}),c.jsxs("div",{style:j.controls,children:[c.jsx("label",{className:"label",style:{marginBottom:"0.75rem"},children:"Student display"}),c.jsxs("div",{style:j.controlGrid,children:[r&&r.resultPolicy==="manual"&&c.jsxs("div",{style:j.controlItem,children:[c.jsx("span",{style:j.controlLabel,children:"Results visible"}),c.jsx(zp,{active:!!r.revealResults,onChange:L=>yc(L,r.revealCorrect)})]}),r&&r.correctPolicy==="manual"&&r.correctIndex!=null&&c.jsxs("div",{style:j.controlItem,children:[c.jsx("span",{style:j.controlLabel,children:"Correct answer visible"}),c.jsx(zp,{active:!!r.revealCorrect,onChange:L=>yc(r.revealResults,L)})]}),c.jsxs("div",{style:j.statusSummary,children:[c.jsx(Bp,{label:"Results",state:T.resultPolicy==="never"?"never":T.resultPolicy==="on_submit"?"auto":T.revealResults?"shown":"hidden"}),T.correctIndex!=null&&c.jsx(Bp,{label:"Answer",state:T.correctPolicy==="never"?"never":tt(T)?"shown":"hidden"})]}),c.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"0.5rem",alignItems:"center"},children:[r&&c.jsx("button",{className:"btn btn-secondary",onClick:()=>y?F_(r.revealResults,r.revealCorrect):Do(r.revealResults,r.revealCorrect),children:y?"End Poll":"Close Poll"}),y&&c.jsx("button",{className:"btn btn-primary",onClick:Ee,children:x?"Finish Set βœ“":`Next Poll β†’ (${u.currentIndex+2} of ${u.totalPolls})`})]})]})]})]})]})]})]})}function zp({active:t,onChange:e}){return c.jsx("button",{onClick:()=>e(!t),style:{position:"relative",width:48,height:26,borderRadius:13,border:"none",background:t?"var(--success)":"var(--border)",cursor:"pointer",transition:"background 0.2s",flexShrink:0},children:c.jsx("span",{style:{position:"absolute",top:3,left:t?22:3,width:20,height:20,borderRadius:"50%",background:"white",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})})}function Bp({label:t,state:e}){const n={shown:{bg:"#dcfce7",color:"#15803d"},hidden:{bg:"#fee2e2",color:"#b91c1c"},auto:{bg:"#dbeafe",color:"#1d4ed8"},never:{bg:"var(--cream)",color:"var(--muted)"}},r={shown:"Shown",hidden:"Hidden",auto:"Auto",never:"Never"},i=n[e]||n.never;return c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem"},children:[c.jsxs("span",{style:{fontSize:"0.78rem",color:"var(--muted)"},children:[t,":"]}),c.jsx("span",{style:{background:i.bg,color:i.color,borderRadius:4,padding:"0.15rem 0.5rem",fontSize:"0.75rem",fontWeight:600},children:r[e]})]})}function gb({timeLeft:t,total:e}){const r=2*Math.PI*28,i=e>0?t/e:0,s=r*(1-i),o=i>.4?"var(--accent2)":i>.15?"#f59e0b":"var(--accent)";return c.jsxs("div",{style:{position:"relative",width:72,height:72,flexShrink:0},children:[c.jsxs("svg",{width:"72",height:"72",style:{transform:"rotate(-90deg)"},children:[c.jsx("circle",{cx:"36",cy:"36",r:28,fill:"none",stroke:"var(--cream)",strokeWidth:"5"}),c.jsx("circle",{cx:"36",cy:"36",r:28,fill:"none",stroke:o,strokeWidth:"5",strokeDasharray:r,strokeDashoffset:s,strokeLinecap:"round",style:{transition:"stroke-dashoffset 0.5s linear, stroke 0.5s"}})]}),c.jsx("span",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.1rem"},children:t})]})}const j={page:{display:"flex",minHeight:"100vh",background:"var(--paper)"},sidebar:{width:220,minHeight:"100vh",background:"var(--ink)",color:"white",display:"flex",flexDirection:"column",padding:"1.5rem 1rem",gap:"0.5rem",position:"sticky",top:0,flexShrink:0},logo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",padding:"0 0.5rem",marginBottom:"1rem"},nav:{display:"flex",flexDirection:"column",gap:"0.25rem"},navBtn:{background:"transparent",color:"rgba(255,255,255,0.7)",border:"none",borderRadius:8,padding:"0.6rem 0.75rem",textAlign:"left",cursor:"pointer",fontSize:"0.9rem",transition:"all 0.15s"},navActive:{background:"rgba(255,255,255,0.12)",color:"white"},navDisabled:{opacity:.4,cursor:"not-allowed"},sidebarBottom:{marginTop:"auto",display:"flex",flexDirection:"column",gap:"0.75rem"},studentCount:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem",color:"rgba(255,255,255,0.6)"},dot:{width:8,height:8,borderRadius:"50%",background:"#4ade80",flexShrink:0,boxShadow:"0 0 6px #4ade80"},studentList:{display:"flex",flexWrap:"wrap",gap:"0.35rem",maxHeight:120,overflowY:"auto"},studentChip:{background:"rgba(255,255,255,0.1)",borderRadius:4,padding:"0.2rem 0.5rem",fontSize:"0.78rem",color:"rgba(255,255,255,0.8)"},main:{flex:1,padding:"2rem",overflowY:"auto"},content:{maxWidth:"100%",margin:"0 auto"},pageTitle:{fontSize:"1.6rem",marginBottom:"1.5rem"},form:{display:"flex",flexDirection:"column",gap:"1.25rem",background:"white",padding:"1.5rem",borderRadius:12,border:"1px solid var(--border)"},hint:{fontSize:"0.82rem",color:"var(--muted)",marginBottom:"0.5rem"},policySection:{display:"flex",flexDirection:"column",gap:"0.5rem"},policyRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},policyBtn:{display:"flex",flexDirection:"column",gap:"0.2rem",padding:"0.6rem 0.85rem",borderRadius:8,border:"1.5px solid var(--border)",background:"var(--paper)",cursor:"pointer",textAlign:"left",transition:"all 0.15s",flex:1,minWidth:120},policyBtnActive:{borderColor:"var(--accent2)",background:"#eff6ff"},policyLabel:{fontSize:"0.88rem",fontWeight:600,color:"var(--ink)"},empty:{textAlign:"center",padding:"4rem 2rem",color:"var(--muted)",display:"flex",flexDirection:"column",alignItems:"center",gap:"0.75rem"},link:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"inherit",textDecoration:"underline"},queueBanner:{display:"flex",alignItems:"center",gap:"0.75rem",background:"#eff6ff",border:"1.5px solid var(--accent2)",borderRadius:12,padding:"0.75rem 1rem",marginBottom:"1.25rem"},queueIcon:{fontSize:"1.4rem"},queueName:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"0.95rem"},queueProgress:{color:"var(--accent2)",fontSize:"0.82rem",marginTop:"0.1rem"},queueDots:{display:"flex",gap:"0.35rem",alignItems:"center"},queueDot:{width:10,height:10,borderRadius:"50%",transition:"background 0.3s"},queueExit:{background:"none",border:"1px solid var(--border)",borderRadius:6,padding:"0.3rem 0.6rem",fontSize:"0.78rem",cursor:"pointer",color:"var(--muted)"},pollCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1.5rem"},timerRow:{display:"flex",alignItems:"center",gap:"1rem"},pollQuestion:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.1rem"},responseMeta:{color:"var(--muted)",fontSize:"0.85rem",marginTop:"0.2rem"},expiredBadge:{width:72,height:72,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.8rem",flexShrink:0},expiredTag:{color:"var(--accent)",fontWeight:500},optionRow:{display:"flex",alignItems:"center",gap:"0.75rem"},optionLabel:{width:28,height:28,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.8rem",fontWeight:700,flexShrink:0},correctLabel:{background:"#dcfce7",color:"var(--success)"},barBg:{height:8,borderRadius:4,background:"var(--cream)",overflow:"hidden"},barFill:{height:"100%",borderRadius:4,transition:"width 0.4s ease"},answeredChip:{background:"#dbeafe",color:"var(--accent2)",borderRadius:4,padding:"0.15rem 0.5rem",fontSize:"0.78rem"},correctBtn:{width:32,height:32,borderRadius:"50%",border:"2px solid var(--border)",background:"var(--cream)",cursor:"pointer",fontWeight:700,fontSize:"0.8rem",flexShrink:0,transition:"all 0.15s"},correctBtnActive:{background:"var(--success)",color:"white",borderColor:"var(--success)"},removeBtn:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",fontSize:"0.9rem",padding:"0.25rem",borderRadius:4},controls:{marginTop:"1.25rem",paddingTop:"1.25rem",borderTop:"1px solid var(--border)"},controlGrid:{display:"flex",gap:"1rem",alignItems:"center",flexWrap:"wrap"},controlItem:{display:"flex",alignItems:"center",gap:"0.6rem"},controlLabel:{fontSize:"0.85rem",color:"var(--muted)"},statusSummary:{display:"flex",gap:"0.75rem",flexWrap:"wrap"}};function vb(){var D;const t=Sr(),[e,n]=C.useState(""),[r,i]=C.useState(!1),[s,o]=C.useState(null),[l,a]=C.useState(null),[u,h]=C.useState(!1),[d,f]=C.useState(0),[v,w]=C.useState(null),_=C.useRef(null),E=C.useRef(null);C.useEffect(()=>dh(X=>{!X&&s&&(w(s),setTimeout(()=>w(null),1e4)),X&&X.id!==E.current&&(a(null),h(!1),E.current=X.id),o(X),X&&!X.ended&&f(Math.max(0,Math.round(X.duration-(Date.now()-X.startedAt)/1e3)))}),[s]),C.useEffect(()=>(clearInterval(_.current),s&&!s.ended&&(_.current=setInterval(()=>{const Y=Math.max(0,Math.round(s.duration-(Date.now()-s.startedAt)/1e3));f(Y),Y===0&&clearInterval(_.current)},500)),()=>clearInterval(_.current)),[s==null?void 0:s.id,s==null?void 0:s.ended]),C.useEffect(()=>{if(!r||!e)return;const Y=()=>vc(e);return window.addEventListener("beforeunload",Y),()=>{Y(),window.removeEventListener("beforeunload",Y)}},[r,e]);function g(Y){Y.preventDefault();const X=e.trim();X&&T_(X).then(()=>i(!0))}function p(Y){u||d===0||s!=null&&s.ended||a(Y)}function m(){l===null||u||!s||(b_(e,s.id,l),h(!0))}const S=s&&((D=s.responses)==null?void 0:D[e])!==void 0,I=S?s.responses[e]:l,P=s?Object.keys(s.responses||{}).length:0,b=(s==null?void 0:s.ended)||d===0;function A(){return s?s.revealResults?!0:s.resultPolicy==="never"||s.resultPolicy==="manual"?!1:s.resultPolicy==="on_submit"?u||S:!1:!1}function q(){return!s||s.correctIndex==null?!1:s.revealCorrect?!0:s.correctPolicy==="never"||s.correctPolicy==="manual"?!1:s.correctPolicy==="with_results"?A():!1}const z=A(),pe=q();return r?!s&&!v?c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.waitCard,className:"fade-up",children:[c.jsx("div",{style:se.pulse}),c.jsxs("h2",{style:{fontFamily:"var(--font-display)",fontSize:"1.5rem"},children:["Hi, ",e,"! πŸ‘‹"]}),c.jsx("p",{style:{color:"var(--muted)"},children:"Waiting for the teacher to start a poll…"}),c.jsx("button",{style:se.backLink,onClick:()=>{vc(e),t("/")},children:"Leave session"})]})}):!s&&v?c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.waitCard,className:"fade-up",children:[c.jsx("span",{style:{fontSize:"2.5rem"},children:"βœ…"}),c.jsx("h2",{style:{fontFamily:"var(--font-display)"},children:"Poll closed!"}),c.jsx("p",{style:{color:"var(--muted)",textAlign:"center"},children:c.jsx("em",{children:v.question})}),v.correctIndex!=null&&v.revealCorrect&&c.jsxs("p",{style:{color:"var(--success)",fontWeight:600},children:["Correct answer: ",v.options[v.correctIndex]]}),c.jsx("p",{style:{color:"var(--muted)",fontSize:"0.85rem"},children:"Waiting for next poll…"})]})}):c.jsxs("div",{style:se.pollPage,children:[c.jsxs("header",{style:se.pollHeader,children:[c.jsxs("span",{style:{fontFamily:"var(--font-display)",fontWeight:700},children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsxs("span",{style:{color:"var(--muted)",fontSize:"0.9rem"},children:["Signed in as ",c.jsx("strong",{children:e})]})]}),c.jsxs("div",{style:se.pollContent,className:"fade-up",children:[!s.ended&&c.jsxs(c.Fragment,{children:[c.jsx("div",{style:se.timerBar,children:c.jsx("div",{style:{...se.timerFill,width:`${d/s.duration*100}%`,background:d>s.duration*.4?"var(--accent2)":d>s.duration*.15?"#f59e0b":"var(--accent)"}})}),c.jsxs("div",{style:se.timerLabel,children:[d,"s remaining Β· ",P," responded"]})]}),s.ended&&c.jsx("div",{style:se.stoppedBanner,children:"⏰ Time's up β€” waiting for teacher"}),c.jsx("h2",{style:se.questionText,children:s.question}),c.jsx("div",{style:se.optionGrid,children:s.options.map((Y,X)=>{const et=I===X,Ee=s.correctIndex===X,Be=Object.values(s.responses||{}).filter(U=>U===X).length,R=P>0?Math.round(Be/P*100):0;return c.jsxs("button",{style:{...se.optionBtn,...et?se.optionSelected:{},...pe&&Ee?se.optionCorrect:{},...b||S?{cursor:"default"}:{}},onClick:()=>p(X),disabled:b||S,children:[c.jsx("span",{style:se.optionLetter,children:String.fromCharCode(65+X)}),c.jsx("span",{style:{flex:1,textAlign:"left"},children:Y}),z&&c.jsxs("span",{style:se.optionPct,children:[R,"%"]}),z&&c.jsx("div",{style:{...se.optionBar,width:`${R}%`,background:pe&&Ee?"rgba(22,163,74,0.15)":"rgba(37,99,235,0.1)"}})]},X)})}),!S&&!u&&!b&&c.jsx("button",{className:"btn btn-primary",style:{width:"100%",justifyContent:"center",padding:"0.85rem",fontSize:"1rem",marginTop:"0.5rem"},onClick:m,disabled:l===null,children:"Submit Answer"}),(u||S)&&!b&&c.jsx("div",{style:se.submittedBadge,children:"βœ“ Answer submitted"}),b&&!S&&!u&&c.jsx("div",{style:{...se.submittedBadge,background:"#fef9c3",color:"#854d0e",borderColor:"#fef08a"},children:"⏰ Time's up β€” no answer recorded"}),b&&(S||u)&&c.jsx("div",{style:se.submittedBadge,children:"βœ“ Answer submitted β€” waiting for teacher"})]})]}):c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.joinCard,className:"fade-up",children:[c.jsxs("div",{style:se.joinLogo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsx("h1",{style:{fontSize:"1.8rem",marginBottom:"0.25rem"},children:"Join Session"}),c.jsx("p",{style:{color:"var(--muted)",marginBottom:"1.5rem"},children:"Enter your name to start answering polls"}),c.jsxs("form",{onSubmit:g,style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[c.jsx("input",{className:"input",placeholder:"Your first name",value:e,onChange:Y=>n(Y.target.value),autoFocus:!0,style:{fontSize:"1.1rem",textAlign:"center"},required:!0}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{justifyContent:"center",padding:"0.75rem"},children:"Join β†’"})]}),c.jsx("button",{style:se.backLink,onClick:()=>t("/"),children:"← Back"})]})})}const se={center:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"var(--paper)"},joinCard:{background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"2.5rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},joinLogo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",marginBottom:"1.5rem",display:"block"},backLink:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",marginTop:"1rem",fontSize:"0.85rem",display:"block",textAlign:"center"},waitCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:"0.75rem",background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"3rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},pulse:{width:16,height:16,borderRadius:"50%",background:"var(--accent2)",boxShadow:"0 0 0 0 rgba(37,99,235,0.4)",animation:"pulse-ring 1.5s ease-out infinite"},pollPage:{minHeight:"100vh",background:"var(--paper)",display:"flex",flexDirection:"column"},pollHeader:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",display:"flex",justifyContent:"space-between",alignItems:"center",background:"white"},pollContent:{maxWidth:620,margin:"0 auto",padding:"2rem 1rem",width:"100%"},timerBar:{height:6,background:"var(--cream)",borderRadius:3,overflow:"hidden",marginBottom:"0.4rem"},timerFill:{height:"100%",borderRadius:3,transition:"width 0.5s linear, background 0.5s"},timerLabel:{color:"var(--muted)",fontSize:"0.82rem",marginBottom:"1.5rem"},stoppedBanner:{background:"#fef9c3",color:"#854d0e",border:"1px solid #fef08a",borderRadius:8,padding:"0.6rem 1rem",fontSize:"0.9rem",marginBottom:"1.5rem",textAlign:"center"},questionText:{fontFamily:"var(--font-display)",fontSize:"clamp(1.2rem, 3vw, 1.6rem)",lineHeight:1.25,marginBottom:"1.25rem"},optionGrid:{display:"flex",flexDirection:"column",gap:"0.6rem"},optionBtn:{position:"relative",overflow:"hidden",display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.9rem 1rem",borderRadius:10,border:"2px solid var(--border)",background:"white",cursor:"pointer",transition:"all 0.15s",textAlign:"left",fontFamily:"var(--font-body)",fontSize:"0.95rem"},optionSelected:{borderColor:"var(--accent2)",background:"#eff6ff"},optionCorrect:{borderColor:"var(--success)",background:"#f0fdf4"},optionLetter:{width:28,height:28,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.8rem",fontWeight:700,flexShrink:0},optionPct:{color:"var(--muted)",fontSize:"0.82rem",fontWeight:600,flexShrink:0,zIndex:1},optionBar:{position:"absolute",left:0,top:0,height:"100%",transition:"width 0.4s ease",zIndex:0,pointerEvents:"none"},submittedBadge:{marginTop:"1rem",padding:"0.75rem",borderRadius:8,background:"#f0fdf4",color:"var(--success)",textAlign:"center",fontWeight:500,fontSize:"0.9rem",border:"1px solid #bbf7d0"}};function U_(t,e={}){const{duration:n=60,resultPolicy:r="on_submit",correctPolicy:i="with_results"}=e,s=t.split(/^---$/m).map(l=>l.trim()).filter(Boolean),o=[];for(const l of s){const a=l.split(` + */const sb=5*60,ob=kv("authIdTokenMaxAge")||sb;let Fp=null;const lb=t=>async e=>{const n=e&&await e.getIdTokenResult(),r=n&&(new Date().getTime()-Date.parse(n.issuedAtTime))/1e3;if(r&&r>ob)return;const i=n==null?void 0:n.token;Fp!==i&&(Fp=i,await fetch(t,{method:i?"POST":"DELETE",headers:i?{Authorization:`Bearer ${i}`}:{}}))};function ab(t=Av()){const e=Ed(t,"auth");if(e.isInitialized())return e.getImmediate();const n=UT(t,{popupRedirectResolver:tb,persistence:[h1,e1,__]}),r=kv("authTokenSyncURL");if(r&&typeof isSecureContext=="boolean"&&isSecureContext){const s=new URL(r,location.origin);if(location.origin===s.origin){const o=lb(s.toString());JT(n,o,()=>o(n.currentUser)),YT(n,l=>o(l))}}const i=xv("auth");return i&&BT(n,`http://${i}`),n}function ub(){var t,e;return(e=(t=document.getElementsByTagName("head"))===null||t===void 0?void 0:t[0])!==null&&e!==void 0?e:document}LT({loadJS(t){return new Promise((e,n)=>{const r=document.createElement("script");r.setAttribute("src",t),r.onload=e,r.onerror=i=>{const s=Ut("internal-error");s.customData=i,n(s)},r.type="text/javascript",r.charset="UTF-8",ub().appendChild(r)})},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="});ib("Browser");const cb={apiKey:"AIzaSyBiZSV4Z_3-L0z8RP5yY_2xXlw5fKOy2jc",authDomain:"classroom-polling-dd344.firebaseapp.com",databaseURL:"https://classroom-polling-dd344-default-rtdb.firebaseio.com",projectId:"classroom-polling-dd344",storageBucket:"classroom-polling-dd344.firebasestorage.app",messagingSenderId:"528103899828",appId:"1:528103899828:web:f74274640de611a61d0de1"},k_=Rv(cb),re=aT(k_),db=ab(k_);GT(db).catch(console.error);function T_(t){const e=new Date().toLocaleDateString("en-CA");return on(ne(re,`session/students/${t}`),{joinedAt:Sp(),date:e}),on(ne(re,`sessionStudents/${e}_${t}`),{name:t,date:e,joinedAt:Sp()})}function vc(t){return vr(ne(re,`session/students/${t}`))}function b_(t,e,n){return sa(ne(re,"session/activePoll/responses"),{[t]:n})}function Pl({question:t,options:e,correctIndex:n,duration:r,resultPolicy:i,correctPolicy:s}){const o=`poll_${Date.now()}`;return on(ne(re,"session/activePoll"),{id:o,question:t,options:e,correctIndex:n??null,duration:r,resultPolicy:i,correctPolicy:s,startedAt:Date.now(),responses:{},ended:!1,revealResults:!1,revealCorrect:!1})}async function Do(t,e){const[n,r]=await Promise.all([Ns(ne(re,"session/activePoll")),Ns(ne(re,"session/queue"))]),i=n.val(),s=r.val();if(!i)return;const o={...i,revealResults:t,revealCorrect:e,endedAt:Date.now()};return s&&(o.setId=s.setId,o.setName=s.setName,o.setPosition=s.currentIndex,o.sessionKey=s.sessionKey),await on(ne(re,`pollHistory/${i.id}`),o),vr(ne(re,"session/activePoll"))}function P_(){return sa(ne(re,"session/activePoll"),{ended:!0})}function yc(t,e){return sa(ne(re,"session/activePoll"),{revealResults:t,revealCorrect:e})}function dh(t){const e=ne(re,"session/activePoll");return xr(e,n=>t(n.val()))}function N_(t){const e=ne(re,"session/students");return xr(e,n=>{const r=n.val()||{};t(Object.keys(r).map(i=>({name:i,...r[i]})))})}function R_(t){const e=ne(re,"pollHistory");return xr(e,n=>{const r=n.val()||{},i=Object.values(r).sort((s,o)=>(o.startedAt||0)-(s.startedAt||0));t(i)})}function A_(t){const e=ne(re,"pollSets");return xr(e,n=>{const r=n.val()||{},i=Object.entries(r).map(([s,o])=>({id:s,...o})).sort((s,o)=>(o.createdAt||0)-(s.createdAt||0));t(i)})}async function _c({name:t,defaults:e,polls:n}){const r=`set_${Date.now()}`;return await on(ne(re,`pollSets/${r}`),{id:r,name:t,createdAt:Date.now(),defaults:e,polls:n||[]}),r}function Lo(t,e){return Ns(ne(re,`pollSets/${t}`)).then(n=>{const r=n.val()||{};return on(ne(re,`pollSets/${t}`),{...r,...e})})}function O_(t){return vr(ne(re,`pollSets/${t}`))}function D_(t,e){const n=ne(re,`pollSets/${t}`);return xr(n,r=>e(r.val()))}function L_(t,e,n){const r=`run_${Date.now()}`;return on(ne(re,"session/queue"),{setId:t,setName:e,currentIndex:0,totalPolls:n,sessionKey:r})}function M_(t){return sa(ne(re,"session/queue"),{currentIndex:t})}function wc(){return vr(ne(re,"session/queue"))}function j_(t){const e=ne(re,"session/queue");return xr(e,n=>t(n.val()))}async function F_(t,e){const r=(await Ns(ne(re,"session/activePoll"))).val(),s=(await Ns(ne(re,"session/queue"))).val();if(!r)return;const o={...r,revealResults:t,revealCorrect:e,endedAt:Date.now()};return s&&(o.setId=s.setId,o.setName=s.setName,o.setPosition=s.currentIndex,o.sessionKey=s.sessionKey),await on(ne(re,`pollHistory/${r.id}`),o),vr(ne(re,"session/activePoll"))}const hb=Object.freeze(Object.defineProperty({__proto__:null,advanceQueue:M_,clearQueue:wc,closePoll:F_,createPollSet:_c,deletePollSet:O_,endPoll:Do,expirePoll:P_,joinSession:T_,launchSet:L_,leaveSession:vc,revealPollResults:yc,startPoll:Pl,submitAnswer:b_,updatePollSet:Lo,watchActivePoll:dh,watchPollHistory:R_,watchPollSet:D_,watchPollSets:A_,watchQueue:j_,watchStudents:N_},Symbol.toStringTag,{value:"Module"})),Up=60,fb=[{value:"on_submit",label:"After they submit"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}],pb=[{value:"with_results",label:"With results"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}];function mb(){var Ge;const t=Sr(),[e,n]=C.useState([]),[r,i]=C.useState(null),[s,o]=C.useState(0),[l,a]=C.useState("dashboard"),[u,h]=C.useState(null),[d,f]=C.useState(null),v=C.useRef(null),w=C.useRef(null),_=C.useRef(null),[E,g]=C.useState(""),[p,m]=C.useState(["",""]),[S,I]=C.useState(null),[P,b]=C.useState(Up),[A,q]=C.useState("on_submit"),[z,pe]=C.useState("with_results");C.useEffect(()=>{localStorage.getItem("role")!=="instructor"&&t("/")},[]),C.useEffect(()=>{const L=dh(xe=>{xe&&(_.current=xe),i(xe),xe&&!xe.ended&&o(Math.max(0,Math.round(xe.duration-(Date.now()-xe.startedAt)/1e3)))}),te=N_(n),Te=j_(xe=>{h(xe),xe!=null&&xe.setId?(w.current&&w.current(),gC(async()=>{const{watchPollSet:Ir}=await Promise.resolve().then(()=>hb);return{watchPollSet:Ir}},void 0).then(({watchPollSet:Ir})=>{w.current=Ir(xe.setId,f)})):(f(null),_.current=null,w.current&&(w.current(),w.current=null))});return()=>{L(),te(),Te()}},[]),C.useEffect(()=>(clearInterval(v.current),r&&!r.ended&&(v.current=setInterval(()=>{const L=Math.max(0,Math.round(r.duration-(Date.now()-r.startedAt)/1e3));o(L),L===0&&(clearInterval(v.current),P_())},500)),()=>clearInterval(v.current)),[r==null?void 0:r.id,r==null?void 0:r.ended]);function D(){p.length<6&&m([...p,""])}function Y(L,te){m(p.map((Te,xe)=>xe===L?te:Te))}function X(L){if(p.length<=2)return;const te=p.filter((Te,xe)=>xe!==L);m(te),S===L?I(null):S>L&&I(S-1)}function et(L){L.preventDefault();const te=p.filter(Te=>Te.trim());!E.trim()||te.length<2||(Pl({question:E.trim(),options:te,correctIndex:S,duration:P,resultPolicy:A,correctPolicy:z}),g(""),m(["",""]),I(null),b(Up),q("on_submit"),pe("with_results"),a("dashboard"))}async function Ee(){if(!u||!d)return;const L=u.currentIndex+1;if(r&&await Do(r.revealResults||!1,r.revealCorrect||!1),L>=u.totalPolls){await wc();return}await M_(L);const te=d.defaults||{},Te=(d.polls||[])[L];Te&&await Pl({question:Te.question,options:Te.options,correctIndex:Te.correctIndex??null,duration:Te.duration??te.duration??60,resultPolicy:Te.resultPolicy??te.resultPolicy??"on_submit",correctPolicy:Te.correctPolicy??te.correctPolicy??"with_results"})}async function Be(){r&&await Do(r.revealResults||!1,r.revealCorrect||!1),await wc()}const R=r?Object.keys(r.responses||{}).length:Object.keys(((Ge=_.current)==null?void 0:Ge.responses)||{}).length,U=r==null?void 0:r.ended,y=!!u,x=u&&u.currentIndex>=u.totalPolls-1,T=r||(y?_.current:null),O=!r&&T;function K(L){return L.revealResults?!0:!(L.resultPolicy==="never"||L.resultPolicy==="manual")}function tt(L){return L.revealCorrect?!0:L.correctPolicy==="never"||L.correctPolicy==="manual"?!1:!!(L.correctPolicy==="with_results"&&K(L))}return c.jsxs("div",{style:j.page,children:[c.jsxs("aside",{style:j.sidebar,children:[c.jsxs("div",{style:j.logo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsxs("nav",{style:j.nav,children:[c.jsx("button",{style:{...j.navBtn,...l==="dashboard"?j.navActive:{}},onClick:()=>a("dashboard"),children:"πŸ“Š Dashboard"}),c.jsx("button",{style:{...j.navBtn,...l==="create"?j.navActive:{},...r?j.navDisabled:{}},onClick:()=>!r&&a("create"),disabled:!!r,children:"βž• New Poll"}),c.jsx("button",{style:j.navBtn,onClick:()=>t("/pollsets"),children:"πŸ“š Poll Sets"}),c.jsx("button",{style:j.navBtn,onClick:()=>t("/history"),children:"πŸ• History"})]}),c.jsxs("div",{style:j.sidebarBottom,children:[c.jsxs("div",{style:j.studentCount,children:[c.jsx("span",{style:j.dot}),c.jsx("strong",{children:e.length})," student",e.length!==1?"s":""," online"]}),c.jsx("div",{style:j.studentList,children:e.map(L=>c.jsx("div",{style:j.studentChip,children:L.name},L.name))}),c.jsx("button",{className:"btn btn-secondary",style:{width:"100%",marginTop:"auto",fontSize:"0.8rem"},onClick:()=>{localStorage.removeItem("role"),localStorage.removeItem("historyAuth"),t("/")},children:"Exit"})]})]}),c.jsxs("main",{style:j.main,children:[l==="create"&&c.jsxs("div",{style:j.content,className:"fade-up",children:[c.jsx("h2",{style:j.pageTitle,children:"Create a Poll"}),c.jsxs("form",{onSubmit:et,style:j.form,children:[c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Question"}),c.jsx("textarea",{className:"input",rows:2,placeholder:"e.g. Which process converts sunlight into energy?",value:E,onChange:L=>g(L.target.value),style:{resize:"vertical",width:"100%"},required:!0})]}),c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Answer Options"}),c.jsx("p",{style:j.hint,children:"Click a letter circle to mark the correct answer (optional)"}),c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:p.map((L,te)=>c.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[c.jsx("button",{type:"button",style:{...j.correctBtn,...S===te?j.correctBtnActive:{}},onClick:()=>I(S===te?null:te),children:S===te?"βœ“":String.fromCharCode(65+te)}),c.jsx("input",{className:"input",style:{flex:1},placeholder:`Option ${String.fromCharCode(65+te)}`,value:L,onChange:Te=>Y(te,Te.target.value),required:!0}),c.jsx("button",{type:"button",style:j.removeBtn,onClick:()=>X(te),disabled:p.length<=2,children:"βœ•"})]},te))}),p.length<6&&c.jsx("button",{type:"button",className:"btn btn-ghost",style:{marginTop:"0.5rem",fontSize:"0.85rem"},onClick:D,children:"+ Add option"})]}),c.jsxs("div",{style:j.policySection,children:[c.jsx("label",{className:"label",children:"Show results to students"}),c.jsx("div",{style:j.policyRow,children:fb.map(L=>c.jsx("button",{type:"button",style:{...j.policyBtn,...A===L.value?j.policyBtnActive:{}},onClick:()=>q(L.value),children:c.jsx("span",{style:j.policyLabel,children:L.label})},L.value))})]}),S!=null&&c.jsxs("div",{style:j.policySection,children:[c.jsx("label",{className:"label",children:"Reveal correct answer to students"}),c.jsx("div",{style:j.policyRow,children:pb.map(L=>c.jsx("button",{type:"button",style:{...j.policyBtn,...z===L.value?j.policyBtnActive:{}},onClick:()=>pe(L.value),children:c.jsx("span",{style:j.policyLabel,children:L.label})},L.value))})]}),c.jsxs("div",{style:{display:"flex",gap:"1rem",alignItems:"flex-end"},children:[c.jsxs("div",{style:{flex:1},children:[c.jsx("label",{className:"label",children:"Duration (seconds)"}),c.jsx("input",{className:"input",type:"number",min:10,max:300,value:P,onChange:L=>b(Number(L.target.value))})]}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{padding:"0.65rem 2rem"},children:"Start Poll β†’"})]})]})]}),l==="dashboard"&&c.jsxs("div",{style:j.content,className:"fade-up",children:[y&&c.jsxs("div",{style:j.queueBanner,children:[c.jsx("span",{style:j.queueIcon,children:"πŸ“š"}),c.jsxs("div",{style:{flex:1},children:[c.jsx("div",{style:j.queueName,children:u.setName}),c.jsxs("div",{style:j.queueProgress,children:["Poll ",u.currentIndex+1," of ",u.totalPolls]})]}),c.jsx("div",{style:j.queueDots,children:Array.from({length:u.totalPolls},(L,te)=>c.jsx("div",{style:{...j.queueDot,background:tea("create"),children:"Create one β†’"})," ","or"," ",c.jsx("button",{style:j.link,onClick:()=>t("/pollsets"),children:"launch a set β†’"})]})]}),T&&c.jsxs("div",{style:j.pollCard,children:[c.jsxs("div",{style:j.timerRow,children:[r&&!U?c.jsx(gb,{timeLeft:s,total:r.duration}):c.jsx("div",{style:j.expiredBadge,children:"⏰"}),c.jsxs("div",{style:{flex:1},children:[c.jsx("div",{style:j.pollQuestion,children:T.question}),c.jsxs("div",{style:j.responseMeta,children:[R," / ",e.length," responded",(U||O)&&c.jsx("span",{style:j.expiredTag,children:O?" Β· Poll ended":" Β· Stopped accepting answers"})]})]})]}),c.jsx("div",{style:{marginTop:"1.25rem",display:"flex",flexDirection:"column",gap:"0.6rem"},children:T.options.map((L,te)=>{const Te=Object.values(T.responses||{}).filter(z_=>z_===te).length,xe=Object.keys(T.responses||{}).length,Ir=xe>0?Math.round(Te/xe*100):0,da=T.correctIndex===te;return c.jsxs("div",{style:j.optionRow,children:[c.jsxs("div",{style:{...j.optionLabel,...da?j.correctLabel:{}},children:[String.fromCharCode(65+te),da?"βœ“":""]}),c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"0.25rem"},children:[c.jsx("span",{style:{fontSize:"0.9rem"},children:L}),c.jsxs("span",{style:{fontSize:"0.85rem",color:"var(--muted)"},children:[Te," (",Ir,"%)"]})]}),c.jsx("div",{style:j.barBg,children:c.jsx("div",{style:{...j.barFill,width:`${Ir}%`,background:da?"var(--success)":"var(--accent2)"}})})]})]},te)})}),R>0&&c.jsxs("div",{style:{marginTop:"1rem"},children:[c.jsx("label",{className:"label",children:"Responded"}),c.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.4rem"},children:Object.keys(T.responses).map(L=>c.jsx("span",{style:j.answeredChip,children:L},L))})]}),c.jsxs("div",{style:j.controls,children:[c.jsx("label",{className:"label",style:{marginBottom:"0.75rem"},children:"Student display"}),c.jsxs("div",{style:j.controlGrid,children:[r&&r.resultPolicy==="manual"&&c.jsxs("div",{style:j.controlItem,children:[c.jsx("span",{style:j.controlLabel,children:"Results visible"}),c.jsx(zp,{active:!!r.revealResults,onChange:L=>yc(L,r.revealCorrect)})]}),r&&r.correctPolicy==="manual"&&r.correctIndex!=null&&c.jsxs("div",{style:j.controlItem,children:[c.jsx("span",{style:j.controlLabel,children:"Correct answer visible"}),c.jsx(zp,{active:!!r.revealCorrect,onChange:L=>yc(r.revealResults,L)})]}),c.jsxs("div",{style:j.statusSummary,children:[c.jsx(Bp,{label:"Results",state:T.resultPolicy==="never"?"never":T.resultPolicy==="on_submit"?"auto":T.revealResults?"shown":"hidden"}),T.correctIndex!=null&&c.jsx(Bp,{label:"Answer",state:T.correctPolicy==="never"?"never":tt(T)?"shown":"hidden"})]}),c.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"0.5rem",alignItems:"center"},children:[r&&c.jsx("button",{className:"btn btn-secondary",onClick:()=>y?F_(r.revealResults,r.revealCorrect):Do(r.revealResults,r.revealCorrect),children:y?"End Poll":"Close Poll"}),y&&c.jsx("button",{className:"btn btn-primary",onClick:Ee,children:x?"Finish Set βœ“":`Next Poll β†’ (${u.currentIndex+2} of ${u.totalPolls})`})]})]})]})]})]})]})]})}function zp({active:t,onChange:e}){return c.jsx("button",{onClick:()=>e(!t),style:{position:"relative",width:48,height:26,borderRadius:13,border:"none",background:t?"var(--success)":"var(--border)",cursor:"pointer",transition:"background 0.2s",flexShrink:0},children:c.jsx("span",{style:{position:"absolute",top:3,left:t?22:3,width:20,height:20,borderRadius:"50%",background:"white",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})})}function Bp({label:t,state:e}){const n={shown:{bg:"#dcfce7",color:"#15803d"},hidden:{bg:"#fee2e2",color:"#b91c1c"},auto:{bg:"#dbeafe",color:"#1d4ed8"},never:{bg:"var(--cream)",color:"var(--muted)"}},r={shown:"Shown",hidden:"Hidden",auto:"Auto",never:"Never"},i=n[e]||n.never;return c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem"},children:[c.jsxs("span",{style:{fontSize:"0.78rem",color:"var(--muted)"},children:[t,":"]}),c.jsx("span",{style:{background:i.bg,color:i.color,borderRadius:4,padding:"0.15rem 0.5rem",fontSize:"0.75rem",fontWeight:600},children:r[e]})]})}function gb({timeLeft:t,total:e}){const r=2*Math.PI*28,i=e>0?t/e:0,s=r*(1-i),o=i>.4?"var(--accent2)":i>.15?"#f59e0b":"var(--accent)";return c.jsxs("div",{style:{position:"relative",width:72,height:72,flexShrink:0},children:[c.jsxs("svg",{width:"72",height:"72",style:{transform:"rotate(-90deg)"},children:[c.jsx("circle",{cx:"36",cy:"36",r:28,fill:"none",stroke:"var(--cream)",strokeWidth:"5"}),c.jsx("circle",{cx:"36",cy:"36",r:28,fill:"none",stroke:o,strokeWidth:"5",strokeDasharray:r,strokeDashoffset:s,strokeLinecap:"round",style:{transition:"stroke-dashoffset 0.5s linear, stroke 0.5s"}})]}),c.jsx("span",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.1rem"},children:t})]})}const j={page:{display:"flex",minHeight:"100vh",background:"var(--paper)"},sidebar:{width:220,minHeight:"100vh",background:"var(--ink)",color:"white",display:"flex",flexDirection:"column",padding:"1.5rem 1rem",gap:"0.5rem",position:"sticky",top:0,flexShrink:0},logo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",padding:"0 0.5rem",marginBottom:"1rem"},nav:{display:"flex",flexDirection:"column",gap:"0.25rem"},navBtn:{background:"transparent",color:"rgba(255,255,255,0.7)",border:"none",borderRadius:8,padding:"0.6rem 0.75rem",textAlign:"left",cursor:"pointer",fontSize:"0.9rem",transition:"all 0.15s"},navActive:{background:"rgba(255,255,255,0.12)",color:"white"},navDisabled:{opacity:.4,cursor:"not-allowed"},sidebarBottom:{marginTop:"auto",display:"flex",flexDirection:"column",gap:"0.75rem"},studentCount:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem",color:"rgba(255,255,255,0.6)"},dot:{width:8,height:8,borderRadius:"50%",background:"#4ade80",flexShrink:0,boxShadow:"0 0 6px #4ade80"},studentList:{display:"flex",flexWrap:"wrap",gap:"0.35rem",maxHeight:120,overflowY:"auto"},studentChip:{background:"rgba(255,255,255,0.1)",borderRadius:4,padding:"0.2rem 0.5rem",fontSize:"0.78rem",color:"rgba(255,255,255,0.8)"},main:{flex:1,padding:"2rem",overflowY:"auto"},content:{maxWidth:"100%",margin:"0 auto"},pageTitle:{fontSize:"1.6rem",marginBottom:"1.5rem"},form:{display:"flex",flexDirection:"column",gap:"1.25rem",background:"white",padding:"1.5rem",borderRadius:12,border:"1px solid var(--border)"},hint:{fontSize:"0.82rem",color:"var(--muted)",marginBottom:"0.5rem"},policySection:{display:"flex",flexDirection:"column",gap:"0.5rem"},policyRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},policyBtn:{display:"flex",flexDirection:"column",gap:"0.2rem",padding:"0.6rem 0.85rem",borderRadius:8,border:"1.5px solid var(--border)",background:"var(--paper)",cursor:"pointer",textAlign:"left",transition:"all 0.15s",flex:1,minWidth:120},policyBtnActive:{borderColor:"var(--accent2)",background:"#eff6ff"},policyLabel:{fontSize:"0.88rem",fontWeight:600,color:"var(--ink)"},empty:{textAlign:"center",padding:"4rem 2rem",color:"var(--muted)",display:"flex",flexDirection:"column",alignItems:"center",gap:"0.75rem"},link:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"inherit",textDecoration:"underline"},queueBanner:{display:"flex",alignItems:"center",gap:"0.75rem",background:"#eff6ff",border:"1.5px solid var(--accent2)",borderRadius:12,padding:"0.75rem 1rem",marginBottom:"1.25rem"},queueIcon:{fontSize:"1.4rem"},queueName:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"0.95rem"},queueProgress:{color:"var(--accent2)",fontSize:"0.82rem",marginTop:"0.1rem"},queueDots:{display:"flex",gap:"0.35rem",alignItems:"center"},queueDot:{width:10,height:10,borderRadius:"50%",transition:"background 0.3s"},queueExit:{background:"none",border:"1px solid var(--border)",borderRadius:6,padding:"0.3rem 0.6rem",fontSize:"0.78rem",cursor:"pointer",color:"var(--muted)"},pollCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1.5rem"},timerRow:{display:"flex",alignItems:"center",gap:"1rem"},pollQuestion:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.1rem"},responseMeta:{color:"var(--muted)",fontSize:"0.85rem",marginTop:"0.2rem"},expiredBadge:{width:72,height:72,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.8rem",flexShrink:0},expiredTag:{color:"var(--accent)",fontWeight:500},optionRow:{display:"flex",alignItems:"center",gap:"0.75rem"},optionLabel:{width:28,height:28,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.8rem",fontWeight:700,flexShrink:0},correctLabel:{background:"#dcfce7",color:"var(--success)"},barBg:{height:8,borderRadius:4,background:"var(--cream)",overflow:"hidden"},barFill:{height:"100%",borderRadius:4,transition:"width 0.4s ease"},answeredChip:{background:"#dbeafe",color:"var(--accent2)",borderRadius:4,padding:"0.15rem 0.5rem",fontSize:"0.78rem"},correctBtn:{width:32,height:32,borderRadius:"50%",border:"2px solid var(--border)",background:"var(--cream)",cursor:"pointer",fontWeight:700,fontSize:"0.8rem",flexShrink:0,transition:"all 0.15s"},correctBtnActive:{background:"var(--success)",color:"white",borderColor:"var(--success)"},removeBtn:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",fontSize:"0.9rem",padding:"0.25rem",borderRadius:4},controls:{marginTop:"1.25rem",paddingTop:"1.25rem",borderTop:"1px solid var(--border)"},controlGrid:{display:"flex",gap:"1rem",alignItems:"center",flexWrap:"wrap"},controlItem:{display:"flex",alignItems:"center",gap:"0.6rem"},controlLabel:{fontSize:"0.85rem",color:"var(--muted)"},statusSummary:{display:"flex",gap:"0.75rem",flexWrap:"wrap"}};function vb(){var D;const t=Sr(),[e,n]=C.useState(""),[r,i]=C.useState(!1),[s,o]=C.useState(null),[l,a]=C.useState(null),[u,h]=C.useState(!1),[d,f]=C.useState(0),[v,w]=C.useState(null),_=C.useRef(null),E=C.useRef(null);C.useEffect(()=>dh(X=>{!X&&s&&(w(s),setTimeout(()=>w(null),1e4)),X&&X.id!==E.current&&(a(null),h(!1),E.current=X.id),o(X),X&&!X.ended&&f(Math.max(0,Math.round(X.duration-(Date.now()-X.startedAt)/1e3)))}),[s]),C.useEffect(()=>(clearInterval(_.current),s&&!s.ended&&(_.current=setInterval(()=>{const Y=Math.max(0,Math.round(s.duration-(Date.now()-s.startedAt)/1e3));f(Y),Y===0&&clearInterval(_.current)},500)),()=>clearInterval(_.current)),[s==null?void 0:s.id,s==null?void 0:s.ended]),C.useEffect(()=>{if(!r||!e)return;const Y=()=>vc(e);return window.addEventListener("beforeunload",Y),()=>{Y(),window.removeEventListener("beforeunload",Y)}},[r,e]);function g(Y){Y.preventDefault();const X=e.trim();X&&T_(X).then(()=>i(!0))}function p(Y){u||d===0||s!=null&&s.ended||a(Y)}function m(){l===null||u||!s||(b_(e,s.id,l),h(!0))}const S=s&&((D=s.responses)==null?void 0:D[e])!==void 0,I=S?s.responses[e]:l,P=s?Object.keys(s.responses||{}).length:0,b=(s==null?void 0:s.ended)||d===0;function A(){return s?s.revealResults?!0:s.resultPolicy==="never"||s.resultPolicy==="manual"?!1:s.resultPolicy==="on_submit"?u||S:!1:!1}function q(){return!s||s.correctIndex==null?!1:s.revealCorrect?!0:s.correctPolicy==="never"||s.correctPolicy==="manual"?!1:s.correctPolicy==="with_results"?A():!1}const z=A(),pe=q();return r?!s&&!v?c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.waitCard,className:"fade-up",children:[c.jsx("div",{style:se.pulse}),c.jsxs("h2",{style:{fontFamily:"var(--font-display)",fontSize:"1.5rem"},children:["Hi, ",e,"! πŸ‘‹"]}),c.jsx("p",{style:{color:"var(--muted)"},children:"Waiting for the teacher to start a poll…"}),c.jsx("button",{style:se.backLink,onClick:()=>{vc(e),t("/")},children:"Leave session"})]})}):!s&&v?c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.waitCard,className:"fade-up",children:[c.jsx("span",{style:{fontSize:"2.5rem"},children:"βœ…"}),c.jsx("h2",{style:{fontFamily:"var(--font-display)"},children:"Poll closed!"}),c.jsx("p",{style:{color:"var(--muted)",textAlign:"center"},children:c.jsx("em",{children:v.question})}),v.correctIndex!=null&&v.revealCorrect&&c.jsxs("p",{style:{color:"var(--success)",fontWeight:600},children:["Correct answer: ",v.options[v.correctIndex]]}),c.jsx("p",{style:{color:"var(--muted)",fontSize:"0.85rem"},children:"Waiting for next poll…"})]})}):c.jsxs("div",{style:se.pollPage,children:[c.jsxs("header",{style:se.pollHeader,children:[c.jsxs("span",{style:{fontFamily:"var(--font-display)",fontWeight:700},children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsxs("span",{style:{color:"var(--muted)",fontSize:"0.9rem"},children:["Signed in as ",c.jsx("strong",{children:e})]})]}),c.jsxs("div",{style:se.pollContent,className:"fade-up",children:[!s.ended&&c.jsxs(c.Fragment,{children:[c.jsx("div",{style:se.timerBar,children:c.jsx("div",{style:{...se.timerFill,width:`${d/s.duration*100}%`,background:d>s.duration*.4?"var(--accent2)":d>s.duration*.15?"#f59e0b":"var(--accent)"}})}),c.jsxs("div",{style:se.timerLabel,children:[d,"s remaining Β· ",P," responded"]})]}),s.ended&&c.jsx("div",{style:se.stoppedBanner,children:"⏰ Time's up β€” waiting for teacher"}),c.jsx("h2",{style:se.questionText,children:s.question}),c.jsx("div",{style:se.optionGrid,children:s.options.map((Y,X)=>{const et=I===X,Ee=s.correctIndex===X,Be=Object.values(s.responses||{}).filter(U=>U===X).length,R=P>0?Math.round(Be/P*100):0;return c.jsxs("button",{style:{...se.optionBtn,...et?se.optionSelected:{},...pe&&Ee?se.optionCorrect:{},...b||S?{cursor:"default"}:{}},onClick:()=>p(X),disabled:b||S,children:[c.jsx("span",{style:se.optionLetter,children:String.fromCharCode(65+X)}),c.jsx("span",{style:{flex:1,textAlign:"left"},children:Y}),z&&c.jsxs("span",{style:se.optionPct,children:[R,"%"]}),z&&c.jsx("div",{style:{...se.optionBar,width:`${R}%`,background:pe&&Ee?"rgba(22,163,74,0.15)":"rgba(37,99,235,0.1)"}})]},X)})}),!S&&!u&&!b&&c.jsx("button",{className:"btn btn-primary",style:{width:"100%",justifyContent:"center",padding:"0.85rem",fontSize:"1rem",marginTop:"0.5rem"},onClick:m,disabled:l===null,children:"Submit Answer"}),(u||S)&&!b&&c.jsx("div",{style:se.submittedBadge,children:"βœ“ Answer submitted"}),b&&!S&&!u&&c.jsx("div",{style:{...se.submittedBadge,background:"#fef9c3",color:"#854d0e",borderColor:"#fef08a"},children:"⏰ Time's up β€” no answer recorded"}),b&&(S||u)&&c.jsx("div",{style:se.submittedBadge,children:"βœ“ Answer submitted β€” waiting for teacher"})]})]}):c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.joinCard,className:"fade-up",children:[c.jsxs("div",{style:se.joinLogo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsx("h1",{style:{fontSize:"1.8rem",marginBottom:"0.25rem"},children:"Join Session"}),c.jsx("p",{style:{color:"var(--muted)",marginBottom:"1.5rem"},children:"Enter your name to start answering polls"}),c.jsxs("form",{onSubmit:g,style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[c.jsx("input",{className:"input",placeholder:"Your first name",value:e,onChange:Y=>n(Y.target.value),autoFocus:!0,style:{fontSize:"1.1rem",textAlign:"center"},required:!0}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{justifyContent:"center",padding:"0.75rem"},children:"Join β†’"})]}),c.jsx("button",{style:se.backLink,onClick:()=>t("/"),children:"← Back"})]})})}const se={center:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"var(--paper)"},joinCard:{background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"2.5rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},joinLogo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",marginBottom:"1.5rem",display:"block"},backLink:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",marginTop:"1rem",fontSize:"0.85rem",display:"block",textAlign:"center"},waitCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:"0.75rem",background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"3rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},pulse:{width:16,height:16,borderRadius:"50%",background:"var(--accent2)",boxShadow:"0 0 0 0 rgba(37,99,235,0.4)",animation:"pulse-ring 1.5s ease-out infinite"},pollPage:{minHeight:"100vh",background:"var(--paper)",display:"flex",flexDirection:"column"},pollHeader:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",display:"flex",justifyContent:"space-between",alignItems:"center",background:"white"},pollContent:{maxWidth:620,margin:"0 auto",padding:"2rem 1rem",width:"100%"},timerBar:{height:6,background:"var(--cream)",borderRadius:3,overflow:"hidden",marginBottom:"0.4rem"},timerFill:{height:"100%",borderRadius:3,transition:"width 0.5s linear, background 0.5s"},timerLabel:{color:"var(--muted)",fontSize:"0.82rem",marginBottom:"1.5rem"},stoppedBanner:{background:"#fef9c3",color:"#854d0e",border:"1px solid #fef08a",borderRadius:8,padding:"0.6rem 1rem",fontSize:"0.9rem",marginBottom:"1.5rem",textAlign:"center"},questionText:{fontFamily:"var(--font-display)",fontSize:"clamp(1.2rem, 3vw, 1.6rem)",lineHeight:1.25,marginBottom:"1.25rem"},optionGrid:{display:"flex",flexDirection:"column",gap:"0.6rem"},optionBtn:{position:"relative",overflow:"hidden",display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.9rem 1rem",borderRadius:10,border:"2px solid var(--border)",background:"white",cursor:"pointer",transition:"all 0.15s",textAlign:"left",fontFamily:"var(--font-body)",fontSize:"0.95rem"},optionSelected:{borderColor:"var(--accent2)",background:"#eff6ff"},optionCorrect:{borderColor:"var(--success)",background:"#f0fdf4"},optionLetter:{width:28,height:28,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.8rem",fontWeight:700,flexShrink:0},optionPct:{color:"var(--muted)",fontSize:"0.82rem",fontWeight:600,flexShrink:0,zIndex:1},optionBar:{position:"absolute",left:0,top:0,height:"100%",transition:"width 0.4s ease",zIndex:0,pointerEvents:"none"},submittedBadge:{marginTop:"1rem",padding:"0.75rem",borderRadius:8,background:"#f0fdf4",color:"var(--success)",textAlign:"center",fontWeight:500,fontSize:"0.9rem",border:"1px solid #bbf7d0"}};function U_(t,e={}){const{duration:n=60,resultPolicy:r="on_submit",correctPolicy:i="with_results"}=e,s=t.split(/^---$/m).map(l=>l.trim()).filter(Boolean),o=[];for(const l of s){const a=l.split(` `);let u="",h=[],d=null,f=n,v=r,w=i,_=0;for(;_=a.length)){for(u=a[_].replace(/^Q:\s*/i,"").trim(),_++;_{const r=[];return n.duration!==e.duration&&r.push(`duration: ${n.duration}`),n.resultPolicy!==e.resultPolicy&&r.push(`results: ${n.resultPolicy}`),n.correctPolicy!==e.correctPolicy&&r.push(`correct: ${n.correctPolicy}`),r.push(`Q: ${n.question}`),r.push(""),n.options.forEach((i,s)=>{const o=n.correctIndex===s?"* ":" ";r.push(`${o}${String.fromCharCode(65+s)}. ${i}`)}),r.join(` @@ -2744,4 +2744,4 @@ duration: 90 D. Vacuole`,value:g,onChange:D=>{p(D.target.value),S(null),P("")},style:{fontFamily:"monospace",fontSize:"0.85rem",resize:"vertical",minHeight:"320px",width:"100%"}}),c.jsxs("div",{style:{display:"flex",gap:"0.75rem",alignItems:"center"},children:[c.jsx("button",{className:"btn btn-secondary",onClick:A,children:"Preview β†’"}),I&&c.jsx("span",{style:Q.err,children:I})]})]}),_==="manual"&&c.jsxs("div",{style:Q.manualBox,children:[c.jsx("p",{children:"The set will be created empty. You can add and edit polls one by one in the set detail view."}),u&&c.jsx("p",{style:Q.err,children:u}),c.jsx("button",{className:"btn btn-primary",style:{marginTop:"0.5rem"},onClick:z,disabled:l,children:l?"Creating…":"Create empty set β†’"})]})]}),_==="text"&&m&&c.jsxs("div",{style:Q.previewBox,children:[c.jsxs("label",{className:"label",children:["Preview β€” ",m.length," poll",m.length!==1?"s":""," found"]}),m.map((D,Y)=>{var X,et;return c.jsxs("div",{style:Q.previewPoll,children:[c.jsxs("div",{style:Q.previewQ,children:[Y+1,". ",D.question]}),c.jsx("div",{style:Q.previewOptions,children:D.options.map((Ee,Be)=>c.jsxs("div",{style:{...Q.previewOpt,...D.correctIndex===Be?Q.previewOptCorrect:{}},children:[D.correctIndex===Be?"βœ“":String.fromCharCode(65+Be),". ",Ee]},Be))}),c.jsxs("div",{style:Q.previewMeta,children:[D.duration,"s Β· Results: ",(X=Vp.find(Ee=>Ee.value===D.resultPolicy))==null?void 0:X.label," Β· Answer: ",(et=Hp.find(Ee=>Ee.value===D.correctPolicy))==null?void 0:et.label]})]},Y)}),u&&c.jsx("p",{style:Q.err,children:u}),c.jsx("button",{className:"btn btn-primary",onClick:q,disabled:l,children:l?"Saving…":"Save Set β†’"})]})]})]})]})}const Q={page:{minHeight:"100vh",background:"var(--paper)"},header:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",background:"white",display:"flex",alignItems:"center",gap:"1rem"},back:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"0.9rem"},title:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.2rem",flex:1},main:{maxWidth:960,margin:"0 auto",padding:"1.5rem 1rem"},empty:{textAlign:"center",padding:"4rem 2rem",color:"var(--muted)",display:"flex",flexDirection:"column",alignItems:"center",gap:"1rem"},setCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",marginBottom:"0.75rem",display:"flex",alignItems:"center",overflow:"hidden"},setCardBtn:{display:"flex",alignItems:"center",justifyContent:"space-between",flex:1,padding:"1rem",background:"none",border:"none",cursor:"pointer",textAlign:"left"},setName:{fontFamily:"var(--font-display)",fontWeight:600,fontSize:"1rem"},setMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},setActions:{padding:"0 0.75rem",display:"flex",alignItems:"center",gap:"0.4rem"},deleteBtn:{background:"none",border:"none",cursor:"pointer",fontSize:"1.1rem",padding:"0.25rem 0.4rem",borderRadius:6,opacity:.5},confirmRow:{display:"flex",alignItems:"center",gap:"0.4rem"},confirmText:{fontSize:"0.82rem",color:"var(--muted)",whiteSpace:"nowrap"},createForm:{display:"flex",flexDirection:"column",gap:"1.25rem"},sectionTitle:{fontSize:"1.4rem"},defaultsBox:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1rem",display:"flex",flexDirection:"column",gap:"0.75rem"},defaultsRow:{display:"flex",gap:"0.75rem",flexWrap:"wrap",alignItems:"flex-end"},modeTabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:8,padding:"0.25rem",marginBottom:"0.75rem",width:"fit-content"},modeTab:{background:"none",border:"none",padding:"0.35rem 0.85rem",borderRadius:6,cursor:"pointer",fontSize:"0.9rem",color:"var(--muted)"},modeTabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},manualBox:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1.25rem",color:"var(--muted)",fontSize:"0.9rem",display:"flex",flexDirection:"column",gap:"0.5rem"},previewBox:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1.25rem",display:"flex",flexDirection:"column",gap:"0.75rem"},previewPoll:{borderBottom:"1px solid var(--border)",paddingBottom:"0.75rem",display:"flex",flexDirection:"column",gap:"0.4rem"},previewQ:{fontWeight:600,fontSize:"0.95rem"},previewOptions:{display:"flex",flexDirection:"column",gap:"0.2rem",paddingLeft:"0.75rem"},previewOpt:{fontSize:"0.88rem",color:"var(--muted)"},previewOptCorrect:{color:"var(--success)",fontWeight:600},previewMeta:{fontSize:"0.75rem",color:"var(--muted)",marginTop:"0.25rem"},err:{color:"var(--accent)",fontSize:"0.85rem"}};function Eb(t,e=40){return t.length>e?t.slice(0,e)+"...":t}function xb(t){if(t==null)return"";const e=String(t);return e.includes(",")||e.includes('"')||e.includes(` `)?`"${e.replace(/"/g,'""')}"`:e}function nt(t){return t.map(xb).join(",")}function Ib(t){const e=t.responses||{},n=t.correctIndex!=null,r=[];r.push(nt(["Question",t.question])),r.push(nt(["Date",new Date(t.startedAt).toLocaleString()])),n&&r.push(nt(["Correct Answer",`${String.fromCharCode(65+t.correctIndex)}. ${t.options[t.correctIndex]}`])),r.push("");const i=["Student","Response"];n&&i.push("Correct (1=yes 0=no)"),r.push(nt(i));const s=Object.keys(e).sort();return s.length===0?r.push(nt(["(no responses)","",""])):s.forEach(o=>{const l=e[o],a=l!=null?`${String.fromCharCode(65+l)}. ${t.options[l]}`:"(no answer)",u=[o,a];n&&u.push(l===t.correctIndex?"1":"0"),r.push(nt(u))}),r.join(` `)}function kb(t,e){if(!e||e.length===0)return"";const n=new Set;e.forEach(o=>{Object.keys(o.responses||{}).forEach(l=>n.add(l))});const r=[...n].sort(),i=[];i.push(nt(["Set",t])),i.push(nt(["Date",new Date(e[0].startedAt).toLocaleString()])),i.push(nt(["Polls",e.length])),i.push("");const s=["Student"];return e.forEach((o,l)=>{const a=`Q${l+1}: ${Eb(o.question)}`;s.push(a),o.correctIndex!=null&&s.push(`Q${l+1} Correct (1=yes 0=no)`)}),i.push(nt(s)),r.forEach(o=>{const l=[o];e.forEach(a=>{const h=(a.responses||{})[o],d=h!=null?`${String.fromCharCode(65+h)}. ${a.options[h]}`:"(no answer)";l.push(d),a.correctIndex!=null&&l.push(h===a.correctIndex?"1":"0")}),i.push(nt(l))}),i.push(""),i.push(nt(["Summary"])),e.forEach((o,l)=>{const a=o.responses||{},u=Object.keys(a).length;i.push(""),i.push(nt([`Q${l+1}`,o.question])),o.options.forEach((h,d)=>{const f=Object.values(a).filter(_=>_===d).length,v=u>0?Math.round(f/u*100):0,w=o.correctIndex===d;i.push(nt([`${String.fromCharCode(65+d)}. ${h}`,`${f} responses`,`${v}%`,w?"correct answer":""]))})}),i.join(` -`)}function Gp(t,e){const n=new Blob([e],{type:"text/csv;charset=utf-8;"}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=t,i.click(),URL.revokeObjectURL(r)}const Tb="prof123";function bb(){const t=Sr(),[e,n]=C.useState(!1),[r,i]=C.useState(""),[s,o]=C.useState(""),[l,a]=C.useState([]),[u,h]=C.useState({}),[d,f]=C.useState("polls"),[v,w]=C.useState(new Set),[_,E]=C.useState(new Set),[g,p]=C.useState(null),[m,S]=C.useState(null),[I,P]=C.useState({}),[b,A]=C.useState({});C.useEffect(()=>{(localStorage.getItem("historyAuth")==="true"||localStorage.getItem("role")==="teacher")&&n(!0)},[]),C.useEffect(()=>{if(!e)return;const y=R_(a),x=xr(ne(re,"sessionStudents"),T=>{const O=T.val()||{},K={};Object.values(O).forEach(Ge=>{const L=Ge.date||"unknown";K[L]||(K[L]=new Set),K[L].add(Ge.name)});const tt={};Object.entries(K).forEach(([Ge,L])=>{tt[Ge]=[...L].sort()}),h(tt)});return()=>{y(),x()}},[e]);function q(y){y.preventDefault(),r===Tb?(localStorage.setItem("historyAuth","true"),n(!0)):(o("Incorrect password."),i(""))}function z(y){vr(ne(re,`pollHistory/${y}`)),p(null),w(x=>{const T=new Set(x);return T.delete(y),T})}function pe(y,x){x.forEach(T=>vr(ne(re,`pollHistory/${T.id}`))),S(null),E(T=>{const O=new Set(T);return O.delete(y),O})}function D(y){w(x=>{const T=new Set(x);return T.has(y)?T.delete(y):T.add(y),T})}function Y(y){E(x=>{const T=new Set(x);return T.has(y)?T.delete(y):T.add(y),T})}function X(y,x){P(T=>({...T,[y]:x}))}function et(y){A(x=>({...x,[y]:!0})),setTimeout(()=>A(x=>({...x,[y]:!1})),2e3)}function Ee(y){const x=Ib(y),T=new Date(y.startedAt).toLocaleDateString().replace(/\//g,"-");Gp(`poll_${T}_${y.id}.csv`,x)}function Be(y,x){const T=kb(y,x),O=new Date(x[0].startedAt).toLocaleDateString().replace(/\//g,"-"),K=y.replace(/[^a-z0-9]/gi,"_").toLowerCase();Gp(`session_${K}_${O}.csv`,T)}function R(y){const x={},T=[];return y.forEach(O=>{if(O.setId){const K=O.sessionKey||`${O.setId}_${new Date(O.startedAt).toLocaleDateString()}`;x[K]||(x[K]={key:K,setId:O.setId,setName:O.setName,date:new Date(O.startedAt).toLocaleDateString(),startedAt:O.startedAt,polls:[]}),x[K].polls.push(O)}else T.push(O)}),Object.values(x).forEach(O=>{O.polls.sort((K,tt)=>(K.setPosition??0)-(tt.setPosition??0))}),[...Object.values(x).map(O=>({type:"set",...O})),...T.map(O=>({type:"poll",...O}))].sort((O,K)=>(K.startedAt||0)-(O.startedAt||0))}if(!e)return c.jsx("div",{style:F.center,children:c.jsxs("div",{style:F.loginCard,className:"fade-up",children:[c.jsxs("div",{style:F.loginLogo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsx("h2",{style:{fontSize:"1.4rem",marginBottom:"0.25rem"},children:"Poll History"}),c.jsx("p",{style:{color:"var(--muted)",marginBottom:"1.5rem",fontSize:"0.9rem"},children:"Enter the teacher password to view history and attendance."}),c.jsxs("form",{onSubmit:q,style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[c.jsx("input",{className:"input",type:"password",placeholder:"Teacher password",value:r,onChange:y=>{i(y.target.value),o("")},autoFocus:!0,style:{textAlign:"center"}}),s&&c.jsx("span",{style:F.err,children:s}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{justifyContent:"center",padding:"0.75rem"},children:"View History β†’"})]}),c.jsx("button",{style:F.backLink,onClick:()=>t("/"),children:"← Back"})]})});const U=R(l);return c.jsxs("div",{style:F.page,children:[c.jsxs("header",{style:F.header,children:[c.jsx("button",{style:F.back,onClick:()=>t("/"),children:"← Back"}),c.jsx("span",{style:F.title,children:"Poll History"}),c.jsxs("div",{style:F.tabs,children:[c.jsx("button",{style:{...F.tab,...d==="polls"?F.tabActive:{}},onClick:()=>f("polls"),children:"Polls"}),c.jsx("button",{style:{...F.tab,...d==="attendance"?F.tabActive:{}},onClick:()=>f("attendance"),children:"Attendance"})]})]}),c.jsxs("main",{style:F.main,children:[d==="polls"&&c.jsxs("div",{className:"fade-up",children:[U.length===0&&c.jsx("div",{style:F.empty,children:"No polls yet. Run your first one in class!"}),U.map(y=>{if(y.type==="set"){const x=_.has(y.key),T=y.polls.reduce((O,K)=>O+Object.keys(K.responses||{}).length,0);return c.jsxs("div",{style:F.setGroup,children:[c.jsxs("div",{style:F.setGroupHeaderRow,children:[c.jsxs("button",{style:F.setGroupHeaderBtn,onClick:()=>Y(y.key),children:[c.jsx("span",{style:F.triangle,children:x?"β–Ό":"β–Ά"}),c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{style:F.setGroupName,children:["πŸ“š ",y.setName]}),c.jsxs("div",{style:F.setGroupMeta,children:[y.date," Β· ",y.polls.length," polls Β· ",T," total responses"]})]})]}),c.jsxs("div",{style:{display:"flex",gap:"0.4rem",alignItems:"center"},children:[c.jsx("button",{style:{...F.exportBtn,...b[y.key]?F.exportBtnSuccess:{}},onClick:()=>{Be(y.setName,y.polls),et(y.key)},children:b[y.key]?"βœ“ Downloading":"⬇ Session CSV"}),m!==y.key?c.jsx("button",{style:F.deleteBtn,onClick:()=>S(y.key),title:"Delete this session",children:"πŸ—‘"}):c.jsxs("div",{style:F.confirmRow,children:[c.jsxs("span",{style:F.confirmText,children:["Delete all ",y.polls.length," polls?"]}),c.jsx("button",{className:"btn btn-primary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem",background:"#dc2626"},onClick:()=>pe(y.key,y.polls),children:"Yes"}),c.jsx("button",{className:"btn btn-secondary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem"},onClick:()=>S(null),children:"Cancel"})]})]})]}),x&&c.jsx("div",{style:F.setGroupPolls,children:y.polls.map(O=>c.jsx(qp,{poll:O,expanded:v.has(O.id),viewMode:I[O.id]||"summary",confirmDelete:g,copyFeedback:b[O.id],onToggle:()=>D(O.id),onDelete:()=>z(O.id),onConfirmDelete:()=>p(O.id),onCancelDelete:()=>p(null),onSetView:K=>X(O.id,K),onDownload:()=>Ee(O),onDownloadFeedback:()=>et(O.id),positionLabel:`${(O.setPosition??0)+1}.`},O.id))})]},y.key)}return c.jsx(qp,{poll:y,expanded:v.has(y.id),viewMode:I[y.id]||"summary",confirmDelete:g,copyFeedback:b[y.id],onToggle:()=>D(y.id),onDelete:()=>z(y.id),onConfirmDelete:()=>p(y.id),onCancelDelete:()=>p(null),onSetView:x=>X(y.id,x),onDownload:()=>Ee(y),onDownloadFeedback:()=>et(y.id)},y.id)})]}),d==="attendance"&&c.jsxs("div",{className:"fade-up",children:[Object.keys(u).length===0&&c.jsx("div",{style:F.empty,children:"No attendance records yet."}),Object.entries(u).sort(([y],[x])=>x.localeCompare(y)).map(([y,x])=>c.jsxs("div",{style:F.pollCard,children:[c.jsx("div",{style:F.pollHeaderRow,children:c.jsxs("div",{style:{padding:"0.25rem 0"},children:[c.jsx("div",{style:F.pollQ,children:y}),c.jsxs("div",{style:F.pollMeta,children:[x.length," student",x.length!==1?"s":""]})]})}),c.jsx("div",{style:{padding:"0 1rem 1rem",display:"flex",flexWrap:"wrap",gap:"0.4rem"},children:x.map(T=>c.jsx("span",{style:F.chip,children:T},T))})]},y))]})]})]})}function qp({poll:t,expanded:e,viewMode:n,confirmDelete:r,copyFeedback:i,onToggle:s,onDelete:o,onConfirmDelete:l,onCancelDelete:a,onSetView:u,onDownload:h,onDownloadFeedback:d,positionLabel:f}){const v=t.responses||{},w=Object.keys(v).length,_=r===t.id,E=t.correctIndex!=null,g={};return t.options.forEach((p,m)=>{g[m]=[]}),Object.entries(v).forEach(([p,m])=>{g[m]!==void 0?g[m].push(p):g[m]=[p]}),c.jsxs("div",{style:F.pollCard,children:[c.jsxs("div",{style:F.pollHeaderRow,children:[c.jsxs("button",{style:F.pollHeaderBtn,onClick:s,children:[c.jsx("span",{style:F.triangle,children:e?"β–Ό":"β–Ά"}),c.jsxs("div",{children:[c.jsxs("div",{style:F.pollQ,children:[f&&c.jsxs("span",{style:F.posLabel,children:[f," "]}),t.question]}),c.jsxs("div",{style:F.pollMeta,children:[new Date(t.startedAt).toLocaleString()," Β· ",w," response",w!==1?"s":""]})]})]}),c.jsxs("div",{style:{display:"flex",gap:"0.4rem",alignItems:"center"},children:[!_&&c.jsx("button",{style:{...F.exportBtn,...i?F.exportBtnSuccess:{}},onClick:()=>{h(),d()},children:i?"βœ“ Downloading":"⬇ CSV"}),_?c.jsxs("div",{style:F.confirmRow,children:[c.jsx("span",{style:F.confirmText,children:"Delete?"}),c.jsx("button",{className:"btn btn-primary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem",background:"#dc2626"},onClick:o,children:"Yes"}),c.jsx("button",{className:"btn btn-secondary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem"},onClick:a,children:"Cancel"})]}):c.jsx("button",{style:F.deleteBtn,onClick:l,title:"Delete",children:"πŸ—‘"})]})]}),e&&c.jsxs("div",{style:F.pollDetails,children:[c.jsxs("div",{style:F.viewTabs,children:[c.jsx("button",{style:{...F.viewTab,...n==="summary"?F.viewTabActive:{}},onClick:()=>u("summary"),children:"Summary"}),c.jsx("button",{style:{...F.viewTab,...n==="students"?F.viewTabActive:{}},onClick:()=>u("students"),children:"By student"})]}),n==="summary"&&c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.6rem"},children:t.options.map((p,m)=>{const S=Object.values(v).filter(b=>b===m).length,I=w>0?Math.round(S/w*100):0,P=E&&t.correctIndex===m;return c.jsxs("div",{style:F.histOpt,children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:4},children:[c.jsxs("span",{style:{fontWeight:P?600:400,color:P?"var(--success)":"inherit"},children:[String.fromCharCode(65+m),". ",p," ",P&&"βœ“"]}),c.jsxs("span",{style:{color:"var(--muted)",fontSize:"0.85rem"},children:[S," (",I,"%)"]})]}),c.jsx("div",{style:F.barBg,children:c.jsx("div",{style:{...F.barFill,width:`${I}%`,background:P?"var(--success)":"var(--accent2)"}})})]},m)})}),n==="students"&&c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[t.options.map((p,m)=>{const S=g[m]||[],I=E&&t.correctIndex===m;return S.length===0?null:c.jsxs("div",{style:F.answerGroup,children:[c.jsxs("div",{style:{...F.answerGroupHeader,...I?F.answerGroupCorrect:{}},children:[c.jsxs("span",{style:{fontWeight:600},children:[String.fromCharCode(65+m),". ",p]}),I&&c.jsx("span",{style:F.correctTag,children:"βœ“ correct"}),c.jsxs("span",{style:F.answerCount,children:[S.length," student",S.length!==1?"s":""]})]}),c.jsx("div",{style:F.studentNames,children:S.sort().map(P=>c.jsx("span",{style:F.chip,children:P},P))})]},m)}),w===0&&c.jsx("div",{style:{color:"var(--muted)",fontSize:"0.9rem"},children:"No responses."})]})]})]})}const F={center:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"var(--paper)"},loginCard:{background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"2.5rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},loginLogo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",marginBottom:"1.5rem",display:"block"},err:{color:"var(--accent)",fontSize:"0.85rem"},backLink:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",marginTop:"1rem",fontSize:"0.85rem",display:"block",textAlign:"center"},page:{minHeight:"100vh",background:"var(--paper)"},header:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",background:"white",display:"flex",alignItems:"center",gap:"1rem",flexWrap:"wrap"},back:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"0.9rem"},title:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.2rem",flex:1},tabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:8,padding:"0.25rem"},tab:{background:"none",border:"none",padding:"0.35rem 0.85rem",borderRadius:6,cursor:"pointer",fontSize:"0.9rem",color:"var(--muted)",transition:"all 0.15s"},tabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},main:{maxWidth:760,margin:"0 auto",padding:"1.5rem 1rem"},empty:{textAlign:"center",color:"var(--muted)",padding:"3rem",fontSize:"0.95rem"},setGroup:{background:"white",borderRadius:12,border:"1.5px solid var(--accent2)",marginBottom:"0.75rem",overflow:"hidden"},setGroupHeaderRow:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.85rem 1rem",borderBottom:"1px solid var(--cream)"},setGroupHeaderBtn:{display:"flex",alignItems:"center",gap:"0.75rem",background:"none",border:"none",cursor:"pointer",textAlign:"left",flex:1},setGroupName:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"0.95rem"},setGroupMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},setGroupPolls:{padding:"0.5rem 0.75rem",display:"flex",flexDirection:"column",gap:"0.4rem"},triangle:{fontSize:"0.7rem",color:"var(--muted)",flexShrink:0},exportBtn:{background:"var(--cream)",border:"1px solid var(--border)",borderRadius:6,padding:"0.3rem 0.65rem",fontSize:"0.78rem",cursor:"pointer",color:"var(--ink)",whiteSpace:"nowrap",transition:"all 0.15s",flexShrink:0},exportBtnSuccess:{background:"#dcfce7",borderColor:"var(--success)",color:"var(--success)"},pollCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",marginBottom:"0.75rem",overflow:"hidden"},pollHeaderRow:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.75rem 1rem"},pollHeaderBtn:{display:"flex",alignItems:"center",gap:"0.6rem",background:"none",border:"none",cursor:"pointer",textAlign:"left",flex:1,padding:"0.25rem 0"},posLabel:{color:"var(--muted)",fontWeight:400},pollQ:{fontFamily:"var(--font-display)",fontWeight:600,fontSize:"0.95rem"},pollMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},deleteBtn:{background:"none",border:"none",cursor:"pointer",fontSize:"1.1rem",padding:"0.25rem 0.4rem",borderRadius:6,opacity:.5},confirmRow:{display:"flex",alignItems:"center",gap:"0.4rem"},confirmText:{fontSize:"0.82rem",color:"var(--muted)",whiteSpace:"nowrap"},pollDetails:{padding:"0.75rem 1rem 1rem",borderTop:"1px solid var(--border)"},viewTabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:6,padding:"0.2rem",marginBottom:"0.75rem",width:"fit-content"},viewTab:{background:"none",border:"none",padding:"0.25rem 0.65rem",borderRadius:4,cursor:"pointer",fontSize:"0.82rem",color:"var(--muted)"},viewTabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 2px rgba(0,0,0,0.08)"},histOpt:{marginBottom:"0.6rem"},barBg:{height:6,borderRadius:3,background:"var(--cream)",overflow:"hidden"},barFill:{height:"100%",borderRadius:3,transition:"width 0.3s"},answerGroup:{borderRadius:8,border:"1px solid var(--border)",overflow:"hidden"},answerGroupHeader:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",background:"var(--cream)",flexWrap:"wrap"},answerGroupCorrect:{background:"#dcfce7"},correctTag:{fontSize:"0.75rem",color:"var(--success)",fontWeight:600,background:"#bbf7d0",borderRadius:4,padding:"0.1rem 0.4rem"},answerCount:{marginLeft:"auto",fontSize:"0.78rem",color:"var(--muted)"},studentNames:{padding:"0.5rem 0.75rem",display:"flex",flexWrap:"wrap",gap:"0.35rem"},chip:{background:"var(--cream)",borderRadius:4,padding:"0.2rem 0.5rem",fontSize:"0.78rem",color:"var(--ink)"}};function Pb(){return c.jsx(dC,{basename:"/classroom-polling",children:c.jsxs(aC,{children:[c.jsx(fn,{path:"/",element:c.jsx(fC,{})}),c.jsx(fn,{path:"/teacher",element:c.jsx(mb,{})}),c.jsx(fn,{path:"/student",element:c.jsx(vb,{})}),c.jsx(fn,{path:"/pollsets/:id",element:c.jsx(Sb,{})}),c.jsx(fn,{path:"/pollsets",element:c.jsx(Cb,{})}),c.jsx(fn,{path:"/history",element:c.jsx(bb,{})}),c.jsx(fn,{path:"*",element:c.jsx(oC,{to:"/"})})]})})}Za.createRoot(document.getElementById("root")).render(c.jsx(im.StrictMode,{children:c.jsx(Pb,{})})); +`)}function Gp(t,e){const n=new Blob([e],{type:"text/csv;charset=utf-8;"}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=t,i.click(),URL.revokeObjectURL(r)}const Tb="changeme";function bb(){const t=Sr(),[e,n]=C.useState(!1),[r,i]=C.useState(""),[s,o]=C.useState(""),[l,a]=C.useState([]),[u,h]=C.useState({}),[d,f]=C.useState("polls"),[v,w]=C.useState(new Set),[_,E]=C.useState(new Set),[g,p]=C.useState(null),[m,S]=C.useState(null),[I,P]=C.useState({}),[b,A]=C.useState({});C.useEffect(()=>{(localStorage.getItem("historyAuth")==="true"||localStorage.getItem("role")==="teacher")&&n(!0)},[]),C.useEffect(()=>{if(!e)return;const y=R_(a),x=xr(ne(re,"sessionStudents"),T=>{const O=T.val()||{},K={};Object.values(O).forEach(Ge=>{const L=Ge.date||"unknown";K[L]||(K[L]=new Set),K[L].add(Ge.name)});const tt={};Object.entries(K).forEach(([Ge,L])=>{tt[Ge]=[...L].sort()}),h(tt)});return()=>{y(),x()}},[e]);function q(y){y.preventDefault(),r===Tb?(localStorage.setItem("historyAuth","true"),n(!0)):(o("Incorrect password."),i(""))}function z(y){vr(ne(re,`pollHistory/${y}`)),p(null),w(x=>{const T=new Set(x);return T.delete(y),T})}function pe(y,x){x.forEach(T=>vr(ne(re,`pollHistory/${T.id}`))),S(null),E(T=>{const O=new Set(T);return O.delete(y),O})}function D(y){w(x=>{const T=new Set(x);return T.has(y)?T.delete(y):T.add(y),T})}function Y(y){E(x=>{const T=new Set(x);return T.has(y)?T.delete(y):T.add(y),T})}function X(y,x){P(T=>({...T,[y]:x}))}function et(y){A(x=>({...x,[y]:!0})),setTimeout(()=>A(x=>({...x,[y]:!1})),2e3)}function Ee(y){const x=Ib(y),T=new Date(y.startedAt).toLocaleDateString().replace(/\//g,"-");Gp(`poll_${T}_${y.id}.csv`,x)}function Be(y,x){const T=kb(y,x),O=new Date(x[0].startedAt).toLocaleDateString().replace(/\//g,"-"),K=y.replace(/[^a-z0-9]/gi,"_").toLowerCase();Gp(`session_${K}_${O}.csv`,T)}function R(y){const x={},T=[];return y.forEach(O=>{if(O.setId){const K=O.sessionKey||`${O.setId}_${new Date(O.startedAt).toLocaleDateString()}`;x[K]||(x[K]={key:K,setId:O.setId,setName:O.setName,date:new Date(O.startedAt).toLocaleDateString(),startedAt:O.startedAt,polls:[]}),x[K].polls.push(O)}else T.push(O)}),Object.values(x).forEach(O=>{O.polls.sort((K,tt)=>(K.setPosition??0)-(tt.setPosition??0))}),[...Object.values(x).map(O=>({type:"set",...O})),...T.map(O=>({type:"poll",...O}))].sort((O,K)=>(K.startedAt||0)-(O.startedAt||0))}if(!e)return c.jsx("div",{style:F.center,children:c.jsxs("div",{style:F.loginCard,className:"fade-up",children:[c.jsxs("div",{style:F.loginLogo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsx("h2",{style:{fontSize:"1.4rem",marginBottom:"0.25rem"},children:"Poll History"}),c.jsx("p",{style:{color:"var(--muted)",marginBottom:"1.5rem",fontSize:"0.9rem"},children:"Enter the teacher password to view history and attendance."}),c.jsxs("form",{onSubmit:q,style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[c.jsx("input",{className:"input",type:"password",placeholder:"Teacher password",value:r,onChange:y=>{i(y.target.value),o("")},autoFocus:!0,style:{textAlign:"center"}}),s&&c.jsx("span",{style:F.err,children:s}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{justifyContent:"center",padding:"0.75rem"},children:"View History β†’"})]}),c.jsx("button",{style:F.backLink,onClick:()=>t("/"),children:"← Back"})]})});const U=R(l);return c.jsxs("div",{style:F.page,children:[c.jsxs("header",{style:F.header,children:[c.jsx("button",{style:F.back,onClick:()=>t("/"),children:"← Back"}),c.jsx("span",{style:F.title,children:"Poll History"}),c.jsxs("div",{style:F.tabs,children:[c.jsx("button",{style:{...F.tab,...d==="polls"?F.tabActive:{}},onClick:()=>f("polls"),children:"Polls"}),c.jsx("button",{style:{...F.tab,...d==="attendance"?F.tabActive:{}},onClick:()=>f("attendance"),children:"Attendance"})]})]}),c.jsxs("main",{style:F.main,children:[d==="polls"&&c.jsxs("div",{className:"fade-up",children:[U.length===0&&c.jsx("div",{style:F.empty,children:"No polls yet. Run your first one in class!"}),U.map(y=>{if(y.type==="set"){const x=_.has(y.key),T=y.polls.reduce((O,K)=>O+Object.keys(K.responses||{}).length,0);return c.jsxs("div",{style:F.setGroup,children:[c.jsxs("div",{style:F.setGroupHeaderRow,children:[c.jsxs("button",{style:F.setGroupHeaderBtn,onClick:()=>Y(y.key),children:[c.jsx("span",{style:F.triangle,children:x?"β–Ό":"β–Ά"}),c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{style:F.setGroupName,children:["πŸ“š ",y.setName]}),c.jsxs("div",{style:F.setGroupMeta,children:[y.date," Β· ",y.polls.length," polls Β· ",T," total responses"]})]})]}),c.jsxs("div",{style:{display:"flex",gap:"0.4rem",alignItems:"center"},children:[c.jsx("button",{style:{...F.exportBtn,...b[y.key]?F.exportBtnSuccess:{}},onClick:()=>{Be(y.setName,y.polls),et(y.key)},children:b[y.key]?"βœ“ Downloading":"⬇ Session CSV"}),m!==y.key?c.jsx("button",{style:F.deleteBtn,onClick:()=>S(y.key),title:"Delete this session",children:"πŸ—‘"}):c.jsxs("div",{style:F.confirmRow,children:[c.jsxs("span",{style:F.confirmText,children:["Delete all ",y.polls.length," polls?"]}),c.jsx("button",{className:"btn btn-primary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem",background:"#dc2626"},onClick:()=>pe(y.key,y.polls),children:"Yes"}),c.jsx("button",{className:"btn btn-secondary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem"},onClick:()=>S(null),children:"Cancel"})]})]})]}),x&&c.jsx("div",{style:F.setGroupPolls,children:y.polls.map(O=>c.jsx(qp,{poll:O,expanded:v.has(O.id),viewMode:I[O.id]||"summary",confirmDelete:g,copyFeedback:b[O.id],onToggle:()=>D(O.id),onDelete:()=>z(O.id),onConfirmDelete:()=>p(O.id),onCancelDelete:()=>p(null),onSetView:K=>X(O.id,K),onDownload:()=>Ee(O),onDownloadFeedback:()=>et(O.id),positionLabel:`${(O.setPosition??0)+1}.`},O.id))})]},y.key)}return c.jsx(qp,{poll:y,expanded:v.has(y.id),viewMode:I[y.id]||"summary",confirmDelete:g,copyFeedback:b[y.id],onToggle:()=>D(y.id),onDelete:()=>z(y.id),onConfirmDelete:()=>p(y.id),onCancelDelete:()=>p(null),onSetView:x=>X(y.id,x),onDownload:()=>Ee(y),onDownloadFeedback:()=>et(y.id)},y.id)})]}),d==="attendance"&&c.jsxs("div",{className:"fade-up",children:[Object.keys(u).length===0&&c.jsx("div",{style:F.empty,children:"No attendance records yet."}),Object.entries(u).sort(([y],[x])=>x.localeCompare(y)).map(([y,x])=>c.jsxs("div",{style:F.pollCard,children:[c.jsx("div",{style:F.pollHeaderRow,children:c.jsxs("div",{style:{padding:"0.25rem 0"},children:[c.jsx("div",{style:F.pollQ,children:y}),c.jsxs("div",{style:F.pollMeta,children:[x.length," student",x.length!==1?"s":""]})]})}),c.jsx("div",{style:{padding:"0 1rem 1rem",display:"flex",flexWrap:"wrap",gap:"0.4rem"},children:x.map(T=>c.jsx("span",{style:F.chip,children:T},T))})]},y))]})]})]})}function qp({poll:t,expanded:e,viewMode:n,confirmDelete:r,copyFeedback:i,onToggle:s,onDelete:o,onConfirmDelete:l,onCancelDelete:a,onSetView:u,onDownload:h,onDownloadFeedback:d,positionLabel:f}){const v=t.responses||{},w=Object.keys(v).length,_=r===t.id,E=t.correctIndex!=null,g={};return t.options.forEach((p,m)=>{g[m]=[]}),Object.entries(v).forEach(([p,m])=>{g[m]!==void 0?g[m].push(p):g[m]=[p]}),c.jsxs("div",{style:F.pollCard,children:[c.jsxs("div",{style:F.pollHeaderRow,children:[c.jsxs("button",{style:F.pollHeaderBtn,onClick:s,children:[c.jsx("span",{style:F.triangle,children:e?"β–Ό":"β–Ά"}),c.jsxs("div",{children:[c.jsxs("div",{style:F.pollQ,children:[f&&c.jsxs("span",{style:F.posLabel,children:[f," "]}),t.question]}),c.jsxs("div",{style:F.pollMeta,children:[new Date(t.startedAt).toLocaleString()," Β· ",w," response",w!==1?"s":""]})]})]}),c.jsxs("div",{style:{display:"flex",gap:"0.4rem",alignItems:"center"},children:[!_&&c.jsx("button",{style:{...F.exportBtn,...i?F.exportBtnSuccess:{}},onClick:()=>{h(),d()},children:i?"βœ“ Downloading":"⬇ CSV"}),_?c.jsxs("div",{style:F.confirmRow,children:[c.jsx("span",{style:F.confirmText,children:"Delete?"}),c.jsx("button",{className:"btn btn-primary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem",background:"#dc2626"},onClick:o,children:"Yes"}),c.jsx("button",{className:"btn btn-secondary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem"},onClick:a,children:"Cancel"})]}):c.jsx("button",{style:F.deleteBtn,onClick:l,title:"Delete",children:"πŸ—‘"})]})]}),e&&c.jsxs("div",{style:F.pollDetails,children:[c.jsxs("div",{style:F.viewTabs,children:[c.jsx("button",{style:{...F.viewTab,...n==="summary"?F.viewTabActive:{}},onClick:()=>u("summary"),children:"Summary"}),c.jsx("button",{style:{...F.viewTab,...n==="students"?F.viewTabActive:{}},onClick:()=>u("students"),children:"By student"})]}),n==="summary"&&c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.6rem"},children:t.options.map((p,m)=>{const S=Object.values(v).filter(b=>b===m).length,I=w>0?Math.round(S/w*100):0,P=E&&t.correctIndex===m;return c.jsxs("div",{style:F.histOpt,children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:4},children:[c.jsxs("span",{style:{fontWeight:P?600:400,color:P?"var(--success)":"inherit"},children:[String.fromCharCode(65+m),". ",p," ",P&&"βœ“"]}),c.jsxs("span",{style:{color:"var(--muted)",fontSize:"0.85rem"},children:[S," (",I,"%)"]})]}),c.jsx("div",{style:F.barBg,children:c.jsx("div",{style:{...F.barFill,width:`${I}%`,background:P?"var(--success)":"var(--accent2)"}})})]},m)})}),n==="students"&&c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[t.options.map((p,m)=>{const S=g[m]||[],I=E&&t.correctIndex===m;return S.length===0?null:c.jsxs("div",{style:F.answerGroup,children:[c.jsxs("div",{style:{...F.answerGroupHeader,...I?F.answerGroupCorrect:{}},children:[c.jsxs("span",{style:{fontWeight:600},children:[String.fromCharCode(65+m),". ",p]}),I&&c.jsx("span",{style:F.correctTag,children:"βœ“ correct"}),c.jsxs("span",{style:F.answerCount,children:[S.length," student",S.length!==1?"s":""]})]}),c.jsx("div",{style:F.studentNames,children:S.sort().map(P=>c.jsx("span",{style:F.chip,children:P},P))})]},m)}),w===0&&c.jsx("div",{style:{color:"var(--muted)",fontSize:"0.9rem"},children:"No responses."})]})]})]})}const F={center:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"var(--paper)"},loginCard:{background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"2.5rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},loginLogo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",marginBottom:"1.5rem",display:"block"},err:{color:"var(--accent)",fontSize:"0.85rem"},backLink:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",marginTop:"1rem",fontSize:"0.85rem",display:"block",textAlign:"center"},page:{minHeight:"100vh",background:"var(--paper)"},header:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",background:"white",display:"flex",alignItems:"center",gap:"1rem",flexWrap:"wrap"},back:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"0.9rem"},title:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.2rem",flex:1},tabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:8,padding:"0.25rem"},tab:{background:"none",border:"none",padding:"0.35rem 0.85rem",borderRadius:6,cursor:"pointer",fontSize:"0.9rem",color:"var(--muted)",transition:"all 0.15s"},tabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},main:{maxWidth:760,margin:"0 auto",padding:"1.5rem 1rem"},empty:{textAlign:"center",color:"var(--muted)",padding:"3rem",fontSize:"0.95rem"},setGroup:{background:"white",borderRadius:12,border:"1.5px solid var(--accent2)",marginBottom:"0.75rem",overflow:"hidden"},setGroupHeaderRow:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.85rem 1rem",borderBottom:"1px solid var(--cream)"},setGroupHeaderBtn:{display:"flex",alignItems:"center",gap:"0.75rem",background:"none",border:"none",cursor:"pointer",textAlign:"left",flex:1},setGroupName:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"0.95rem"},setGroupMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},setGroupPolls:{padding:"0.5rem 0.75rem",display:"flex",flexDirection:"column",gap:"0.4rem"},triangle:{fontSize:"0.7rem",color:"var(--muted)",flexShrink:0},exportBtn:{background:"var(--cream)",border:"1px solid var(--border)",borderRadius:6,padding:"0.3rem 0.65rem",fontSize:"0.78rem",cursor:"pointer",color:"var(--ink)",whiteSpace:"nowrap",transition:"all 0.15s",flexShrink:0},exportBtnSuccess:{background:"#dcfce7",borderColor:"var(--success)",color:"var(--success)"},pollCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",marginBottom:"0.75rem",overflow:"hidden"},pollHeaderRow:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.75rem 1rem"},pollHeaderBtn:{display:"flex",alignItems:"center",gap:"0.6rem",background:"none",border:"none",cursor:"pointer",textAlign:"left",flex:1,padding:"0.25rem 0"},posLabel:{color:"var(--muted)",fontWeight:400},pollQ:{fontFamily:"var(--font-display)",fontWeight:600,fontSize:"0.95rem"},pollMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},deleteBtn:{background:"none",border:"none",cursor:"pointer",fontSize:"1.1rem",padding:"0.25rem 0.4rem",borderRadius:6,opacity:.5},confirmRow:{display:"flex",alignItems:"center",gap:"0.4rem"},confirmText:{fontSize:"0.82rem",color:"var(--muted)",whiteSpace:"nowrap"},pollDetails:{padding:"0.75rem 1rem 1rem",borderTop:"1px solid var(--border)"},viewTabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:6,padding:"0.2rem",marginBottom:"0.75rem",width:"fit-content"},viewTab:{background:"none",border:"none",padding:"0.25rem 0.65rem",borderRadius:4,cursor:"pointer",fontSize:"0.82rem",color:"var(--muted)"},viewTabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 2px rgba(0,0,0,0.08)"},histOpt:{marginBottom:"0.6rem"},barBg:{height:6,borderRadius:3,background:"var(--cream)",overflow:"hidden"},barFill:{height:"100%",borderRadius:3,transition:"width 0.3s"},answerGroup:{borderRadius:8,border:"1px solid var(--border)",overflow:"hidden"},answerGroupHeader:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",background:"var(--cream)",flexWrap:"wrap"},answerGroupCorrect:{background:"#dcfce7"},correctTag:{fontSize:"0.75rem",color:"var(--success)",fontWeight:600,background:"#bbf7d0",borderRadius:4,padding:"0.1rem 0.4rem"},answerCount:{marginLeft:"auto",fontSize:"0.78rem",color:"var(--muted)"},studentNames:{padding:"0.5rem 0.75rem",display:"flex",flexWrap:"wrap",gap:"0.35rem"},chip:{background:"var(--cream)",borderRadius:4,padding:"0.2rem 0.5rem",fontSize:"0.78rem",color:"var(--ink)"}};function Pb(){return c.jsx(dC,{basename:"/classroom-polling",children:c.jsxs(aC,{children:[c.jsx(fn,{path:"/",element:c.jsx(fC,{})}),c.jsx(fn,{path:"/instructor",element:c.jsx(mb,{})}),c.jsx(fn,{path:"/student",element:c.jsx(vb,{})}),c.jsx(fn,{path:"/pollsets/:id",element:c.jsx(Sb,{})}),c.jsx(fn,{path:"/pollsets",element:c.jsx(Cb,{})}),c.jsx(fn,{path:"/history",element:c.jsx(bb,{})}),c.jsx(fn,{path:"*",element:c.jsx(oC,{to:"/"})})]})})}Za.createRoot(document.getElementById("root")).render(c.jsx(im.StrictMode,{children:c.jsx(Pb,{})})); diff --git a/dist/index.html b/dist/index.html index ea9ae57..4c2d7ef 100644 --- a/dist/index.html +++ b/dist/index.html @@ -8,7 +8,7 @@ - + From 07540ea68ab67cbbc04ecb909e443cbb93b6434f Mon Sep 17 00:00:00 2001 From: Jody Date: Sun, 14 Jun 2026 16:24:47 -0600 Subject: [PATCH 2/4] Replace instances of "teacher" with "instructor" --- README.md | 18 +++++++++--------- node_modules/.vite/deps/_metadata.json | 18 +++++++++--------- src/App.jsx | 4 ++-- .../{TeacherPage.jsx => InstructorPage.jsx} | 4 ++-- 4 files changed, 22 insertions(+), 22 deletions(-) rename src/pages/{TeacherPage.jsx => InstructorPage.jsx} (99%) diff --git a/README.md b/README.md index 893237f..9b85199 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ All data stays in your own Firebase project. - View poll history and attendance, grouped by poll set and session - CSV export of poll results (per-poll and per-session) - Delete individual polls from history -- Password-protected teacher and history access +- Password-protected instructor and history access ### For students - Join with just a name β€” no account needed @@ -137,7 +137,7 @@ Copy the example file and fill in your values: cp .env.example .env.local ``` -Edit `.env.local` with your Firebase config values and a teacher password of your choice: +Edit `.env.local` with your Firebase config values and an instructor password of your choice: ``` VITE_FIREBASE_API_KEY=your_api_key @@ -148,7 +148,7 @@ VITE_FIREBASE_STORAGE_BUCKET=your_project.firebasestorage.app VITE_FIREBASE_MESSAGING_SENDER_ID=your_sender_id VITE_FIREBASE_APP_ID=your_app_id -VITE_TEACHER_PASSWORD=your_password_here +VITE_INSTRUCTOR_PASSWORD=your_password_here ``` **Never commit `.env.local` to git.** It is already listed in `.gitignore`. @@ -166,7 +166,7 @@ npm run dev ``` Open [http://localhost:5173/classroom-polling/](http://localhost:5173/classroom-polling/). -Open two browser tabs β€” one as teacher, one as student β€” to verify everything works. +Open two browser tabs β€” one as instructor, one as student β€” to verify everything works. ### Step 9 β€” Set your repo name in vite.config.js @@ -223,7 +223,7 @@ git merge upstream/main ### Running a poll -1. Open the app β†’ **I'm the Teacher** β†’ enter your password +1. Open the app β†’ **I'm the Instructor** β†’ enter your password 2. Click **New Poll** β†’ enter question and options β†’ click **Start Poll** 3. Share your app URL with students β€” they click **I'm a Student**, enter their name, and wait 4. Students see the poll instantly; results update live on your dashboard @@ -239,7 +239,7 @@ git merge upstream/main ### Viewing history and attendance -1. Click **History** β†’ enter teacher password +1. Click **History** β†’ enter instructor password 2. **Polls tab**: past polls grouped by set, expandable with per-option results 3. **Attendance tab**: students who joined, grouped by date @@ -247,7 +247,7 @@ git merge upstream/main | File | What to change | |------|---------------| -| `.env.local` | Teacher password, Firebase config | +| `.env.local` | Instructor password, Firebase config | | `firebase-rules.json` | Database security rules | | `vite.config.js` | Repository name for GitHub Pages base path | | `src/index.css` | Colors, fonts, visual design | @@ -264,7 +264,7 @@ classroom-polling/ β”‚ β”‚ └── csvExport.js CSV export utilities β”‚ β”œβ”€β”€ pages/ β”‚ β”‚ β”œβ”€β”€ RoleSelector.jsx Landing page -β”‚ β”‚ β”œβ”€β”€ TeacherPage.jsx Teacher dashboard +β”‚ β”‚ β”œβ”€β”€ InstructorPage.jsx Instructor dashboard β”‚ β”‚ β”œβ”€β”€ StudentPage.jsx Student poll experience β”‚ β”‚ β”œβ”€β”€ PollHistory.jsx History and attendance β”‚ β”‚ β”œβ”€β”€ PollSets.jsx Poll set list and creation @@ -290,7 +290,7 @@ The Firebase Spark (free) plan is sufficient for typical classroom use: ## Known limitations -- Teacher password is a single shared secret; not suitable for multiple instructors sharing one instance +- Instructor password is a single shared secret; not suitable for multiple instructors sharing one instance - Code formatting in questions is plain text only (markdown support planned) - Student names are self-reported and not authenticated diff --git a/node_modules/.vite/deps/_metadata.json b/node_modules/.vite/deps/_metadata.json index 4495baf..3c979f8 100644 --- a/node_modules/.vite/deps/_metadata.json +++ b/node_modules/.vite/deps/_metadata.json @@ -7,55 +7,55 @@ "react": { "src": "../../react/index.js", "file": "react.js", - "fileHash": "4c5b97b1", + "fileHash": "62626146", "needsInterop": true }, "react-dom": { "src": "../../react-dom/index.js", "file": "react-dom.js", - "fileHash": "a800d98c", + "fileHash": "e205e623", "needsInterop": true }, "react/jsx-dev-runtime": { "src": "../../react/jsx-dev-runtime.js", "file": "react_jsx-dev-runtime.js", - "fileHash": "49403d8d", + "fileHash": "cd7f1551", "needsInterop": true }, "react/jsx-runtime": { "src": "../../react/jsx-runtime.js", "file": "react_jsx-runtime.js", - "fileHash": "8319c78f", + "fileHash": "d524e7c0", "needsInterop": true }, "firebase/app": { "src": "../../firebase/app/dist/esm/index.esm.js", "file": "firebase_app.js", - "fileHash": "06daed78", + "fileHash": "263b99ae", "needsInterop": false }, "firebase/auth": { "src": "../../firebase/auth/dist/esm/index.esm.js", "file": "firebase_auth.js", - "fileHash": "bb5fb4ae", + "fileHash": "4fed8dd8", "needsInterop": false }, "firebase/database": { "src": "../../firebase/database/dist/esm/index.esm.js", "file": "firebase_database.js", - "fileHash": "ba620094", + "fileHash": "9dbf7323", "needsInterop": false }, "react-dom/client": { "src": "../../react-dom/client.js", "file": "react-dom_client.js", - "fileHash": "e33ee8df", + "fileHash": "50817ba9", "needsInterop": true }, "react-router-dom": { "src": "../../react-router-dom/dist/index.js", "file": "react-router-dom.js", - "fileHash": "1273c6ff", + "fileHash": "f2af17c3", "needsInterop": false } }, diff --git a/src/App.jsx b/src/App.jsx index 2ccf6c3..afdcb5b 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -10,7 +10,7 @@ */ import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'; import RoleSelector from './pages/RoleSelector'; -import TeacherPage from './pages/TeacherPage'; +import InstructorPage from './pages/InstructorPage'; import StudentPage from './pages/StudentPage'; import PollSetDetail from './pages/PollSetDetail'; import PollSets from './pages/PollSets'; @@ -21,7 +21,7 @@ export default function App() { } /> - } /> + } /> } /> } /> } /> diff --git a/src/pages/TeacherPage.jsx b/src/pages/InstructorPage.jsx similarity index 99% rename from src/pages/TeacherPage.jsx rename to src/pages/InstructorPage.jsx index 8c66680..43a9d5f 100644 --- a/src/pages/TeacherPage.jsx +++ b/src/pages/InstructorPage.jsx @@ -28,7 +28,7 @@ const CORRECT_OPTIONS = [ { value: 'never', label: 'Never' }, ]; -export default function TeacherPage() { +export default function InstructorPage() { const navigate = useNavigate(); const [students, setStudents] = useState([]); const [activePoll, setActivePoll] = useState(null); @@ -48,7 +48,7 @@ export default function TeacherPage() { const [correctPolicy, setCorrectPolicy] = useState('with_results'); useEffect(() => { - if (localStorage.getItem("role") !== 'teacher') navigate('/'); + if (localStorage.getItem("role") !== 'instructor') navigate('/'); }, []); useEffect(() => { From 55e33dbb7b971d79473354f78e610745c4a088be Mon Sep 17 00:00:00 2001 From: Jody Date: Sun, 14 Jun 2026 16:44:02 -0600 Subject: [PATCH 3/4] Completed changes from teacher to instructor --- dist/.DS_Store | Bin 6148 -> 0 bytes dist/assets/index-HXjiAoNO.js | 2747 --------------------------------- dist/index.html | 2 +- src/pages/PollHistory.jsx | 8 +- src/pages/PollSetDetail.jsx | 4 +- src/pages/PollSets.jsx | 4 +- src/pages/RoleSelector.jsx | 24 +- src/pages/StudentPage.jsx | 12 +- 8 files changed, 27 insertions(+), 2774 deletions(-) delete mode 100644 dist/.DS_Store delete mode 100644 dist/assets/index-HXjiAoNO.js diff --git a/dist/.DS_Store b/dist/.DS_Store deleted file mode 100644 index c133dc5bbdbf6cadd9693a5e0dacb9c39cd34757..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKO-@2F5S~$Dnz&)92k)OAz}z7!>m}g4osy50LnGG2z2QsBqtgs!>kAo zgf$hYscbCf8+q`gjI_k#~PMj2db_Se*E(6!P?92H-#$Tq| zSI85sBhS6(lT diff --git a/dist/assets/index-HXjiAoNO.js b/dist/assets/index-HXjiAoNO.js deleted file mode 100644 index 5dba374..0000000 --- a/dist/assets/index-HXjiAoNO.js +++ /dev/null @@ -1,2747 +0,0 @@ -function B_(t,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();function W_(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Kp={exports:{}},Nl={},Qp={exports:{}},G={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var As=Symbol.for("react.element"),$_=Symbol.for("react.portal"),V_=Symbol.for("react.fragment"),H_=Symbol.for("react.strict_mode"),G_=Symbol.for("react.profiler"),q_=Symbol.for("react.provider"),K_=Symbol.for("react.context"),Q_=Symbol.for("react.forward_ref"),Y_=Symbol.for("react.suspense"),J_=Symbol.for("react.memo"),X_=Symbol.for("react.lazy"),hh=Symbol.iterator;function Z_(t){return t===null||typeof t!="object"?null:(t=hh&&t[hh]||t["@@iterator"],typeof t=="function"?t:null)}var Yp={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Jp=Object.assign,Xp={};function fi(t,e,n){this.props=t,this.context=e,this.refs=Xp,this.updater=n||Yp}fi.prototype.isReactComponent={};fi.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};fi.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Zp(){}Zp.prototype=fi.prototype;function Sc(t,e,n){this.props=t,this.context=e,this.refs=Xp,this.updater=n||Yp}var Cc=Sc.prototype=new Zp;Cc.constructor=Sc;Jp(Cc,fi.prototype);Cc.isPureReactComponent=!0;var fh=Array.isArray,em=Object.prototype.hasOwnProperty,Ec={current:null},tm={key:!0,ref:!0,__self:!0,__source:!0};function nm(t,e,n){var r,i={},s=null,o=null;if(e!=null)for(r in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(s=""+e.key),e)em.call(e,r)&&!tm.hasOwnProperty(r)&&(i[r]=e[r]);var l=arguments.length-2;if(l===1)i.children=n;else if(1>>1,T=R[x];if(0>>1;xi(tt,y))Gei(L,tt)?(R[x]=L,R[Ge]=y,x=Ge):(R[x]=tt,R[K]=y,x=K);else if(Gei(L,y))R[x]=L,R[Ge]=y,x=Ge;else break e}}return U}function i(R,U){var y=R.sortIndex-U.sortIndex;return y!==0?y:R.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var a=[],u=[],h=1,d=null,f=3,v=!1,w=!1,_=!1,E=typeof setTimeout=="function"?setTimeout:null,g=typeof clearTimeout=="function"?clearTimeout:null,p=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function m(R){for(var U=n(u);U!==null;){if(U.callback===null)r(u);else if(U.startTime<=R)r(u),U.sortIndex=U.expirationTime,e(a,U);else break;U=n(u)}}function S(R){if(_=!1,m(R),!w)if(n(a)!==null)w=!0,Ee(I);else{var U=n(u);U!==null&&Be(S,U.startTime-R)}}function I(R,U){w=!1,_&&(_=!1,g(A),A=-1),v=!0;var y=f;try{for(m(U),d=n(a);d!==null&&(!(d.expirationTime>U)||R&&!pe());){var x=d.callback;if(typeof x=="function"){d.callback=null,f=d.priorityLevel;var T=x(d.expirationTime<=U);U=t.unstable_now(),typeof T=="function"?d.callback=T:d===n(a)&&r(a),m(U)}else r(a);d=n(a)}if(d!==null)var O=!0;else{var K=n(u);K!==null&&Be(S,K.startTime-U),O=!1}return O}finally{d=null,f=y,v=!1}}var P=!1,b=null,A=-1,q=5,z=-1;function pe(){return!(t.unstable_now()-zR||125x?(R.sortIndex=y,e(u,R),n(a)===null&&R===n(u)&&(_?(g(A),A=-1):_=!0,Be(S,y-x))):(R.sortIndex=T,e(a,R),w||v||(w=!0,Ee(I))),R},t.unstable_shouldYield=pe,t.unstable_wrapCallback=function(R){var U=f;return function(){var y=f;f=U;try{return R.apply(this,arguments)}finally{f=y}}}})(am);lm.exports=am;var d0=lm.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var h0=C,ht=d0;function k(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),eu=Object.prototype.hasOwnProperty,f0=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,mh={},gh={};function p0(t){return eu.call(gh,t)?!0:eu.call(mh,t)?!1:f0.test(t)?gh[t]=!0:(mh[t]=!0,!1)}function m0(t,e,n,r){if(n!==null&&n.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function g0(t,e,n,r){if(e===null||typeof e>"u"||m0(t,e,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function Ze(t,e,n,r,i,s,o){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=t,this.type=e,this.sanitizeURL=s,this.removeEmptyString=o}var Ue={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){Ue[t]=new Ze(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];Ue[e]=new Ze(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){Ue[t]=new Ze(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){Ue[t]=new Ze(t,2,!1,t,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(t){Ue[t]=new Ze(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){Ue[t]=new Ze(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){Ue[t]=new Ze(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){Ue[t]=new Ze(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){Ue[t]=new Ze(t,5,!1,t.toLowerCase(),null,!1,!1)});var Ic=/[\-:]([a-z])/g;function kc(t){return t[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(t){var e=t.replace(Ic,kc);Ue[e]=new Ze(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(Ic,kc);Ue[e]=new Ze(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(Ic,kc);Ue[e]=new Ze(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){Ue[t]=new Ze(t,1,!1,t.toLowerCase(),null,!1,!1)});Ue.xlinkHref=new Ze("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){Ue[t]=new Ze(t,1,!1,t.toLowerCase(),null,!0,!0)});function Tc(t,e,n,r){var i=Ue.hasOwnProperty(e)?Ue[e]:null;(i!==null?i.type!==0:r||!(2l||i[o]!==s[l]){var a=` -`+i[o].replace(" at new "," at ");return t.displayName&&a.includes("")&&(a=a.replace("",t.displayName)),a}while(1<=o&&0<=l);break}}}finally{pa=!1,Error.prepareStackTrace=n}return(t=t?t.displayName||t.name:"")?Mi(t):""}function v0(t){switch(t.tag){case 5:return Mi(t.type);case 16:return Mi("Lazy");case 13:return Mi("Suspense");case 19:return Mi("SuspenseList");case 0:case 2:case 15:return t=ma(t.type,!1),t;case 11:return t=ma(t.type.render,!1),t;case 1:return t=ma(t.type,!0),t;default:return""}}function iu(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case Pr:return"Fragment";case br:return"Portal";case tu:return"Profiler";case bc:return"StrictMode";case nu:return"Suspense";case ru:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case dm:return(t.displayName||"Context")+".Consumer";case cm:return(t._context.displayName||"Context")+".Provider";case Pc:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Nc:return e=t.displayName||null,e!==null?e:iu(t.type)||"Memo";case pn:e=t._payload,t=t._init;try{return iu(t(e))}catch{}}return null}function y0(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return iu(e);case 8:return e===bc?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function zn(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function fm(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function _0(t){var e=fm(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),r=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return i.call(this)},set:function(o){r=""+o,s.call(this,o)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function Xs(t){t._valueTracker||(t._valueTracker=_0(t))}function pm(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=fm(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function Mo(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function su(t,e){var n=e.checked;return ve({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??t._wrapperState.initialChecked})}function yh(t,e){var n=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;n=zn(e.value!=null?e.value:n),t._wrapperState={initialChecked:r,initialValue:n,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function mm(t,e){e=e.checked,e!=null&&Tc(t,"checked",e,!1)}function ou(t,e){mm(t,e);var n=zn(e.value),r=e.type;if(n!=null)r==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+n):t.value!==""+n&&(t.value=""+n);else if(r==="submit"||r==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?lu(t,e.type,n):e.hasOwnProperty("defaultValue")&&lu(t,e.type,zn(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function _h(t,e,n){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var r=e.type;if(!(r!=="submit"&&r!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,n||e===t.value||(t.value=e),t.defaultValue=e}n=t.name,n!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,n!==""&&(t.name=n)}function lu(t,e,n){(e!=="number"||Mo(t.ownerDocument)!==t)&&(n==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+n&&(t.defaultValue=""+n))}var ji=Array.isArray;function Wr(t,e,n,r){if(t=t.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=Zs.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function ns(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var zi={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},w0=["Webkit","ms","Moz","O"];Object.keys(zi).forEach(function(t){w0.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),zi[e]=zi[t]})});function _m(t,e,n){return e==null||typeof e=="boolean"||e===""?"":n||typeof e!="number"||e===0||zi.hasOwnProperty(t)&&zi[t]?(""+e).trim():e+"px"}function wm(t,e){t=t.style;for(var n in e)if(e.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=_m(n,e[n],r);n==="float"&&(n="cssFloat"),r?t.setProperty(n,i):t[n]=i}}var S0=ve({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function cu(t,e){if(e){if(S0[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(k(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(k(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(k(61))}if(e.style!=null&&typeof e.style!="object")throw Error(k(62))}}function du(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var hu=null;function Rc(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var fu=null,$r=null,Vr=null;function Ch(t){if(t=Ls(t)){if(typeof fu!="function")throw Error(k(280));var e=t.stateNode;e&&(e=Ll(e),fu(t.stateNode,t.type,e))}}function Sm(t){$r?Vr?Vr.push(t):Vr=[t]:$r=t}function Cm(){if($r){var t=$r,e=Vr;if(Vr=$r=null,Ch(t),e)for(t=0;t>>=0,t===0?32:31-(A0(t)/O0|0)|0}var eo=64,to=4194304;function Fi(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function zo(t,e){var n=t.pendingLanes;if(n===0)return 0;var r=0,i=t.suspendedLanes,s=t.pingedLanes,o=n&268435455;if(o!==0){var l=o&~i;l!==0?r=Fi(l):(s&=o,s!==0&&(r=Fi(s)))}else o=n&~i,o!==0?r=Fi(o):s!==0&&(r=Fi(s));if(r===0)return 0;if(e!==0&&e!==r&&!(e&i)&&(i=r&-r,s=e&-e,i>=s||i===16&&(s&4194240)!==0))return e;if(r&4&&(r|=n&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=r;0n;n++)e.push(t);return e}function Os(t,e,n){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-Nt(e),t[e]=n}function j0(t,e){var n=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var r=t.eventTimes;for(t=t.expirationTimes;0=Wi),Rh=" ",Ah=!1;function Wm(t,e){switch(t){case"keyup":return dw.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function $m(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Nr=!1;function fw(t,e){switch(t){case"compositionend":return $m(e);case"keypress":return e.which!==32?null:(Ah=!0,Rh);case"textInput":return t=e.data,t===Rh&&Ah?null:t;default:return null}}function pw(t,e){if(Nr)return t==="compositionend"||!Uc&&Wm(t,e)?(t=zm(),wo=Mc=Cn=null,Nr=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:n,offset:e-t};t=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Mh(n)}}function qm(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?qm(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Km(){for(var t=window,e=Mo();e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=Mo(t.document)}return e}function zc(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function Ew(t){var e=Km(),n=t.focusedElem,r=t.selectionRange;if(e!==n&&n&&n.ownerDocument&&qm(n.ownerDocument.documentElement,n)){if(r!==null&&zc(n)){if(e=r.start,t=r.end,t===void 0&&(t=e),"selectionStart"in n)n.selectionStart=e,n.selectionEnd=Math.min(t,n.value.length);else if(t=(e=n.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=r.end===void 0?s:Math.min(r.end,i),!t.extend&&s>r&&(i=r,r=s,s=i),i=jh(n,s);var o=jh(n,r);i&&o&&(t.rangeCount!==1||t.anchorNode!==i.node||t.anchorOffset!==i.offset||t.focusNode!==o.node||t.focusOffset!==o.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),t.removeAllRanges(),s>r?(t.addRange(e),t.extend(o.node,o.offset)):(e.setEnd(o.node,o.offset),t.addRange(e)))}}for(e=[],t=n;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Rr=null,_u=null,Vi=null,wu=!1;function Fh(t,e,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;wu||Rr==null||Rr!==Mo(r)||(r=Rr,"selectionStart"in r&&zc(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Vi&&as(Vi,r)||(Vi=r,r=$o(_u,"onSelect"),0Dr||(t.current=ku[Dr],ku[Dr]=null,Dr--)}function ce(t,e){Dr++,ku[Dr]=t.current,t.current=e}var Bn={},He=qn(Bn),ot=qn(!1),ar=Bn;function ei(t,e){var n=t.type.contextTypes;if(!n)return Bn;var r=t.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in n)i[s]=e[s];return r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=i),i}function lt(t){return t=t.childContextTypes,t!=null}function Ho(){he(ot),he(He)}function Hh(t,e,n){if(He.current!==Bn)throw Error(k(168));ce(He,e),ce(ot,n)}function rg(t,e,n){var r=t.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in e))throw Error(k(108,y0(t)||"Unknown",i));return ve({},n,r)}function Go(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||Bn,ar=He.current,ce(He,t),ce(ot,ot.current),!0}function Gh(t,e,n){var r=t.stateNode;if(!r)throw Error(k(169));n?(t=rg(t,e,ar),r.__reactInternalMemoizedMergedChildContext=t,he(ot),he(He),ce(He,t)):he(ot),ce(ot,n)}var $t=null,Ml=!1,Pa=!1;function ig(t){$t===null?$t=[t]:$t.push(t)}function Lw(t){Ml=!0,ig(t)}function Kn(){if(!Pa&&$t!==null){Pa=!0;var t=0,e=ie;try{var n=$t;for(ie=1;t>=o,i-=o,Vt=1<<32-Nt(e)+i|n<A?(q=b,b=null):q=b.sibling;var z=f(g,b,m[A],S);if(z===null){b===null&&(b=q);break}t&&b&&z.alternate===null&&e(g,b),p=s(z,p,A),P===null?I=z:P.sibling=z,P=z,b=q}if(A===m.length)return n(g,b),fe&&Jn(g,A),I;if(b===null){for(;AA?(q=b,b=null):q=b.sibling;var pe=f(g,b,z.value,S);if(pe===null){b===null&&(b=q);break}t&&b&&pe.alternate===null&&e(g,b),p=s(pe,p,A),P===null?I=pe:P.sibling=pe,P=pe,b=q}if(z.done)return n(g,b),fe&&Jn(g,A),I;if(b===null){for(;!z.done;A++,z=m.next())z=d(g,z.value,S),z!==null&&(p=s(z,p,A),P===null?I=z:P.sibling=z,P=z);return fe&&Jn(g,A),I}for(b=r(g,b);!z.done;A++,z=m.next())z=v(b,g,A,z.value,S),z!==null&&(t&&z.alternate!==null&&b.delete(z.key===null?A:z.key),p=s(z,p,A),P===null?I=z:P.sibling=z,P=z);return t&&b.forEach(function(D){return e(g,D)}),fe&&Jn(g,A),I}function E(g,p,m,S){if(typeof m=="object"&&m!==null&&m.type===Pr&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case Js:e:{for(var I=m.key,P=p;P!==null;){if(P.key===I){if(I=m.type,I===Pr){if(P.tag===7){n(g,P.sibling),p=i(P,m.props.children),p.return=g,g=p;break e}}else if(P.elementType===I||typeof I=="object"&&I!==null&&I.$$typeof===pn&&Qh(I)===P.type){n(g,P.sibling),p=i(P,m.props),p.ref=Pi(g,P,m),p.return=g,g=p;break e}n(g,P);break}else e(g,P);P=P.sibling}m.type===Pr?(p=or(m.props.children,g.mode,S,m.key),p.return=g,g=p):(S=bo(m.type,m.key,m.props,null,g.mode,S),S.ref=Pi(g,p,m),S.return=g,g=S)}return o(g);case br:e:{for(P=m.key;p!==null;){if(p.key===P)if(p.tag===4&&p.stateNode.containerInfo===m.containerInfo&&p.stateNode.implementation===m.implementation){n(g,p.sibling),p=i(p,m.children||[]),p.return=g,g=p;break e}else{n(g,p);break}else e(g,p);p=p.sibling}p=ja(m,g.mode,S),p.return=g,g=p}return o(g);case pn:return P=m._init,E(g,p,P(m._payload),S)}if(ji(m))return w(g,p,m,S);if(xi(m))return _(g,p,m,S);ao(g,m)}return typeof m=="string"&&m!==""||typeof m=="number"?(m=""+m,p!==null&&p.tag===6?(n(g,p.sibling),p=i(p,m),p.return=g,g=p):(n(g,p),p=Ma(m,g.mode,S),p.return=g,g=p),o(g)):n(g,p)}return E}var ni=ag(!0),ug=ag(!1),Qo=qn(null),Yo=null,jr=null,Vc=null;function Hc(){Vc=jr=Yo=null}function Gc(t){var e=Qo.current;he(Qo),t._currentValue=e}function Pu(t,e,n){for(;t!==null;){var r=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),t===n)break;t=t.return}}function Gr(t,e){Yo=t,Vc=jr=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(it=!0),t.firstContext=null)}function wt(t){var e=t._currentValue;if(Vc!==t)if(t={context:t,memoizedValue:e,next:null},jr===null){if(Yo===null)throw Error(k(308));jr=t,Yo.dependencies={lanes:0,firstContext:t}}else jr=jr.next=t;return e}var nr=null;function qc(t){nr===null?nr=[t]:nr.push(t)}function cg(t,e,n,r){var i=e.interleaved;return i===null?(n.next=n,qc(e)):(n.next=i.next,i.next=n),e.interleaved=n,tn(t,r)}function tn(t,e){t.lanes|=e;var n=t.alternate;for(n!==null&&(n.lanes|=e),n=t,t=t.return;t!==null;)t.childLanes|=e,n=t.alternate,n!==null&&(n.childLanes|=e),n=t,t=t.return;return n.tag===3?n.stateNode:null}var mn=!1;function Kc(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function dg(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function Jt(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function Nn(t,e,n){var r=t.updateQueue;if(r===null)return null;if(r=r.shared,J&2){var i=r.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),r.pending=e,tn(t,n)}return i=r.interleaved,i===null?(e.next=e,qc(r)):(e.next=i.next,i.next=e),r.interleaved=e,tn(t,n)}function Co(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194240)!==0)){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,Oc(t,n)}}function Yh(t,e){var n=t.updateQueue,r=t.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?i=s=o:s=s.next=o,n=n.next}while(n!==null);s===null?i=s=e:s=s.next=e}else i=s=e;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}function Jo(t,e,n,r){var i=t.updateQueue;mn=!1;var s=i.firstBaseUpdate,o=i.lastBaseUpdate,l=i.shared.pending;if(l!==null){i.shared.pending=null;var a=l,u=a.next;a.next=null,o===null?s=u:o.next=u,o=a;var h=t.alternate;h!==null&&(h=h.updateQueue,l=h.lastBaseUpdate,l!==o&&(l===null?h.firstBaseUpdate=u:l.next=u,h.lastBaseUpdate=a))}if(s!==null){var d=i.baseState;o=0,h=u=a=null,l=s;do{var f=l.lane,v=l.eventTime;if((r&f)===f){h!==null&&(h=h.next={eventTime:v,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var w=t,_=l;switch(f=e,v=n,_.tag){case 1:if(w=_.payload,typeof w=="function"){d=w.call(v,d,f);break e}d=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=_.payload,f=typeof w=="function"?w.call(v,d,f):w,f==null)break e;d=ve({},d,f);break e;case 2:mn=!0}}l.callback!==null&&l.lane!==0&&(t.flags|=64,f=i.effects,f===null?i.effects=[l]:f.push(l))}else v={eventTime:v,lane:f,tag:l.tag,payload:l.payload,callback:l.callback,next:null},h===null?(u=h=v,a=d):h=h.next=v,o|=f;if(l=l.next,l===null){if(l=i.shared.pending,l===null)break;f=l,l=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(!0);if(h===null&&(a=d),i.baseState=a,i.firstBaseUpdate=u,i.lastBaseUpdate=h,e=i.shared.interleaved,e!==null){i=e;do o|=i.lane,i=i.next;while(i!==e)}else s===null&&(i.shared.lanes=0);dr|=o,t.lanes=o,t.memoizedState=d}}function Jh(t,e,n){if(t=e.effects,e.effects=null,t!==null)for(e=0;en?n:4,t(!0);var r=Ra.transition;Ra.transition={};try{t(!1),e()}finally{ie=n,Ra.transition=r}}function bg(){return St().memoizedState}function Uw(t,e,n){var r=An(t);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Pg(t))Ng(e,n);else if(n=cg(t,e,n,r),n!==null){var i=Qe();Rt(n,t,r,i),Rg(n,e,r)}}function zw(t,e,n){var r=An(t),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Pg(t))Ng(e,i);else{var s=t.alternate;if(t.lanes===0&&(s===null||s.lanes===0)&&(s=e.lastRenderedReducer,s!==null))try{var o=e.lastRenderedState,l=s(o,n);if(i.hasEagerState=!0,i.eagerState=l,Ot(l,o)){var a=e.interleaved;a===null?(i.next=i,qc(e)):(i.next=a.next,a.next=i),e.interleaved=i;return}}catch{}finally{}n=cg(t,e,i,r),n!==null&&(i=Qe(),Rt(n,t,r,i),Rg(n,e,r))}}function Pg(t){var e=t.alternate;return t===ge||e!==null&&e===ge}function Ng(t,e){Hi=Zo=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function Rg(t,e,n){if(n&4194240){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,Oc(t,n)}}var el={readContext:wt,useCallback:We,useContext:We,useEffect:We,useImperativeHandle:We,useInsertionEffect:We,useLayoutEffect:We,useMemo:We,useReducer:We,useRef:We,useState:We,useDebugValue:We,useDeferredValue:We,useTransition:We,useMutableSource:We,useSyncExternalStore:We,useId:We,unstable_isNewReconciler:!1},Bw={readContext:wt,useCallback:function(t,e){return Lt().memoizedState=[t,e===void 0?null:e],t},useContext:wt,useEffect:Zh,useImperativeHandle:function(t,e,n){return n=n!=null?n.concat([t]):null,xo(4194308,4,Eg.bind(null,e,t),n)},useLayoutEffect:function(t,e){return xo(4194308,4,t,e)},useInsertionEffect:function(t,e){return xo(4,2,t,e)},useMemo:function(t,e){var n=Lt();return e=e===void 0?null:e,t=t(),n.memoizedState=[t,e],t},useReducer:function(t,e,n){var r=Lt();return e=n!==void 0?n(e):e,r.memoizedState=r.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},r.queue=t,t=t.dispatch=Uw.bind(null,ge,t),[r.memoizedState,t]},useRef:function(t){var e=Lt();return t={current:t},e.memoizedState=t},useState:Xh,useDebugValue:nd,useDeferredValue:function(t){return Lt().memoizedState=t},useTransition:function(){var t=Xh(!1),e=t[0];return t=Fw.bind(null,t[1]),Lt().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,n){var r=ge,i=Lt();if(fe){if(n===void 0)throw Error(k(407));n=n()}else{if(n=e(),Le===null)throw Error(k(349));cr&30||mg(r,e,n)}i.memoizedState=n;var s={value:n,getSnapshot:e};return i.queue=s,Zh(vg.bind(null,r,s,t),[t]),r.flags|=2048,gs(9,gg.bind(null,r,s,n,e),void 0,null),n},useId:function(){var t=Lt(),e=Le.identifierPrefix;if(fe){var n=Ht,r=Vt;n=(r&~(1<<32-Nt(r)-1)).toString(32)+n,e=":"+e+"R"+n,n=ps++,0<\/script>",t=t.removeChild(t.firstChild)):typeof r.is=="string"?t=o.createElement(n,{is:r.is}):(t=o.createElement(n),n==="select"&&(o=t,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):t=o.createElementNS(t,n),t[Mt]=e,t[ds]=r,Bg(t,e,!1,!1),e.stateNode=t;e:{switch(o=du(n,r),n){case"dialog":de("cancel",t),de("close",t),i=r;break;case"iframe":case"object":case"embed":de("load",t),i=r;break;case"video":case"audio":for(i=0;isi&&(e.flags|=128,r=!0,Ni(s,!1),e.lanes=4194304)}else{if(!r)if(t=Xo(o),t!==null){if(e.flags|=128,r=!0,n=t.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),Ni(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!fe)return $e(e),null}else 2*Ce()-s.renderingStartTime>si&&n!==1073741824&&(e.flags|=128,r=!0,Ni(s,!1),e.lanes=4194304);s.isBackwards?(o.sibling=e.child,e.child=o):(n=s.last,n!==null?n.sibling=o:e.child=o,s.last=o)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=Ce(),e.sibling=null,n=me.current,ce(me,r?n&1|2:n&1),e):($e(e),null);case 22:case 23:return ad(),r=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==r&&(e.flags|=8192),r&&e.mode&1?ut&1073741824&&($e(e),e.subtreeFlags&6&&(e.flags|=8192)):$e(e),null;case 24:return null;case 25:return null}throw Error(k(156,e.tag))}function Qw(t,e){switch(Wc(e),e.tag){case 1:return lt(e.type)&&Ho(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return ri(),he(ot),he(He),Jc(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return Yc(e),null;case 13:if(he(me),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(k(340));ti()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return he(me),null;case 4:return ri(),null;case 10:return Gc(e.type._context),null;case 22:case 23:return ad(),null;case 24:return null;default:return null}}var co=!1,Ve=!1,Yw=typeof WeakSet=="function"?WeakSet:Set,M=null;function Fr(t,e){var n=t.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ye(t,e,r)}else n.current=null}function Fu(t,e,n){try{n()}catch(r){ye(t,e,r)}}var df=!1;function Jw(t,e){if(Su=Bo,t=Km(),zc(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var o=0,l=-1,a=-1,u=0,h=0,d=t,f=null;t:for(;;){for(var v;d!==n||i!==0&&d.nodeType!==3||(l=o+i),d!==s||r!==0&&d.nodeType!==3||(a=o+r),d.nodeType===3&&(o+=d.nodeValue.length),(v=d.firstChild)!==null;)f=d,d=v;for(;;){if(d===t)break t;if(f===n&&++u===i&&(l=o),f===s&&++h===r&&(a=o),(v=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=v}n=l===-1||a===-1?null:{start:l,end:a}}else n=null}n=n||{start:0,end:0}}else n=null;for(Cu={focusedElem:t,selectionRange:n},Bo=!1,M=e;M!==null;)if(e=M,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,M=t;else for(;M!==null;){e=M;try{var w=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var _=w.memoizedProps,E=w.memoizedState,g=e.stateNode,p=g.getSnapshotBeforeUpdate(e.elementType===e.type?_:It(e.type,_),E);g.__reactInternalSnapshotBeforeUpdate=p}break;case 3:var m=e.stateNode.containerInfo;m.nodeType===1?m.textContent="":m.nodeType===9&&m.documentElement&&m.removeChild(m.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(k(163))}}catch(S){ye(e,e.return,S)}if(t=e.sibling,t!==null){t.return=e.return,M=t;break}M=e.return}return w=df,df=!1,w}function Gi(t,e,n){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&t)===t){var s=i.destroy;i.destroy=void 0,s!==void 0&&Fu(e,n,s)}i=i.next}while(i!==r)}}function Ul(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var n=e=e.next;do{if((n.tag&t)===t){var r=n.create;n.destroy=r()}n=n.next}while(n!==e)}}function Uu(t){var e=t.ref;if(e!==null){var n=t.stateNode;switch(t.tag){case 5:t=n;break;default:t=n}typeof e=="function"?e(t):e.current=t}}function Vg(t){var e=t.alternate;e!==null&&(t.alternate=null,Vg(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[Mt],delete e[ds],delete e[Iu],delete e[Ow],delete e[Dw])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function Hg(t){return t.tag===5||t.tag===3||t.tag===4}function hf(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Hg(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function zu(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.nodeType===8?n.parentNode.insertBefore(t,e):n.insertBefore(t,e):(n.nodeType===8?(e=n.parentNode,e.insertBefore(t,n)):(e=n,e.appendChild(t)),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=Vo));else if(r!==4&&(t=t.child,t!==null))for(zu(t,e,n),t=t.sibling;t!==null;)zu(t,e,n),t=t.sibling}function Bu(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(r!==4&&(t=t.child,t!==null))for(Bu(t,e,n),t=t.sibling;t!==null;)Bu(t,e,n),t=t.sibling}var Me=null,kt=!1;function dn(t,e,n){for(n=n.child;n!==null;)Gg(t,e,n),n=n.sibling}function Gg(t,e,n){if(jt&&typeof jt.onCommitFiberUnmount=="function")try{jt.onCommitFiberUnmount(Rl,n)}catch{}switch(n.tag){case 5:Ve||Fr(n,e);case 6:var r=Me,i=kt;Me=null,dn(t,e,n),Me=r,kt=i,Me!==null&&(kt?(t=Me,n=n.stateNode,t.nodeType===8?t.parentNode.removeChild(n):t.removeChild(n)):Me.removeChild(n.stateNode));break;case 18:Me!==null&&(kt?(t=Me,n=n.stateNode,t.nodeType===8?ba(t.parentNode,n):t.nodeType===1&&ba(t,n),os(t)):ba(Me,n.stateNode));break;case 4:r=Me,i=kt,Me=n.stateNode.containerInfo,kt=!0,dn(t,e,n),Me=r,kt=i;break;case 0:case 11:case 14:case 15:if(!Ve&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var s=i,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&Fu(n,e,o),i=i.next}while(i!==r)}dn(t,e,n);break;case 1:if(!Ve&&(Fr(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){ye(n,e,l)}dn(t,e,n);break;case 21:dn(t,e,n);break;case 22:n.mode&1?(Ve=(r=Ve)||n.memoizedState!==null,dn(t,e,n),Ve=r):dn(t,e,n);break;default:dn(t,e,n)}}function ff(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var n=t.stateNode;n===null&&(n=t.stateNode=new Yw),e.forEach(function(r){var i=oS.bind(null,t,r);n.has(r)||(n.add(r),r.then(i,i))})}}function xt(t,e){var n=e.deletions;if(n!==null)for(var r=0;ri&&(i=o),r&=~s}if(r=i,r=Ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Zw(r/1960))-r,10t?16:t,En===null)var r=!1;else{if(t=En,En=null,rl=0,J&6)throw Error(k(331));var i=J;for(J|=4,M=t.current;M!==null;){var s=M,o=s.child;if(M.flags&16){var l=s.deletions;if(l!==null){for(var a=0;aCe()-od?sr(t,0):sd|=n),at(t,e)}function ev(t,e){e===0&&(t.mode&1?(e=to,to<<=1,!(to&130023424)&&(to=4194304)):e=1);var n=Qe();t=tn(t,e),t!==null&&(Os(t,e,n),at(t,n))}function sS(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),ev(t,n)}function oS(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,i=t.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=t.stateNode;break;default:throw Error(k(314))}r!==null&&r.delete(e),ev(t,n)}var tv;tv=function(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps||ot.current)it=!0;else{if(!(t.lanes&n)&&!(e.flags&128))return it=!1,qw(t,e,n);it=!!(t.flags&131072)}else it=!1,fe&&e.flags&1048576&&sg(e,Ko,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;Io(t,e),t=e.pendingProps;var i=ei(e,He.current);Gr(e,n),i=Zc(null,e,r,t,i,n);var s=ed();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,lt(r)?(s=!0,Go(e)):s=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Kc(e),i.updater=Fl,e.stateNode=i,i._reactInternals=e,Ru(e,r,t,n),e=Du(null,e,r,!0,s,n)):(e.tag=0,fe&&s&&Bc(e),qe(null,e,i,n),e=e.child),e;case 16:r=e.elementType;e:{switch(Io(t,e),t=e.pendingProps,i=r._init,r=i(r._payload),e.type=r,i=e.tag=aS(r),t=It(r,t),i){case 0:e=Ou(null,e,r,t,n);break e;case 1:e=af(null,e,r,t,n);break e;case 11:e=of(null,e,r,t,n);break e;case 14:e=lf(null,e,r,It(r.type,t),n);break e}throw Error(k(306,r,""))}return e;case 0:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:It(r,i),Ou(t,e,r,i,n);case 1:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:It(r,i),af(t,e,r,i,n);case 3:e:{if(Fg(e),t===null)throw Error(k(387));r=e.pendingProps,s=e.memoizedState,i=s.element,dg(t,e),Jo(e,r,null,n);var o=e.memoizedState;if(r=o.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},e.updateQueue.baseState=s,e.memoizedState=s,e.flags&256){i=ii(Error(k(423)),e),e=uf(t,e,r,n,i);break e}else if(r!==i){i=ii(Error(k(424)),e),e=uf(t,e,r,n,i);break e}else for(ct=Pn(e.stateNode.containerInfo.firstChild),dt=e,fe=!0,Tt=null,n=ug(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ti(),r===i){e=nn(t,e,n);break e}qe(t,e,r,n)}e=e.child}return e;case 5:return hg(e),t===null&&bu(e),r=e.type,i=e.pendingProps,s=t!==null?t.memoizedProps:null,o=i.children,Eu(r,i)?o=null:s!==null&&Eu(r,s)&&(e.flags|=32),jg(t,e),qe(t,e,o,n),e.child;case 6:return t===null&&bu(e),null;case 13:return Ug(t,e,n);case 4:return Qc(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=ni(e,null,r,n):qe(t,e,r,n),e.child;case 11:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:It(r,i),of(t,e,r,i,n);case 7:return qe(t,e,e.pendingProps,n),e.child;case 8:return qe(t,e,e.pendingProps.children,n),e.child;case 12:return qe(t,e,e.pendingProps.children,n),e.child;case 10:e:{if(r=e.type._context,i=e.pendingProps,s=e.memoizedProps,o=i.value,ce(Qo,r._currentValue),r._currentValue=o,s!==null)if(Ot(s.value,o)){if(s.children===i.children&&!ot.current){e=nn(t,e,n);break e}}else for(s=e.child,s!==null&&(s.return=e);s!==null;){var l=s.dependencies;if(l!==null){o=s.child;for(var a=l.firstContext;a!==null;){if(a.context===r){if(s.tag===1){a=Jt(-1,n&-n),a.tag=2;var u=s.updateQueue;if(u!==null){u=u.shared;var h=u.pending;h===null?a.next=a:(a.next=h.next,h.next=a),u.pending=a}}s.lanes|=n,a=s.alternate,a!==null&&(a.lanes|=n),Pu(s.return,n,e),l.lanes|=n;break}a=a.next}}else if(s.tag===10)o=s.type===e.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(k(341));o.lanes|=n,l=o.alternate,l!==null&&(l.lanes|=n),Pu(o,n,e),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===e){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}qe(t,e,i.children,n),e=e.child}return e;case 9:return i=e.type,r=e.pendingProps.children,Gr(e,n),i=wt(i),r=r(i),e.flags|=1,qe(t,e,r,n),e.child;case 14:return r=e.type,i=It(r,e.pendingProps),i=It(r.type,i),lf(t,e,r,i,n);case 15:return Lg(t,e,e.type,e.pendingProps,n);case 17:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:It(r,i),Io(t,e),e.tag=1,lt(r)?(t=!0,Go(e)):t=!1,Gr(e,n),Ag(e,r,i),Ru(e,r,i,n),Du(null,e,r,!0,t,n);case 19:return zg(t,e,n);case 22:return Mg(t,e,n)}throw Error(k(156,e.tag))};function nv(t,e){return Pm(t,e)}function lS(t,e,n,r){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function vt(t,e,n,r){return new lS(t,e,n,r)}function cd(t){return t=t.prototype,!(!t||!t.isReactComponent)}function aS(t){if(typeof t=="function")return cd(t)?1:0;if(t!=null){if(t=t.$$typeof,t===Pc)return 11;if(t===Nc)return 14}return 2}function On(t,e){var n=t.alternate;return n===null?(n=vt(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&14680064,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n}function bo(t,e,n,r,i,s){var o=2;if(r=t,typeof t=="function")cd(t)&&(o=1);else if(typeof t=="string")o=5;else e:switch(t){case Pr:return or(n.children,i,s,e);case bc:o=8,i|=8;break;case tu:return t=vt(12,n,e,i|2),t.elementType=tu,t.lanes=s,t;case nu:return t=vt(13,n,e,i),t.elementType=nu,t.lanes=s,t;case ru:return t=vt(19,n,e,i),t.elementType=ru,t.lanes=s,t;case hm:return Bl(n,i,s,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case cm:o=10;break e;case dm:o=9;break e;case Pc:o=11;break e;case Nc:o=14;break e;case pn:o=16,r=null;break e}throw Error(k(130,t==null?t:typeof t,""))}return e=vt(o,n,e,i),e.elementType=t,e.type=r,e.lanes=s,e}function or(t,e,n,r){return t=vt(7,t,r,e),t.lanes=n,t}function Bl(t,e,n,r){return t=vt(22,t,r,e),t.elementType=hm,t.lanes=n,t.stateNode={isHidden:!1},t}function Ma(t,e,n){return t=vt(6,t,null,e),t.lanes=n,t}function ja(t,e,n){return e=vt(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function uS(t,e,n,r,i){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=va(0),this.expirationTimes=va(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=va(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function dd(t,e,n,r,i,s,o,l,a){return t=new uS(t,e,n,l,a),e===1?(e=1,s===!0&&(e|=8)):e=0,s=vt(3,null,null,e),t.current=s,s.stateNode=t,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Kc(s),t}function cS(t,e,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(ov)}catch(t){console.error(t)}}ov(),om.exports=ft;var mS=om.exports,Sf=mS;Za.createRoot=Sf.createRoot,Za.hydrateRoot=Sf.hydrateRoot;/** - * @remix-run/router v1.23.3 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function ys(){return ys=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function md(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function vS(){return Math.random().toString(36).substr(2,8)}function Ef(t,e){return{usr:t.state,key:t.key,idx:e}}function Gu(t,e,n,r){return n===void 0&&(n=null),ys({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?gi(e):e,{state:n,key:e&&e.key||r||vS()})}function lv(t){let{pathname:e="/",search:n="",hash:r=""}=t;return n&&n!=="?"&&(e+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(e+=r.charAt(0)==="#"?r:"#"+r),e}function gi(t){let e={};if(t){let n=t.indexOf("#");n>=0&&(e.hash=t.substr(n),t=t.substr(0,n));let r=t.indexOf("?");r>=0&&(e.search=t.substr(r),t=t.substr(0,r)),t&&(e.pathname=t)}return e}function yS(t,e,n,r){r===void 0&&(r={});let{window:i=document.defaultView,v5Compat:s=!1}=r,o=i.history,l=xn.Pop,a=null,u=h();u==null&&(u=0,o.replaceState(ys({},o.state,{idx:u}),""));function h(){return(o.state||{idx:null}).idx}function d(){l=xn.Pop;let E=h(),g=E==null?null:E-u;u=E,a&&a({action:l,location:_.location,delta:g})}function f(E,g){l=xn.Push;let p=Gu(_.location,E,g);u=h()+1;let m=Ef(p,u),S=_.createHref(p);try{o.pushState(m,"",S)}catch(I){if(I instanceof DOMException&&I.name==="DataCloneError")throw I;i.location.assign(S)}s&&a&&a({action:l,location:_.location,delta:1})}function v(E,g){l=xn.Replace;let p=Gu(_.location,E,g);u=h();let m=Ef(p,u),S=_.createHref(p);o.replaceState(m,"",S),s&&a&&a({action:l,location:_.location,delta:0})}function w(E){let g=i.location.origin!=="null"?i.location.origin:i.location.href,p=typeof E=="string"?E:lv(E);return p=p.replace(/ $/,"%20"),ke(g,"No window.location.(origin|href) available to create URL for href: "+p),new URL(p,g)}let _={get action(){return l},get location(){return t(i,o)},listen(E){if(a)throw new Error("A history only accepts one active listener");return i.addEventListener(Cf,d),a=E,()=>{i.removeEventListener(Cf,d),a=null}},createHref(E){return e(i,E)},createURL:w,encodeLocation(E){let g=w(E);return{pathname:g.pathname,search:g.search,hash:g.hash}},push:f,replace:v,go(E){return o.go(E)}};return _}var xf;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(xf||(xf={}));function _S(t,e,n){return n===void 0&&(n="/"),wS(t,e,n)}function wS(t,e,n,r){let i=typeof e=="string"?gi(e):e,s=cv(i.pathname||"/",n);if(s==null)return null;let o=av(t);SS(o);let l=null,a=OS(s);for(let u=0;l==null&&u{let a={relativePath:l===void 0?s.path||"":l,caseSensitive:s.caseSensitive===!0,childrenIndex:o,route:s};a.relativePath.startsWith("/")&&(ke(a.relativePath.startsWith(r),'Absolute route path "'+a.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),a.relativePath=a.relativePath.slice(r.length));let u=lr([r,a.relativePath]),h=n.concat(a);s.children&&s.children.length>0&&(ke(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+u+'".')),av(s.children,e,h,u)),!(s.path==null&&!s.index)&&e.push({path:u,score:bS(u,s.index),routesMeta:h})};return t.forEach((s,o)=>{var l;if(s.path===""||!((l=s.path)!=null&&l.includes("?")))i(s,o);else for(let a of uv(s.path))i(s,o,a)}),e}function uv(t){let e=t.split("/");if(e.length===0)return[];let[n,...r]=e,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return i?[s,""]:[s];let o=uv(r.join("/")),l=[];return l.push(...o.map(a=>a===""?s:[s,a].join("/"))),i&&l.push(...o),l.map(a=>t.startsWith("/")&&a===""?"/":a)}function SS(t){t.sort((e,n)=>e.score!==n.score?n.score-e.score:PS(e.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const CS=/^:[\w-]+$/,ES=3,xS=2,IS=1,kS=10,TS=-2,If=t=>t==="*";function bS(t,e){let n=t.split("/"),r=n.length;return n.some(If)&&(r+=TS),e&&(r+=xS),n.filter(i=>!If(i)).reduce((i,s)=>i+(CS.test(s)?ES:s===""?IS:kS),r)}function PS(t,e){return t.length===e.length&&t.slice(0,-1).every((r,i)=>r===e[i])?t[t.length-1]-e[e.length-1]:0}function NS(t,e,n){let{routesMeta:r}=t,i={},s="/",o=[];for(let l=0;l{let{paramName:f,isOptional:v}=h;if(f==="*"){let _=l[d]||"";o=s.slice(0,s.length-_.length).replace(/(.)\/+$/,"$1")}const w=l[d];return v&&!w?u[f]=void 0:u[f]=(w||"").replace(/%2F/g,"/"),u},{}),pathname:s,pathnameBase:o,pattern:t}}function AS(t,e,n){e===void 0&&(e=!1),n===void 0&&(n=!0),md(t==="*"||!t.endsWith("*")||t.endsWith("/*"),'Route path "'+t+'" will be treated as if it were '+('"'+t.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+t.replace(/\*$/,"/*")+'".'));let r=[],i="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,l,a)=>(r.push({paramName:l,isOptional:a!=null}),a?"/?([^\\/]+)?":"/([^\\/]+)"));return t.endsWith("*")?(r.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),r]}function OS(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return md(!1,'The URL path "'+t+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),t}}function cv(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let n=e.endsWith("/")?e.length-1:e.length,r=t.charAt(n);return r&&r!=="/"?null:t.slice(n)||"/"}const DS=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,LS=t=>DS.test(t);function MS(t,e){e===void 0&&(e="/");let{pathname:n,search:r="",hash:i=""}=typeof t=="string"?gi(t):t,s;if(n)if(LS(n))s=n;else{if(n.includes("//")){let o=n;n=fv(n),md(!1,"Pathnames cannot have embedded double slashes - normalizing "+(o+" -> "+n))}n.startsWith("/")?s=kf(n.substring(1),"/"):s=kf(n,e)}else s=e;return{pathname:s,search:US(r),hash:zS(i)}}function kf(t,e){let n=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(i=>{i===".."?n.length>1&&n.pop():i!=="."&&n.push(i)}),n.length>1?n.join("/"):"/"}function Fa(t,e,n,r){return"Cannot include a '"+t+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function jS(t){return t.filter((e,n)=>n===0||e.route.path&&e.route.path.length>0)}function dv(t,e){let n=jS(t);return e?n.map((r,i)=>i===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function hv(t,e,n,r){r===void 0&&(r=!1);let i;typeof t=="string"?i=gi(t):(i=ys({},t),ke(!i.pathname||!i.pathname.includes("?"),Fa("?","pathname","search",i)),ke(!i.pathname||!i.pathname.includes("#"),Fa("#","pathname","hash",i)),ke(!i.search||!i.search.includes("#"),Fa("#","search","hash",i)));let s=t===""||i.pathname==="",o=s?"/":i.pathname,l;if(o==null)l=n;else{let d=e.length-1;if(!r&&o.startsWith("..")){let f=o.split("/");for(;f[0]==="..";)f.shift(),d-=1;i.pathname=f.join("/")}l=d>=0?e[d]:"/"}let a=MS(i,l),u=o&&o!=="/"&&o.endsWith("/"),h=(s||o===".")&&n.endsWith("/");return!a.pathname.endsWith("/")&&(u||h)&&(a.pathname+="/"),a}const fv=t=>t.replace(/\/\/+/g,"/"),lr=t=>fv(t.join("/")),FS=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),US=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,zS=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function BS(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const pv=["post","put","patch","delete"];new Set(pv);const WS=["get",...pv];new Set(WS);/** - * React Router v6.30.4 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function _s(){return _s=Object.assign?Object.assign.bind():function(t){for(var e=1;e{l.current=!0}),C.useCallback(function(u,h){if(h===void 0&&(h={}),!l.current)return;if(typeof u=="number"){r.go(u);return}let d=hv(u,JSON.parse(o),s,h.relative==="path");t==null&&e!=="/"&&(d.pathname=d.pathname==="/"?e:lr([e,d.pathname])),(h.replace?r.replace:r.push)(d,h.state,h)},[e,r,o,s,t])}function HS(){let{matches:t}=C.useContext(Qn),e=t[t.length-1];return e?e.params:{}}function GS(t,e){return qS(t,e)}function qS(t,e,n,r){Fs()||ke(!1);let{navigator:i}=C.useContext(js),{matches:s}=C.useContext(Qn),o=s[s.length-1],l=o?o.params:{};o&&o.pathname;let a=o?o.pathnameBase:"/";o&&o.route;let u=vd(),h;if(e){var d;let E=typeof e=="string"?gi(e):e;a==="/"||(d=E.pathname)!=null&&d.startsWith(a)||ke(!1),h=E}else h=u;let f=h.pathname||"/",v=f;if(a!=="/"){let E=a.replace(/^\//,"").split("/");v="/"+f.replace(/^\//,"").split("/").slice(E.length).join("/")}let w=_S(t,{pathname:v}),_=XS(w&&w.map(E=>Object.assign({},E,{params:Object.assign({},l,E.params),pathname:lr([a,i.encodeLocation?i.encodeLocation(E.pathname).pathname:E.pathname]),pathnameBase:E.pathnameBase==="/"?a:lr([a,i.encodeLocation?i.encodeLocation(E.pathnameBase).pathname:E.pathnameBase])})),s,n,r);return e&&_?C.createElement(Gl.Provider,{value:{location:_s({pathname:"/",search:"",hash:"",state:null,key:"default"},h),navigationType:xn.Pop}},_):_}function KS(){let t=nC(),e=BS(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return C.createElement(C.Fragment,null,C.createElement("h2",null,"Unexpected Application Error!"),C.createElement("h3",{style:{fontStyle:"italic"}},e),n?C.createElement("pre",{style:i},n):null,null)}const QS=C.createElement(KS,null);class YS extends C.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,n){return n.location!==e.location||n.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:n.error,location:n.location,revalidation:e.revalidation||n.revalidation}}componentDidCatch(e,n){console.error("React Router caught the following error during render",e,n)}render(){return this.state.error!==void 0?C.createElement(Qn.Provider,{value:this.props.routeContext},C.createElement(mv.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function JS(t){let{routeContext:e,match:n,children:r}=t,i=C.useContext(gd);return i&&i.static&&i.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=n.route.id),C.createElement(Qn.Provider,{value:e},r)}function XS(t,e,n,r){var i;if(e===void 0&&(e=[]),n===void 0&&(n=null),r===void 0&&(r=null),t==null){var s;if(!n)return null;if(n.errors)t=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&e.length===0&&!n.initialized&&n.matches.length>0)t=n.matches;else return null}let o=t,l=(i=n)==null?void 0:i.errors;if(l!=null){let h=o.findIndex(d=>d.route.id&&(l==null?void 0:l[d.route.id])!==void 0);h>=0||ke(!1),o=o.slice(0,Math.min(o.length,h+1))}let a=!1,u=-1;if(n&&r&&r.v7_partialHydration)for(let h=0;h=0?o=o.slice(0,u+1):o=[o[0]];break}}}return o.reduceRight((h,d,f)=>{let v,w=!1,_=null,E=null;n&&(v=l&&d.route.id?l[d.route.id]:void 0,_=d.route.errorElement||QS,a&&(u<0&&f===0?(iC("route-fallback"),w=!0,E=null):u===f&&(w=!0,E=d.route.hydrateFallbackElement||null)));let g=e.concat(o.slice(0,f+1)),p=()=>{let m;return v?m=_:w?m=E:d.route.Component?m=C.createElement(d.route.Component,null):d.route.element?m=d.route.element:m=h,C.createElement(JS,{match:d,routeContext:{outlet:h,matches:g,isDataRoute:n!=null},children:m})};return n&&(d.route.ErrorBoundary||d.route.errorElement||f===0)?C.createElement(YS,{location:n.location,revalidation:n.revalidation,component:_,error:v,children:p(),routeContext:{outlet:null,matches:g,isDataRoute:!0}}):p()},null)}var vv=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(vv||{}),yv=function(t){return t.UseBlocker="useBlocker",t.UseLoaderData="useLoaderData",t.UseActionData="useActionData",t.UseRouteError="useRouteError",t.UseNavigation="useNavigation",t.UseRouteLoaderData="useRouteLoaderData",t.UseMatches="useMatches",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t.UseRouteId="useRouteId",t}(yv||{});function ZS(t){let e=C.useContext(gd);return e||ke(!1),e}function eC(t){let e=C.useContext($S);return e||ke(!1),e}function tC(t){let e=C.useContext(Qn);return e||ke(!1),e}function _v(t){let e=tC(),n=e.matches[e.matches.length-1];return n.route.id||ke(!1),n.route.id}function nC(){var t;let e=C.useContext(mv),n=eC(),r=_v();return e!==void 0?e:(t=n.errors)==null?void 0:t[r]}function rC(){let{router:t}=ZS(vv.UseNavigateStable),e=_v(yv.UseNavigateStable),n=C.useRef(!1);return gv(()=>{n.current=!0}),C.useCallback(function(i,s){s===void 0&&(s={}),n.current&&(typeof i=="number"?t.navigate(i):t.navigate(i,_s({fromRouteId:e},s)))},[t,e])}const Tf={};function iC(t,e,n){Tf[t]||(Tf[t]=!0)}function sC(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function oC(t){let{to:e,replace:n,state:r,relative:i}=t;Fs()||ke(!1);let{future:s,static:o}=C.useContext(js),{matches:l}=C.useContext(Qn),{pathname:a}=vd(),u=Sr(),h=hv(e,dv(l,s.v7_relativeSplatPath),a,i==="path"),d=JSON.stringify(h);return C.useEffect(()=>u(JSON.parse(d),{replace:n,state:r,relative:i}),[u,d,i,n,r]),null}function fn(t){ke(!1)}function lC(t){let{basename:e="/",children:n=null,location:r,navigationType:i=xn.Pop,navigator:s,static:o=!1,future:l}=t;Fs()&&ke(!1);let a=e.replace(/^\/*/,"/"),u=C.useMemo(()=>({basename:a,navigator:s,static:o,future:_s({v7_relativeSplatPath:!1},l)}),[a,l,s,o]);typeof r=="string"&&(r=gi(r));let{pathname:h="/",search:d="",hash:f="",state:v=null,key:w="default"}=r,_=C.useMemo(()=>{let E=cv(h,a);return E==null?null:{location:{pathname:E,search:d,hash:f,state:v,key:w},navigationType:i}},[a,h,d,f,v,w,i]);return _==null?null:C.createElement(js.Provider,{value:u},C.createElement(Gl.Provider,{children:n,value:_}))}function aC(t){let{children:e,location:n}=t;return GS(qu(e),n)}new Promise(()=>{});function qu(t,e){e===void 0&&(e=[]);let n=[];return C.Children.forEach(t,(r,i)=>{if(!C.isValidElement(r))return;let s=[...e,i];if(r.type===C.Fragment){n.push.apply(n,qu(r.props.children,s));return}r.type!==fn&&ke(!1),!r.props.index||!r.props.children||ke(!1);let o={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(o.children=qu(r.props.children,s)),n.push(o)}),n}/** - * React Router DOM v6.30.4 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */const uC="6";try{window.__reactRouterVersion=uC}catch{}const cC="startTransition",bf=i0[cC];function dC(t){let{basename:e,children:n,future:r,window:i}=t,s=C.useRef();s.current==null&&(s.current=gS({window:i,v5Compat:!0}));let o=s.current,[l,a]=C.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},h=C.useCallback(d=>{u&&bf?bf(()=>a(d)):a(d)},[a,u]);return C.useLayoutEffect(()=>o.listen(h),[o,h]),C.useEffect(()=>sC(r),[r]),C.createElement(lC,{basename:e,children:n,location:l.location,navigationType:l.action,navigator:o,future:r})}var Pf;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(Pf||(Pf={}));var Nf;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(Nf||(Nf={}));const hC="changeme";function fC(){const t=Sr(),[e,n]=C.useState(!1),[r,i]=C.useState(""),[s,o]=C.useState("");function l(a){a.preventDefault(),r===hC?(localStorage.setItem("role","teacher"),t("/teacher")):(o("Incorrect password."),i(""))}return c.jsxs("div",{style:Se.page,children:[c.jsxs("div",{style:Se.header,children:[c.jsx("div",{style:Se.logoMark,children:"●"}),c.jsx("span",{style:Se.logoText,children:"ClassPoll"})]}),c.jsxs("div",{style:Se.hero,className:"fade-up",children:[c.jsxs("h1",{style:Se.title,children:["Live Classroom",c.jsx("br",{}),"Polling"]}),c.jsx("p",{style:Se.sub,children:"Real-time polls, instant results, zero setup for students."})]}),c.jsxs("div",{style:Se.cards,className:"fade-up",children:[c.jsxs("button",{style:Se.roleCard,onClick:()=>t("/student"),children:[c.jsx("span",{style:Se.roleIcon,children:"πŸŽ“"}),c.jsx("span",{style:Se.roleLabel,children:"I'm a Student"}),c.jsx("span",{style:Se.roleHint,children:"Join and answer polls"})]}),e?c.jsxs("form",{style:{...Se.roleCard,gap:"0.75rem"},onSubmit:l,children:[c.jsx("span",{style:Se.roleIcon,children:"πŸ”‘"}),c.jsx("span",{style:Se.roleLabel,children:"Teacher Password"}),c.jsx("input",{className:"input",type:"password",placeholder:"Enter password",value:r,onChange:a=>{i(a.target.value),o("")},autoFocus:!0,style:{textAlign:"center"}}),s&&c.jsx("span",{style:Se.err,children:s}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{width:"100%",justifyContent:"center"},children:"Enter"}),c.jsx("button",{type:"button",className:"btn btn-secondary",style:{width:"100%",justifyContent:"center",fontSize:"0.85rem"},onClick:()=>{n(!1),o(""),i("")},children:"Cancel"})]}):c.jsxs("button",{style:Se.roleCard,onClick:()=>n(!0),children:[c.jsx("span",{style:Se.roleIcon,children:"πŸ“‹"}),c.jsx("span",{style:Se.roleLabel,children:"I'm the Teacher"}),c.jsx("span",{style:Se.roleHint,children:"Create and manage polls"})]})]}),c.jsx("a",{href:"/classroom-polling/history",style:Se.historyLink,children:"View Poll History β†’"})]})}const Se={page:{minHeight:"100vh",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"2rem 1rem",gap:"2rem",background:"var(--paper)"},header:{position:"fixed",top:0,left:0,right:0,padding:"1rem 2rem",display:"flex",alignItems:"center",gap:"0.5rem",borderBottom:"1px solid var(--border)",background:"var(--paper)"},logoMark:{color:"var(--accent)",fontSize:"1.2rem"},logoText:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem"},hero:{textAlign:"center"},title:{fontSize:"clamp(2.2rem, 6vw, 3.5rem)",lineHeight:1.1,marginBottom:"0.75rem"},sub:{color:"var(--muted)",fontSize:"1.05rem",maxWidth:"30ch",margin:"0 auto"},cards:{display:"flex",gap:"1.25rem",flexWrap:"wrap",justifyContent:"center"},roleCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:"0.5rem",padding:"2rem 2.5rem",borderRadius:"16px",border:"2px solid var(--border)",cursor:"pointer",transition:"all 0.2s",background:"white",minWidth:"200px",boxShadow:"var(--shadow)"},roleIcon:{fontSize:"2.5rem"},roleLabel:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.15rem"},roleHint:{fontSize:"0.82rem",color:"var(--muted)"},err:{color:"var(--accent)",fontSize:"0.85rem"},historyLink:{color:"var(--muted)",fontSize:"0.85rem",textDecoration:"underline",cursor:"pointer"}},pC="modulepreload",mC=function(t){return"/classroom-polling/"+t},Rf={},gC=function(e,n,r){let i=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.allSettled(n.map(a=>{if(a=mC(a),a in Rf)return;Rf[a]=!0;const u=a.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${a}"]${h}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":pC,u||(d.as="script"),d.crossOrigin="",d.href=a,l&&d.setAttribute("nonce",l),document.head.appendChild(d),u)return new Promise((f,v)=>{d.addEventListener("load",f),d.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${a}`)))})}))}function s(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&s(l.reason);return e().catch(s)})};var Af={};/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const wv={NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const N=function(t,e){if(!t)throw vi(e)},vi=function(t){return new Error("Firebase Database ("+wv.SDK_VERSION+") INTERNAL ASSERT FAILED: "+t)};/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Sv=function(t){const e=[];let n=0;for(let r=0;r>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e},vC=function(t){const e=[];let n=0,r=0;for(;n191&&i<224){const s=t[n++];e[r++]=String.fromCharCode((i&31)<<6|s&63)}else if(i>239&&i<365){const s=t[n++],o=t[n++],l=t[n++],a=((i&7)<<18|(s&63)<<12|(o&63)<<6|l&63)-65536;e[r++]=String.fromCharCode(55296+(a>>10)),e[r++]=String.fromCharCode(56320+(a&1023))}else{const s=t[n++],o=t[n++];e[r++]=String.fromCharCode((i&15)<<12|(s&63)<<6|o&63)}}return e.join("")},yd={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:typeof atob=="function",encodeByteArray(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let i=0;i>2,d=(s&3)<<4|l>>4;let f=(l&15)<<2|u>>6,v=u&63;a||(v=64,o||(f=64)),r.push(n[h],n[d],n[f],n[v])}return r.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(Sv(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):vC(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();const n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let i=0;i>4;if(r.push(f),u!==64){const v=l<<4&240|u>>2;if(r.push(v),d!==64){const w=u<<6&192|d;r.push(w)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}};class yC extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const Cv=function(t){const e=Sv(t);return yd.encodeByteArray(e,!0)},ol=function(t){return Cv(t).replace(/\./g,"")},ll=function(t){try{return yd.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function _C(t){return Ev(void 0,t)}function Ev(t,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:const n=e;return new Date(n.getTime());case Object:t===void 0&&(t={});break;case Array:t=[];break;default:return e}for(const n in e)!e.hasOwnProperty(n)||!wC(n)||(t[n]=Ev(t[n],e[n]));return t}function wC(t){return t!=="__proto__"}/** - * @license - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function SC(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}/** - * @license - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const CC=()=>SC().__FIREBASE_DEFAULTS__,EC=()=>{if(typeof process>"u"||typeof Af>"u")return;const t=Af.__FIREBASE_DEFAULTS__;if(t)return JSON.parse(t)},xC=()=>{if(typeof document>"u")return;let t;try{t=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const e=t&&ll(t[1]);return e&&JSON.parse(e)},_d=()=>{try{return CC()||EC()||xC()}catch(t){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${t}`);return}},xv=t=>{var e,n;return(n=(e=_d())===null||e===void 0?void 0:e.emulatorHosts)===null||n===void 0?void 0:n[t]},IC=t=>{const e=xv(t);if(!e)return;const n=e.lastIndexOf(":");if(n<=0||n+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);const r=parseInt(e.substring(n+1),10);return e[0]==="["?[e.substring(1,n-1),r]:[e.substring(0,n),r]},Iv=()=>{var t;return(t=_d())===null||t===void 0?void 0:t.config},kv=t=>{var e;return(e=_d())===null||e===void 0?void 0:e[`_${t}`]};/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Us{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,n)=>{this.resolve=e,this.reject=n})}wrapCallback(e){return(n,r)=>{n?this.reject(n):this.resolve(r),typeof e=="function"&&(this.promise.catch(()=>{}),e.length===1?e(n):e(n,r))}}}/** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function kC(t,e){if(t.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n={alg:"none",type:"JWT"},r=e||"demo-project",i=t.iat||0,s=t.sub||t.user_id;if(!s)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const o=Object.assign({iss:`https://securetoken.google.com/${r}`,aud:r,iat:i,exp:i+3600,auth_time:i,sub:s,user_id:s,firebase:{sign_in_provider:"custom",identities:{}}},t);return[ol(JSON.stringify(n)),ol(JSON.stringify(o)),""].join(".")}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function Je(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function wd(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(Je())}function TC(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function bC(){const t=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof t=="object"&&t.id!==void 0}function Tv(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function PC(){const t=Je();return t.indexOf("MSIE ")>=0||t.indexOf("Trident/")>=0}function NC(){return wv.NODE_ADMIN===!0}function RC(){try{return typeof indexedDB=="object"}catch{return!1}}function AC(){return new Promise((t,e)=>{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),t(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var s;e(((s=i.error)===null||s===void 0?void 0:s.message)||"")}}catch(n){e(n)}})}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const OC="FirebaseError";class Yn extends Error{constructor(e,n,r){super(n),this.code=e,this.customData=r,this.name=OC,Object.setPrototypeOf(this,Yn.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,zs.prototype.create)}}class zs{constructor(e,n,r){this.service=e,this.serviceName=n,this.errors=r}create(e,...n){const r=n[0]||{},i=`${this.service}/${e}`,s=this.errors[e],o=s?DC(s,r):"Error",l=`${this.serviceName}: ${o} (${i}).`;return new Yn(i,l,r)}}function DC(t,e){return t.replace(LC,(n,r)=>{const i=e[r];return i!=null?String(i):`<${r}?>`})}const LC=/\{\$([^}]+)}/g;/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function ws(t){return JSON.parse(t)}function Ne(t){return JSON.stringify(t)}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const bv=function(t){let e={},n={},r={},i="";try{const s=t.split(".");e=ws(ll(s[0])||""),n=ws(ll(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch{}return{header:e,claims:n,data:r,signature:i}},MC=function(t){const e=bv(t),n=e.claims;return!!n&&typeof n=="object"&&n.hasOwnProperty("iat")},jC=function(t){const e=bv(t).claims;return typeof e=="object"&&e.admin===!0};/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function Bt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function oi(t,e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]}function Ku(t){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function al(t,e,n){const r={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[i]=e.call(n,t[i],i,t));return r}function ul(t,e){if(t===e)return!0;const n=Object.keys(t),r=Object.keys(e);for(const i of n){if(!r.includes(i))return!1;const s=t[i],o=e[i];if(Of(s)&&Of(o)){if(!ul(s,o))return!1}else if(s!==o)return!1}for(const i of r)if(!n.includes(i))return!1;return!0}function Of(t){return t!==null&&typeof t=="object"}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function yi(t){const e=[];for(const[n,r]of Object.entries(t))Array.isArray(r)?r.forEach(i=>{e.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}):e.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return e.length?"&"+e.join("&"):""}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class FC{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=512/8,this.pad_[0]=128;for(let e=1;e>>31)&4294967295}let i=this.chain_[0],s=this.chain_[1],o=this.chain_[2],l=this.chain_[3],a=this.chain_[4],u,h;for(let d=0;d<80;d++){d<40?d<20?(u=l^s&(o^l),h=1518500249):(u=s^o^l,h=1859775393):d<60?(u=s&o|l&(s|o),h=2400959708):(u=s^o^l,h=3395469782);const f=(i<<5|i>>>27)+u+a+h+r[d]&4294967295;a=l,l=o,o=(s<<30|s>>>2)&4294967295,s=i,i=f}this.chain_[0]=this.chain_[0]+i&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+l&4294967295,this.chain_[4]=this.chain_[4]+a&4294967295}update(e,n){if(e==null)return;n===void 0&&(n=e.length);const r=n-this.blockSize;let i=0;const s=this.buf_;let o=this.inbuf_;for(;i=56;i--)this.buf_[i]=n&255,n/=256;this.compress_(this.buf_);let r=0;for(let i=0;i<5;i++)for(let s=24;s>=0;s-=8)e[r]=this.chain_[i]>>s&255,++r;return e}}function UC(t,e){const n=new zC(t,e);return n.subscribe.bind(n)}class zC{constructor(e,n){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=n,this.task.then(()=>{e(this)}).catch(r=>{this.error(r)})}next(e){this.forEachObserver(n=>{n.next(e)})}error(e){this.forEachObserver(n=>{n.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,n,r){let i;if(e===void 0&&n===void 0&&r===void 0)throw new Error("Missing Observer.");BC(e,["next","error","complete"])?i=e:i={next:e,error:n,complete:r},i.next===void 0&&(i.next=Ua),i.error===void 0&&(i.error=Ua),i.complete===void 0&&(i.complete=Ua);const s=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch{}}),this.observers.push(i),s}unsubscribeOne(e){this.observers===void 0||this.observers[e]===void 0||(delete this.observers[e],this.observerCount-=1,this.observerCount===0&&this.onNoObservers!==void 0&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let n=0;n{if(this.observers!==void 0&&this.observers[e]!==void 0)try{n(this.observers[e])}catch(r){typeof console<"u"&&console.error&&console.error(r)}})}close(e){this.finalized||(this.finalized=!0,e!==void 0&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function BC(t,e){if(typeof t!="object"||t===null)return!1;for(const n of e)if(n in t&&typeof t[n]=="function")return!0;return!1}function Ua(){}function ql(t,e){return`${t} failed: ${e} argument `}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const WC=function(t){const e=[];let n=0;for(let r=0;r=55296&&i<=56319){const s=i-55296;r++,N(r>6|192,e[n++]=i&63|128):i<65536?(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e},Kl=function(t){let e=0;for(let n=0;n=55296&&r<=56319?(e+=4,n++):e+=3}return e};/** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function Et(t){return t&&t._delegate?t._delegate:t}class fr{constructor(e,n,r){this.name=e,this.instanceFactory=n,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}}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Zn="[DEFAULT]";/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class $C{constructor(e,n){this.name=e,this.container=n,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const n=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(n)){const r=new Us;if(this.instancesDeferred.set(n,r),this.isInitialized(n)||this.shouldAutoInitialize())try{const i=this.getOrInitializeService({instanceIdentifier:n});i&&r.resolve(i)}catch{}}return this.instancesDeferred.get(n).promise}getImmediate(e){var n;const r=this.normalizeInstanceIdentifier(e==null?void 0:e.identifier),i=(n=e==null?void 0:e.optional)!==null&&n!==void 0?n:!1;if(this.isInitialized(r)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:r})}catch(s){if(i)return null;throw s}else{if(i)return null;throw Error(`Service ${this.name} is not available`)}}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(HC(e))try{this.getOrInitializeService({instanceIdentifier:Zn})}catch{}for(const[n,r]of this.instancesDeferred.entries()){const i=this.normalizeInstanceIdentifier(n);try{const s=this.getOrInitializeService({instanceIdentifier:i});r.resolve(s)}catch{}}}}clearInstance(e=Zn){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(n=>"INTERNAL"in n).map(n=>n.INTERNAL.delete()),...e.filter(n=>"_delete"in n).map(n=>n._delete())])}isComponentSet(){return this.component!=null}isInitialized(e=Zn){return this.instances.has(e)}getOptions(e=Zn){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:n={}}=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`);const i=this.getOrInitializeService({instanceIdentifier:r,options:n});for(const[s,o]of this.instancesDeferred.entries()){const l=this.normalizeInstanceIdentifier(s);r===l&&o.resolve(i)}return i}onInit(e,n){var r;const i=this.normalizeInstanceIdentifier(n),s=(r=this.onInitCallbacks.get(i))!==null&&r!==void 0?r:new Set;s.add(e),this.onInitCallbacks.set(i,s);const o=this.instances.get(i);return o&&e(o,i),()=>{s.delete(e)}}invokeOnInitCallbacks(e,n){const r=this.onInitCallbacks.get(n);if(r)for(const i of r)try{i(e,n)}catch{}}getOrInitializeService({instanceIdentifier:e,options:n={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:VC(e),options:n}),this.instances.set(e,r),this.instancesOptions.set(e,n),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r)}catch{}return r||null}normalizeInstanceIdentifier(e=Zn){return this.component?this.component.multipleInstances?e:Zn:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function VC(t){return t===Zn?void 0:t}function HC(t){return t.instantiationMode==="EAGER"}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class GC{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const n=this.getProvider(e.name);if(n.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);n.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 n=new $C(e,this);return this.providers.set(e,n),n}getProviders(){return Array.from(this.providers.values())}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */var oe;(function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"})(oe||(oe={}));const qC={debug:oe.DEBUG,verbose:oe.VERBOSE,info:oe.INFO,warn:oe.WARN,error:oe.ERROR,silent:oe.SILENT},KC=oe.INFO,QC={[oe.DEBUG]:"log",[oe.VERBOSE]:"log",[oe.INFO]:"info",[oe.WARN]:"warn",[oe.ERROR]:"error"},YC=(t,e,...n)=>{if(ee.some(n=>t instanceof n);let Df,Lf;function XC(){return Df||(Df=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ZC(){return Lf||(Lf=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Pv=new WeakMap,Qu=new WeakMap,Nv=new WeakMap,za=new WeakMap,Cd=new WeakMap;function eE(t){const e=new Promise((n,r)=>{const i=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o)},s=()=>{n(Dn(t.result)),i()},o=()=>{r(t.error),i()};t.addEventListener("success",s),t.addEventListener("error",o)});return e.then(n=>{n instanceof IDBCursor&&Pv.set(n,t)}).catch(()=>{}),Cd.set(e,t),e}function tE(t){if(Qu.has(t))return;const e=new Promise((n,r)=>{const i=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",o),t.removeEventListener("abort",o)},s=()=>{n(),i()},o=()=>{r(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",s),t.addEventListener("error",o),t.addEventListener("abort",o)});Qu.set(t,e)}let Yu={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return Qu.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Nv.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Dn(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function nE(t){Yu=t(Yu)}function rE(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){const r=t.call(Ba(this),e,...n);return Nv.set(r,e.sort?e.sort():[e]),Dn(r)}:ZC().includes(t)?function(...e){return t.apply(Ba(this),e),Dn(Pv.get(this))}:function(...e){return Dn(t.apply(Ba(this),e))}}function iE(t){return typeof t=="function"?rE(t):(t instanceof IDBTransaction&&tE(t),JC(t,XC())?new Proxy(t,Yu):t)}function Dn(t){if(t instanceof IDBRequest)return eE(t);if(za.has(t))return za.get(t);const e=iE(t);return e!==t&&(za.set(t,e),Cd.set(e,t)),e}const Ba=t=>Cd.get(t);function sE(t,e,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const o=indexedDB.open(t,e),l=Dn(o);return r&&o.addEventListener("upgradeneeded",a=>{r(Dn(o.result),a.oldVersion,a.newVersion,Dn(o.transaction),a)}),n&&o.addEventListener("blocked",a=>n(a.oldVersion,a.newVersion,a)),l.then(a=>{s&&a.addEventListener("close",()=>s()),i&&a.addEventListener("versionchange",u=>i(u.oldVersion,u.newVersion,u))}).catch(()=>{}),l}const oE=["get","getKey","getAll","getAllKeys","count"],lE=["put","add","delete","clear"],Wa=new Map;function Mf(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(Wa.get(e))return Wa.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,i=lE.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||oE.includes(n)))return;const s=async function(o,...l){const a=this.transaction(o,i?"readwrite":"readonly");let u=a.store;return r&&(u=u.index(l.shift())),(await Promise.all([u[n](...l),i&&a.done]))[0]};return Wa.set(e,s),s}nE(t=>({...t,get:(e,n,r)=>Mf(e,n)||t.get(e,n,r),has:(e,n)=>!!Mf(e,n)||t.has(e,n)}));/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class aE{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(n=>{if(uE(n)){const r=n.getImmediate();return`${r.library}/${r.version}`}else return null}).filter(n=>n).join(" ")}}function uE(t){const e=t.getComponent();return(e==null?void 0:e.type)==="VERSION"}const Ju="@firebase/app",jf="0.10.13";/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const rn=new Sd("@firebase/app"),cE="@firebase/app-compat",dE="@firebase/analytics-compat",hE="@firebase/analytics",fE="@firebase/app-check-compat",pE="@firebase/app-check",mE="@firebase/auth",gE="@firebase/auth-compat",vE="@firebase/database",yE="@firebase/data-connect",_E="@firebase/database-compat",wE="@firebase/functions",SE="@firebase/functions-compat",CE="@firebase/installations",EE="@firebase/installations-compat",xE="@firebase/messaging",IE="@firebase/messaging-compat",kE="@firebase/performance",TE="@firebase/performance-compat",bE="@firebase/remote-config",PE="@firebase/remote-config-compat",NE="@firebase/storage",RE="@firebase/storage-compat",AE="@firebase/firestore",OE="@firebase/vertexai-preview",DE="@firebase/firestore-compat",LE="firebase",ME="10.14.1";/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Xu="[DEFAULT]",jE={[Ju]:"fire-core",[cE]:"fire-core-compat",[hE]:"fire-analytics",[dE]:"fire-analytics-compat",[pE]:"fire-app-check",[fE]:"fire-app-check-compat",[mE]:"fire-auth",[gE]:"fire-auth-compat",[vE]:"fire-rtdb",[yE]:"fire-data-connect",[_E]:"fire-rtdb-compat",[wE]:"fire-fn",[SE]:"fire-fn-compat",[CE]:"fire-iid",[EE]:"fire-iid-compat",[xE]:"fire-fcm",[IE]:"fire-fcm-compat",[kE]:"fire-perf",[TE]:"fire-perf-compat",[bE]:"fire-rc",[PE]:"fire-rc-compat",[NE]:"fire-gcs",[RE]:"fire-gcs-compat",[AE]:"fire-fst",[DE]:"fire-fst-compat",[OE]:"fire-vertex","fire-js":"fire-js",[LE]:"fire-js-all"};/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const cl=new Map,FE=new Map,Zu=new Map;function Ff(t,e){try{t.container.addComponent(e)}catch(n){rn.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n)}}function li(t){const e=t.name;if(Zu.has(e))return rn.debug(`There were multiple attempts to register component ${e}.`),!1;Zu.set(e,t);for(const n of cl.values())Ff(n,t);for(const n of FE.values())Ff(n,t);return!0}function Ed(t,e){const n=t.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),t.container.getProvider(e)}function Gt(t){return t.settings!==void 0}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const UE={"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."},Ln=new zs("app","Firebase",UE);/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class zE{constructor(e,n,r){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},n),this._name=n.name,this._automaticDataCollectionEnabled=n.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new fr("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 Ln.create("app-deleted",{appName:this._name})}}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const _i=ME;function Rv(t,e={}){let n=t;typeof e!="object"&&(e={name:e});const r=Object.assign({name:Xu,automaticDataCollectionEnabled:!1},e),i=r.name;if(typeof i!="string"||!i)throw Ln.create("bad-app-name",{appName:String(i)});if(n||(n=Iv()),!n)throw Ln.create("no-options");const s=cl.get(i);if(s){if(ul(n,s.options)&&ul(r,s.config))return s;throw Ln.create("duplicate-app",{appName:i})}const o=new GC(i);for(const a of Zu.values())o.addComponent(a);const l=new zE(n,r,o);return cl.set(i,l),l}function Av(t=Xu){const e=cl.get(t);if(!e&&t===Xu&&Iv())return Rv();if(!e)throw Ln.create("no-app",{appName:t});return e}function Mn(t,e,n){var r;let i=(r=jE[t])!==null&&r!==void 0?r:t;n&&(i+=`-${n}`);const s=i.match(/\s|\//),o=e.match(/\s|\//);if(s||o){const l=[`Unable to register library "${i}" with version "${e}":`];s&&l.push(`library name "${i}" contains illegal characters (whitespace or "/")`),s&&o&&l.push("and"),o&&l.push(`version name "${e}" contains illegal characters (whitespace or "/")`),rn.warn(l.join(" "));return}li(new fr(`${i}-version`,()=>({library:i,version:e}),"VERSION"))}/** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const BE="firebase-heartbeat-database",WE=1,Ss="firebase-heartbeat-store";let $a=null;function Ov(){return $a||($a=sE(BE,WE,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(Ss)}catch(n){console.warn(n)}}}}).catch(t=>{throw Ln.create("idb-open",{originalErrorMessage:t.message})})),$a}async function $E(t){try{const n=(await Ov()).transaction(Ss),r=await n.objectStore(Ss).get(Dv(t));return await n.done,r}catch(e){if(e instanceof Yn)rn.warn(e.message);else{const n=Ln.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});rn.warn(n.message)}}}async function Uf(t,e){try{const r=(await Ov()).transaction(Ss,"readwrite");await r.objectStore(Ss).put(e,Dv(t)),await r.done}catch(n){if(n instanceof Yn)rn.warn(n.message);else{const r=Ln.create("idb-set",{originalErrorMessage:n==null?void 0:n.message});rn.warn(r.message)}}}function Dv(t){return`${t.name}!${t.options.appId}`}/** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const VE=1024,HE=30*24*60*60*1e3;class GE{constructor(e){this.container=e,this._heartbeatsCache=null;const n=this.container.getProvider("app").getImmediate();this._storage=new KE(n),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r))}async triggerHeartbeat(){var e,n;try{const i=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),s=zf();return((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,((n=this._heartbeatsCache)===null||n===void 0?void 0:n.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===s||this._heartbeatsCache.heartbeats.some(o=>o.date===s)?void 0:(this._heartbeatsCache.heartbeats.push({date:s,agent:i}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(o=>{const l=new Date(o.date).valueOf();return Date.now()-l<=HE}),this._storage.overwrite(this._heartbeatsCache))}catch(r){rn.warn(r)}}async getHeartbeatsHeader(){var e;try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null||this._heartbeatsCache.heartbeats.length===0)return"";const n=zf(),{heartbeatsToSend:r,unsentEntries:i}=qE(this._heartbeatsCache.heartbeats),s=ol(JSON.stringify({version:2,heartbeats:r}));return this._heartbeatsCache.lastSentHeartbeatDate=n,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),s}catch(n){return rn.warn(n),""}}}function zf(){return new Date().toISOString().substring(0,10)}function qE(t,e=VE){const n=[];let r=t.slice();for(const i of t){const s=n.find(o=>o.agent===i.agent);if(s){if(s.dates.push(i.date),Bf(n)>e){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),Bf(n)>e){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}class KE{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return RC()?AC().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const n=await $E(this.app);return n!=null&&n.heartbeats?n:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){var n;if(await this._canUseIndexedDBPromise){const i=await this.read();return Uf(this.app,{lastSentHeartbeatDate:(n=e.lastSentHeartbeatDate)!==null&&n!==void 0?n:i.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){var n;if(await this._canUseIndexedDBPromise){const i=await this.read();return Uf(this.app,{lastSentHeartbeatDate:(n=e.lastSentHeartbeatDate)!==null&&n!==void 0?n:i.lastSentHeartbeatDate,heartbeats:[...i.heartbeats,...e.heartbeats]})}else return}}function Bf(t){return ol(JSON.stringify({version:2,heartbeats:t})).length}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function QE(t){li(new fr("platform-logger",e=>new aE(e),"PRIVATE")),li(new fr("heartbeat",e=>new GE(e),"PRIVATE")),Mn(Ju,jf,t),Mn(Ju,jf,"esm2017"),Mn("fire-js","")}QE("");var YE="firebase",JE="10.14.1";/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */Mn(YE,JE,"app");var Wf={};const $f="@firebase/database",Vf="1.0.8";/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */let Lv="";function XE(t){Lv=t}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class ZE{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,n){n==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),Ne(n))}get(e){const n=this.domStorage_.getItem(this.prefixedName_(e));return n==null?null:ws(n)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class ex{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,n){n==null?delete this.cache_[e]:this.cache_[e]=n}get(e){return Bt(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Mv=function(t){try{if(typeof window<"u"&&typeof window[t]<"u"){const e=window[t];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new ZE(e)}}catch{}return new ex},ir=Mv("localStorage"),tx=Mv("sessionStorage");/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Kr=new Sd("@firebase/database"),nx=function(){let t=1;return function(){return t++}}(),jv=function(t){const e=WC(t),n=new FC;n.update(e);const r=n.digest();return yd.encodeByteArray(r)},Bs=function(...t){let e="";for(let n=0;n{document.readyState==="complete"&&n()}),window.attachEvent("onload",n))}},ai="[MIN_NAME]",pr="[MAX_NAME]",Cr=function(t,e){if(t===e)return 0;if(t===ai||e===pr)return-1;if(e===ai||t===pr)return 1;{const n=Gf(t),r=Gf(e);return n!==null?r!==null?n-r===0?t.length-e.length:n-r:-1:r!==null?1:tn?r.push(t.substring(i,n)):r.push(t.substring(i,i+e));return r};function ze(t,e){for(const n in t)t.hasOwnProperty(n)&&e(n,t[n])}const Uv=function(t){N(!xd(t),"Invalid JSON number");const e=11,n=52,r=(1<=Math.pow(2,1-r)?(l=Math.min(Math.floor(Math.log(t)/Math.LN2),r),s=l+r,o=Math.round(t*Math.pow(2,n-l)-Math.pow(2,n))):(s=0,o=Math.round(t/Math.pow(2,1-r-n))));const u=[];for(a=n;a;a-=1)u.push(o%2?1:0),o=Math.floor(o/2);for(a=e;a;a-=1)u.push(s%2?1:0),s=Math.floor(s/2);u.push(i?1:0),u.reverse();const h=u.join("");let d="";for(a=0;a<64;a+=8){let f=parseInt(h.substr(a,8),2).toString(16);f.length===1&&(f="0"+f),d=d+f}return d.toLowerCase()},lx=function(){return!!(typeof window=="object"&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},ax=function(){return typeof Windows=="object"&&typeof Windows.UI=="object"};function ux(t,e){let n="Unknown Error";t==="too_big"?n="The data requested exceeds the maximum size that can be accessed with a single request.":t==="permission_denied"?n="Client doesn't have permission to access the desired data.":t==="unavailable"&&(n="The service is unavailable");const r=new Error(t+" at "+e._path.toString()+": "+n);return r.code=t.toUpperCase(),r}const cx=new RegExp("^-?(0*)\\d{1,10}$"),dx=-2147483648,hx=2147483647,Gf=function(t){if(cx.test(t)){const e=Number(t);if(e>=dx&&e<=hx)return e}return null},wi=function(t){try{t()}catch(e){setTimeout(()=>{const n=e.stack||"";throw Ye("Exception was thrown by user callback.",n),e},Math.floor(0))}},fx=function(){return(typeof window=="object"&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},Yi=function(t,e){const n=setTimeout(t,e);return typeof n=="number"&&typeof Deno<"u"&&Deno.unrefTimer?Deno.unrefTimer(n):typeof n=="object"&&n.unref&&n.unref(),n};/** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class px{constructor(e,n){this.appName_=e,this.appCheckProvider=n,this.appCheck=n==null?void 0:n.getImmediate({optional:!0}),this.appCheck||n==null||n.get().then(r=>this.appCheck=r)}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise((n,r)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(n,r):n(null)},0)})}addTokenChangeListener(e){var n;(n=this.appCheckProvider)===null||n===void 0||n.get().then(r=>r.addTokenListener(e))}notifyForInvalidToken(){Ye(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class mx{constructor(e,n,r){this.appName_=e,this.firebaseOptions_=n,this.authProvider_=r,this.auth_=null,this.auth_=r.getImmediate({optional:!0}),this.auth_||r.onInit(i=>this.auth_=i)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(n=>n&&n.code==="auth/token-not-initialized"?(je("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(n)):new Promise((n,r)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(n,r):n(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(n=>n.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(n=>n.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/.',Ye(e)}}class Po{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Po.OWNER="owner";/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const kd="5",zv="v",Bv="s",Wv="r",$v="f",Vv=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Hv="ls",Gv="p",tc="ac",qv="websocket",Kv="long_polling";/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Qv{constructor(e,n,r,i,s=!1,o="",l=!1,a=!1){this.secure=n,this.namespace=r,this.webSocketOnly=i,this.nodeAdmin=s,this.persistenceKey=o,this.includeNamespaceInQueryParams=l,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ir.get("host:"+e)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)==="s-"}isCustomHost(){return this._domain!=="firebaseio.com"&&this._domain!=="firebaseio-demo.com"}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&ir.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://",n=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${n}`}}function gx(t){return t.host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams}function Yv(t,e,n){N(typeof e=="string","typeof type must == string"),N(typeof n=="object","typeof params must == object");let r;if(e===qv)r=(t.secure?"wss://":"ws://")+t.internalHost+"/.ws?";else if(e===Kv)r=(t.secure?"https://":"http://")+t.internalHost+"/.lp?";else throw new Error("Unknown connection type: "+e);gx(t)&&(n.ns=t.namespace);const i=[];return ze(n,(s,o)=>{i.push(s+"="+o)}),r+i.join("&")}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class vx{constructor(){this.counters_={}}incrementCounter(e,n=1){Bt(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=n}get(){return _C(this.counters_)}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Va={},Ha={};function Td(t){const e=t.toString();return Va[e]||(Va[e]=new vx),Va[e]}function yx(t,e){const n=t.toString();return Ha[n]||(Ha[n]=e()),Ha[n]}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class _x{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,n){this.closeAfterResponse=e,this.onClose=n,this.closeAfterResponse{this.onMessage_(r[i])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const qf="start",wx="close",Sx="pLPCommand",Cx="pRTLPCB",Jv="id",Xv="pw",Zv="ser",Ex="cb",xx="seg",Ix="ts",kx="d",Tx="dframe",ey=1870,ty=30,bx=ey-ty,Px=25e3,Nx=3e4;class zr{constructor(e,n,r,i,s,o,l){this.connId=e,this.repoInfo=n,this.applicationId=r,this.appCheckToken=i,this.authToken=s,this.transportSessionId=o,this.lastSessionId=l,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Ws(e),this.stats_=Td(n),this.urlFn=a=>(this.appCheckToken&&(a[tc]=this.appCheckToken),Yv(n,Kv,a))}open(e,n){this.curSegmentNum=0,this.onDisconnect_=n,this.myPacketOrderer=new _x(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(Nx)),sx(()=>{if(this.isClosed_)return;this.scriptTagHolder=new bd((...s)=>{const[o,l,a,u,h]=s;if(this.incrementIncomingBytes_(s),!!this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,o===qf)this.id=l,this.password=a;else if(o===wx)l?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(l,()=>{this.onClosed_()})):this.onClosed_();else throw new Error("Unrecognized command received: "+o)},(...s)=>{const[o,l]=s;this.incrementIncomingBytes_(s),this.myPacketOrderer.handleResponse(o,l)},()=>{this.onClosed_()},this.urlFn);const r={};r[qf]="t",r[Zv]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(r[Ex]=this.scriptTagHolder.uniqueCallbackIdentifier),r[zv]=kd,this.transportSessionId&&(r[Bv]=this.transportSessionId),this.lastSessionId&&(r[Hv]=this.lastSessionId),this.applicationId&&(r[Gv]=this.applicationId),this.appCheckToken&&(r[tc]=this.appCheckToken),typeof location<"u"&&location.hostname&&Vv.test(location.hostname)&&(r[Wv]=$v);const i=this.urlFn(r);this.log_("Connecting via long-poll to "+i),this.scriptTagHolder.addTag(i,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){zr.forceAllow_=!0}static forceDisallow(){zr.forceDisallow_=!0}static isAvailable(){return zr.forceAllow_?!0:!zr.forceDisallow_&&typeof document<"u"&&document.createElement!=null&&!lx()&&!ax()}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 n=Ne(e);this.bytesSent+=n.length,this.stats_.incrementCounter("bytes_sent",n.length);const r=Cv(n),i=Fv(r,bx);for(let s=0;sdocument.domain="'+document.domain+'";<\/script>');const o=""+s+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(o),this.myIFrame.doc.close()}catch(l){je("frame writing exception"),l.stack&&je(l.stack),je(l)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||je("No IE domain setting required")}catch{const r=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+r+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";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(()=>{this.myIFrame!==null&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,n){for(this.myID=e,this.myPW=n,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[Jv]=this.myID,e[Xv]=this.myPW,e[Zv]=this.currentSerial;let n=this.urlFn(e),r="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+ty+r.length<=ey;){const o=this.pendingSegs.shift();r=r+"&"+xx+i+"="+o.seg+"&"+Ix+i+"="+o.ts+"&"+kx+i+"="+o.d,i++}return n=n+r,this.addLongPollTag_(n,this.currentSerial),!0}else return!1}enqueueSegment(e,n,r){this.pendingSegs.push({seg:e,ts:n,d:r}),this.alive&&this.newRequest_()}addLongPollTag_(e,n){this.outstandingRequests.add(n);const r=()=>{this.outstandingRequests.delete(n),this.newRequest_()},i=setTimeout(r,Math.floor(Px)),s=()=>{clearTimeout(i),r()};this.addTag(e,s)}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const r=this.myIFrame.doc.createElement("script");r.type="text/javascript",r.async=!0,r.src=e,r.onload=r.onreadystatechange=function(){const i=r.readyState;(!i||i==="loaded"||i==="complete")&&(r.onload=r.onreadystatechange=null,r.parentNode&&r.parentNode.removeChild(r),n())},r.onerror=()=>{je("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(r)}catch{}},Math.floor(1))}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Rx=16384,Ax=45e3;let dl=null;typeof MozWebSocket<"u"?dl=MozWebSocket:typeof WebSocket<"u"&&(dl=WebSocket);class bt{constructor(e,n,r,i,s,o,l){this.connId=e,this.applicationId=r,this.appCheckToken=i,this.authToken=s,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Ws(this.connId),this.stats_=Td(n),this.connURL=bt.connectionURL_(n,o,l,i,r),this.nodeAdmin=n.nodeAdmin}static connectionURL_(e,n,r,i,s){const o={};return o[zv]=kd,typeof location<"u"&&location.hostname&&Vv.test(location.hostname)&&(o[Wv]=$v),n&&(o[Bv]=n),r&&(o[Hv]=r),i&&(o[tc]=i),s&&(o[Gv]=s),Yv(e,qv,o)}open(e,n){this.onDisconnect=n,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ir.set("previous_websocket_failure",!0);try{let r;NC(),this.mySock=new dl(this.connURL,[],r)}catch(r){this.log_("Error instantiating WebSocket.");const i=r.message||r.data;i&&this.log_(i),this.onClosed_();return}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=r=>{this.handleIncomingFrame(r)},this.mySock.onerror=r=>{this.log_("WebSocket error. Closing connection.");const i=r.message||r.data;i&&this.log_(i),this.onClosed_()}}start(){}static forceDisallow(){bt.forceDisallow_=!0}static isAvailable(){let e=!1;if(typeof navigator<"u"&&navigator.userAgent){const n=/Android ([0-9]{0,}\.[0-9]{0,})/,r=navigator.userAgent.match(n);r&&r.length>1&&parseFloat(r[1])<4.4&&(e=!0)}return!e&&dl!==null&&!bt.forceDisallow_}static previouslyFailed(){return ir.isInMemoryStorage||ir.get("previous_websocket_failure")===!0}markConnectionHealthy(){ir.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const n=this.frames.join("");this.frames=null;const r=ws(n);this.onMessage(r)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(N(this.frames===null,"We already have a frame buffer"),e.length<=6){const n=Number(e);if(!isNaN(n))return this.handleNewFrameCount_(n),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(this.mySock===null)return;const n=e.data;if(this.bytesReceived+=n.length,this.stats_.incrementCounter("bytes_received",n.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(n);else{const r=this.extractFrameCount_(n);r!==null&&this.appendFrame_(r)}}send(e){this.resetKeepAlive();const n=Ne(e);this.bytesSent+=n.length,this.stats_.incrementCounter("bytes_sent",n.length);const r=Fv(n,Rx);r.length>1&&this.sendString_(String(r.length));for(let i=0;i{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(Ax))}sendString_(e){try{this.mySock.send(e)}catch(n){this.log_("Exception thrown from WebSocket.send():",n.message||n.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}bt.responsesRequiredToBeHealthy=2;bt.healthyTimeout=3e4;/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Cs{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[zr,bt]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){const n=bt&&bt.isAvailable();let r=n&&!bt.previouslyFailed();if(e.webSocketOnly&&(n||Ye("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),r=!0),r)this.transports_=[bt];else{const i=this.transports_=[];for(const s of Cs.ALL_TRANSPORTS)s&&s.isAvailable()&&i.push(s);Cs.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}}Cs.globalTransportInitialized_=!1;/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Ox=6e4,Dx=5e3,Lx=10*1024,Mx=100*1024,Ga="t",Kf="d",jx="s",Qf="r",Fx="e",Yf="o",Jf="a",Xf="n",Zf="p",Ux="h";class zx{constructor(e,n,r,i,s,o,l,a,u,h){this.id=e,this.repoInfo_=n,this.applicationId_=r,this.appCheckToken_=i,this.authToken_=s,this.onMessage_=o,this.onReady_=l,this.onDisconnect_=a,this.onKill_=u,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Ws("c:"+this.id+":"),this.transportManager_=new Cs(n),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 n=this.connReceiver_(this.conn_),r=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(n,r)},Math.floor(0));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=Yi(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>Mx?(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>Lx?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(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return n=>{e===this.conn_?this.onConnectionLost_(n):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return n=>{this.state_!==2&&(e===this.rx_?this.onPrimaryMessageReceived_(n):e===this.secondaryConn_?this.onSecondaryMessageReceived_(n):this.log_("message on old connection"))}}sendRequest(e){const n={t:"d",d:e};this.sendData_(n)}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(Ga in e){const n=e[Ga];n===Jf?this.upgradeIfSecondaryHealthy_():n===Qf?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):n===Yf&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const n=Ai("t",e),r=Ai("d",e);if(n==="c")this.onSecondaryControl_(r);else if(n==="d")this.pendingDataMessages.push(r);else throw new Error("Unknown protocol layer: "+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:Zf,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:Jf,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:Xf,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const n=Ai("t",e),r=Ai("d",e);n==="c"?this.onControl_(r):n==="d"&&this.onDataMessage_(r)}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 n=Ai(Ga,e);if(Kf in e){const r=e[Kf];if(n===Ux){const i=Object.assign({},r);this.repoInfo_.isUsingEmulator&&(i.h=this.repoInfo_.host),this.onHandshake_(i)}else if(n===Xf){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let i=0;i{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(Ox))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,this.state_===1?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,n){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(n,this.sessionId),this.onReady_=null),this.primaryResponsesRequired_===0?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Yi(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(Dx))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:Zf,d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,!e&&this.state_===0?(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(ir.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)):this.state_===1&&this.log_("Realtime connection lost."),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(this.state_!==1)throw"Connection is not connected";this.tx_.send(e)}close(){this.state_!==2&&(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)}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class ny{put(e,n,r,i){}merge(e,n,r,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,n,r){}onDisconnectMerge(e,n,r){}onDisconnectCancel(e,n){}reportStats(e){}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class ry{constructor(e){this.allowedEvents_=e,this.listeners_={},N(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...n){if(Array.isArray(this.listeners_[e])){const r=[...this.listeners_[e]];for(let i=0;in===e),"Unknown event: "+e)}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class hl extends ry{constructor(){super(["online"]),this.online_=!0,typeof window<"u"&&typeof window.addEventListener<"u"&&!wd()&&(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))}static getInstance(){return new hl}getInitialEvent(e){return N(e==="online","Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const ep=32,tp=768;class le{constructor(e,n){if(n===void 0){this.pieces_=e.split("/");let r=0;for(let i=0;i0&&(this.pieces_[r]=this.pieces_[i],r++);this.pieces_.length=r,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=n}toString(){let e="";for(let n=this.pieceNum_;n=t.pieces_.length?null:t.pieces_[t.pieceNum_]}function Wn(t){return t.pieces_.length-t.pieceNum_}function ue(t){let e=t.pieceNum_;return e=t.pieces_.length)return null;const e=[];for(let n=t.pieceNum_;n0&&n.push(r[i])}return new le(n,0)}function H(t){return t.pieceNum_>=t.pieces_.length}function Ke(t,e){const n=$(t),r=$(e);if(n===null)return e;if(n===r)return Ke(ue(t),ue(e));throw new Error("INTERNAL ERROR: innerPath ("+e+") is not within outerPath ("+t+")")}function Wx(t,e){const n=Es(t,0),r=Es(e,0);for(let i=0;iWn(e))return!1;for(;n0&&(t.byteLength_+=1),t.parts_.push(e),t.byteLength_+=Kl(e),sy(t)}function Hx(t){const e=t.parts_.pop();t.byteLength_-=Kl(e),t.parts_.length>0&&(t.byteLength_-=1)}function sy(t){if(t.byteLength_>tp)throw new Error(t.errorPrefix_+"has a key path longer than "+tp+" bytes ("+t.byteLength_+").");if(t.parts_.length>ep)throw new Error(t.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+ep+") or object contains a cycle "+er(t))}function er(t){return t.parts_.length===0?"":"in property '"+t.parts_.join(".")+"'"}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Rd extends ry{constructor(){super(["visible"]);let e,n;typeof document<"u"&&typeof document.addEventListener<"u"&&(typeof document.hidden<"u"?(n="visibilitychange",e="hidden"):typeof document.mozHidden<"u"?(n="mozvisibilitychange",e="mozHidden"):typeof document.msHidden<"u"?(n="msvisibilitychange",e="msHidden"):typeof document.webkitHidden<"u"&&(n="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,n&&document.addEventListener(n,()=>{const r=!document[e];r!==this.visible_&&(this.visible_=r,this.trigger("visible",r))},!1)}static getInstance(){return new Rd}getInitialEvent(e){return N(e==="visible","Unknown event type: "+e),[this.visible_]}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Oi=1e3,Gx=60*5*1e3,np=30*1e3,qx=1.3,Kx=3e4,Qx="server_kill",rp=3;class Xt extends ny{constructor(e,n,r,i,s,o,l,a){if(super(),this.repoInfo_=e,this.applicationId_=n,this.onDataUpdate_=r,this.onConnectStatus_=i,this.onServerInfoUpdate_=s,this.authTokenProvider_=o,this.appCheckTokenProvider_=l,this.authOverride_=a,this.id=Xt.nextPersistentConnectionId_++,this.log_=Ws("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_=Oi,this.maxReconnectDelay_=Gx,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)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Rd.getInstance().on("visible",this.onVisible_,this),e.host.indexOf("fblocal")===-1&&hl.getInstance().on("online",this.onOnline_,this)}sendRequest(e,n,r){const i=++this.requestNumber_,s={r:i,a:e,b:n};this.log_(Ne(s)),N(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(s),r&&(this.requestCBHash_[i]=r)}get(e){this.initConnection_();const n=new Us,i={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:o=>{const l=o.d;o.s==="ok"?n.resolve(l):n.reject(l)}};this.outstandingGets_.push(i),this.outstandingGetCount_++;const s=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(s),n.promise}listen(e,n,r,i){this.initConnection_();const s=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+s),this.listens.has(o)||this.listens.set(o,new Map),N(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),N(!this.listens.get(o).has(s),"listen() called twice for same path/queryId.");const l={onComplete:i,hashFn:n,query:e,tag:r};this.listens.get(o).set(s,l),this.connected_&&this.sendListen_(l)}sendGet_(e){const n=this.outstandingGets_[e];this.sendRequest("g",n.request,r=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(r)})}sendListen_(e){const n=e.query,r=n._path.toString(),i=n._queryIdentifier;this.log_("Listen on "+r+" for "+i);const s={p:r},o="q";e.tag&&(s.q=n._queryObject,s.t=e.tag),s.h=e.hashFn(),this.sendRequest(o,s,l=>{const a=l.d,u=l.s;Xt.warnOnListenWarnings_(a,n),(this.listens.get(r)&&this.listens.get(r).get(i))===e&&(this.log_("listen response",l),u!=="ok"&&this.removeListen_(r,i),e.onComplete&&e.onComplete(u,a))})}static warnOnListenWarnings_(e,n){if(e&&typeof e=="object"&&Bt(e,"w")){const r=oi(e,"w");if(Array.isArray(r)&&~r.indexOf("no_index")){const i='".indexOn": "'+n._queryParams.getIndex().toString()+'"',s=n._path.toString();Ye(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${i} at ${s} 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&&e.length===40||jC(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=np)}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_,n=MC(e)?"auth":"gauth",r={cred:e};this.authOverride_===null?r.noauth=!0:typeof this.authOverride_=="object"&&(r.authvar=this.authOverride_),this.sendRequest(n,r,i=>{const s=i.s,o=i.d||"error";this.authToken_===e&&(s==="ok"?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(s,o))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{const n=e.s,r=e.d||"error";n==="ok"?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(n,r)})}unlisten(e,n){const r=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+r+" "+i),N(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(r,i)&&this.connected_&&this.sendUnlisten_(r,i,e._queryObject,n)}sendUnlisten_(e,n,r,i){this.log_("Unlisten on "+e+" for "+n);const s={p:e},o="n";i&&(s.q=r,s.t=i),this.sendRequest(o,s)}onDisconnectPut(e,n,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,n,r):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:n,onComplete:r})}onDisconnectMerge(e,n,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,n,r):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:n,onComplete:r})}onDisconnectCancel(e,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:n})}sendOnDisconnect_(e,n,r,i){const s={p:n,d:r};this.log_("onDisconnect "+e,s),this.sendRequest(e,s,o=>{i&&setTimeout(()=>{i(o.s,o.d)},Math.floor(0))})}put(e,n,r,i){this.putInternal("p",e,n,r,i)}merge(e,n,r,i){this.putInternal("m",e,n,r,i)}putInternal(e,n,r,i,s){this.initConnection_();const o={p:n,d:r};s!==void 0&&(o.h=s),this.outstandingPuts_.push({action:e,request:o,onComplete:i}),this.outstandingPutCount_++;const l=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(l):this.log_("Buffering put: "+n)}sendPut_(e){const n=this.outstandingPuts_[e].action,r=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(n,r,s=>{this.log_(n+" response",s),delete this.outstandingPuts_[e],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),i&&i(s.s,s.d)})}reportStats(e){if(this.connected_){const n={c:e};this.log_("reportStats",n),this.sendRequest("s",n,r=>{if(r.s!=="ok"){const s=r.d;this.log_("reportStats","Error sending stats: "+s)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+Ne(e));const n=e.r,r=this.requestCBHash_[n];r&&(delete this.requestCBHash_[n],r(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,n){this.log_("handleServerMessage",e,n),e==="d"?this.onDataUpdate_(n.p,n.d,!1,n.t):e==="m"?this.onDataUpdate_(n.p,n.d,!0,n.t):e==="c"?this.onListenRevoked_(n.p,n.q):e==="ac"?this.onAuthRevoked_(n.s,n.d):e==="apc"?this.onAppCheckRevoked_(n.s,n.d):e==="sd"?this.onSecurityDebugPacket_(n):ec("Unrecognized action received from server: "+Ne(e)+` -Are you using the latest client?`)}onReady_(e,n){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(e),this.lastSessionId=n,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){N(!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_=Oi,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=Oi,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_()){this.visible_?this.lastConnectionEstablishedTime_&&(new Date().getTime()-this.lastConnectionEstablishedTime_>Kx&&(this.reconnectDelay_=Oi),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());const e=new Date().getTime()-this.lastConnectionAttemptTime_;let n=Math.max(0,this.reconnectDelay_-e);n=Math.random()*n,this.log_("Trying to reconnect in "+n+"ms"),this.scheduleConnect_(n),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*qx)}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),n=this.onReady_.bind(this),r=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+Xt.nextConnectionId_++,s=this.lastSessionId;let o=!1,l=null;const a=function(){l?l.close():(o=!0,r())},u=function(d){N(l,"sendRequest call when we're not connected not allowed."),l.sendRequest(d)};this.realtime_={close:a,sendRequest:u};const h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[d,f]=await Promise.all([this.authTokenProvider_.getToken(h),this.appCheckTokenProvider_.getToken(h)]);o?je("getToken() completed but was canceled"):(je("getToken() completed. Creating connection."),this.authToken_=d&&d.accessToken,this.appCheckToken_=f&&f.token,l=new zx(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,n,r,v=>{Ye(v+" ("+this.repoInfo_.toString()+")"),this.interrupt(Qx)},s))}catch(d){this.log_("Failed to get token: "+d),o||(this.repoInfo_.nodeAdmin&&Ye(d),a())}}}interrupt(e){je("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){je("Resuming connection for reason: "+e),delete this.interruptReasons_[e],Ku(this.interruptReasons_)&&(this.reconnectDelay_=Oi,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const n=e-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:n})}cancelSentTransactions_(){for(let e=0;eId(s)).join("$"):r="default";const i=this.removeListen_(e,r);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,n){const r=new le(e).toString();let i;if(this.listens.has(r)){const s=this.listens.get(r);i=s.get(n),s.delete(n),s.size===0&&this.listens.delete(r)}else i=void 0;return i}onAuthRevoked_(e,n){je("Auth token revoked: "+e+"/"+n),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(e==="invalid_token"||e==="permission_denied")&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=rp&&(this.reconnectDelay_=np,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,n){je("App check token revoked: "+e+"/"+n),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(e==="invalid_token"||e==="permission_denied")&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=rp&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace(` -`,` -FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const n of e.values())this.sendListen_(n);for(let e=0;e0}peek(){if(this.nodeStack_.length===0)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 De{constructor(e,n,r,i,s){this.key=e,this.value=n,this.color=r??De.RED,this.left=i??st.EMPTY_NODE,this.right=s??st.EMPTY_NODE}copy(e,n,r,i,s){return new De(e??this.key,n??this.value,r??this.color,i??this.left,s??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,n,r){let i=this;const s=r(e,i.key);return s<0?i=i.copy(null,null,null,i.left.insert(e,n,r),null):s===0?i=i.copy(null,n,null,null,null):i=i.copy(null,null,null,null,i.right.insert(e,n,r)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return st.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,n){let r,i;if(r=this,n(e,r.key)<0)!r.left.isEmpty()&&!r.left.isRed_()&&!r.left.left.isRed_()&&(r=r.moveRedLeft_()),r=r.copy(null,null,null,r.left.remove(e,n),null);else{if(r.left.isRed_()&&(r=r.rotateRight_()),!r.right.isEmpty()&&!r.right.isRed_()&&!r.right.left.isRed_()&&(r=r.moveRedRight_()),n(e,r.key)===0){if(r.right.isEmpty())return st.EMPTY_NODE;i=r.right.min_(),r=r.copy(i.key,i.value,null,null,r.right.removeMin_())}r=r.copy(null,null,null,null,r.right.remove(e,n))}return r.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,De.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,De.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),n=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,n)}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)}}De.RED=!0;De.BLACK=!1;class Yx{copy(e,n,r,i,s){return this}insert(e,n,r){return new De(e,n,null)}remove(e,n){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}}class st{constructor(e,n=st.EMPTY_NODE){this.comparator_=e,this.root_=n}insert(e,n){return new st(this.comparator_,this.root_.insert(e,n,this.comparator_).copy(null,null,De.BLACK,null,null))}remove(e){return new st(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,De.BLACK,null,null))}get(e){let n,r=this.root_;for(;!r.isEmpty();){if(n=this.comparator_(e,r.key),n===0)return r.value;n<0?r=r.left:n>0&&(r=r.right)}return null}getPredecessorKey(e){let n,r=this.root_,i=null;for(;!r.isEmpty();)if(n=this.comparator_(e,r.key),n===0){if(r.left.isEmpty())return i?i.key:null;for(r=r.left;!r.right.isEmpty();)r=r.right;return r.key}else n<0?r=r.left:n>0&&(i=r,r=r.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 mo(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,n){return new mo(this.root_,e,this.comparator_,!1,n)}getReverseIteratorFrom(e,n){return new mo(this.root_,e,this.comparator_,!0,n)}getReverseIterator(e){return new mo(this.root_,null,this.comparator_,!0,e)}}st.EMPTY_NODE=new Yx;/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function Jx(t,e){return Cr(t.name,e.name)}function Ad(t,e){return Cr(t,e)}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */let nc;function Xx(t){nc=t}const ly=function(t){return typeof t=="number"?"number:"+Uv(t):"string:"+t},ay=function(t){if(t.isLeafNode()){const e=t.val();N(typeof e=="string"||typeof e=="number"||typeof e=="object"&&Bt(e,".sv"),"Priority must be a string or number.")}else N(t===nc||t.isEmpty(),"priority of unexpected type.");N(t===nc||t.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */let ip;class Ae{constructor(e,n=Ae.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=n,this.lazyHash_=null,N(this.value_!==void 0&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value."),ay(this.priorityNode_)}static set __childrenNodeConstructor(e){ip=e}static get __childrenNodeConstructor(){return ip}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Ae(this.value_,e)}getImmediateChild(e){return e===".priority"?this.priorityNode_:Ae.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return H(e)?this:$(e)===".priority"?this.priorityNode_:Ae.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,n){return null}updateImmediateChild(e,n){return e===".priority"?this.updatePriority(n):n.isEmpty()&&e!==".priority"?this:Ae.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,n).updatePriority(this.priorityNode_)}updateChild(e,n){const r=$(e);return r===null?n:n.isEmpty()&&r!==".priority"?this:(N(r!==".priority"||Wn(e)===1,".priority must be the last token in a path"),this.updateImmediateChild(r,Ae.__childrenNodeConstructor.EMPTY_NODE.updateChild(ue(e),n)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,n){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+ly(this.priorityNode_.val())+":");const n=typeof this.value_;e+=n+":",n==="number"?e+=Uv(this.value_):e+=this.value_,this.lazyHash_=jv(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Ae.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Ae.__childrenNodeConstructor?-1:(N(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const n=typeof e.value_,r=typeof this.value_,i=Ae.VALUE_TYPE_ORDER.indexOf(n),s=Ae.VALUE_TYPE_ORDER.indexOf(r);return N(i>=0,"Unknown leaf type: "+n),N(s>=0,"Unknown leaf type: "+r),i===s?r==="object"?0:this.value_parseInt(Math.log(s)/nI,10),r=s=>parseInt(Array(s+1).join("1"),2);this.count=n(e+1),this.current_=this.count-1;const i=r(this.count);this.bits_=e+1&i}nextBitIsOne(){const e=!(this.bits_&1<{const o=oi(this.indexSet_,s);if(N(o,"Missing index implementation for "+s),i===Tr)if(o.isDefinedOn(e.node)){const l=[],a=n.getIterator(V.Wrap);let u=a.getNext();for(;u;)u.name!==e.name&&l.push(u),u=a.getNext();return l.push(e),fl(l,o.getCompare())}else return Tr;else{const l=n.get(e.name);let a=i;return l&&(a=a.remove(new V(e.name,l))),a.insert(e,e.node)}});return new qt(r,this.indexSet_)}removeFromIndexes(e,n){const r=al(this.indexes_,i=>{if(i===Tr)return i;{const s=n.get(e.name);return s?i.remove(new V(e.name,s)):i}});return new qt(r,this.indexSet_)}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */let Di;class B{constructor(e,n,r){this.children_=e,this.priorityNode_=n,this.indexMap_=r,this.lazyHash_=null,this.priorityNode_&&ay(this.priorityNode_),this.children_.isEmpty()&&N(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return Di||(Di=new B(new st(Ad),null,qt.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Di}updatePriority(e){return this.children_.isEmpty()?this:new B(this.children_,e,this.indexMap_)}getImmediateChild(e){if(e===".priority")return this.getPriority();{const n=this.children_.get(e);return n===null?Di:n}}getChild(e){const n=$(e);return n===null?this:this.getImmediateChild(n).getChild(ue(e))}hasChild(e){return this.children_.get(e)!==null}updateImmediateChild(e,n){if(N(n,"We should always be passing snapshot nodes"),e===".priority")return this.updatePriority(n);{const r=new V(e,n);let i,s;n.isEmpty()?(i=this.children_.remove(e),s=this.indexMap_.removeFromIndexes(r,this.children_)):(i=this.children_.insert(e,n),s=this.indexMap_.addToIndexes(r,this.children_));const o=i.isEmpty()?Di:this.priorityNode_;return new B(i,o,s)}}updateChild(e,n){const r=$(e);if(r===null)return n;{N($(e)!==".priority"||Wn(e)===1,".priority must be the last token in a path");const i=this.getImmediateChild(r).updateChild(ue(e),n);return this.updateImmediateChild(r,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const n={};let r=0,i=0,s=!0;if(this.forEachChild(we,(o,l)=>{n[o]=l.val(e),r++,s&&B.INTEGER_REGEXP_.test(o)?i=Math.max(i,Number(o)):s=!1}),!e&&s&&i<2*r){const o=[];for(const l in n)o[l]=n[l];return o}else return e&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n}hash(){if(this.lazyHash_===null){let e="";this.getPriority().isEmpty()||(e+="priority:"+ly(this.getPriority().val())+":"),this.forEachChild(we,(n,r)=>{const i=r.hash();i!==""&&(e+=":"+n+":"+i)}),this.lazyHash_=e===""?"":jv(e)}return this.lazyHash_}getPredecessorChildName(e,n,r){const i=this.resolveIndex_(r);if(i){const s=i.getPredecessorKey(new V(e,n));return s?s.name:null}else return this.children_.getPredecessorKey(e)}getFirstChildName(e){const n=this.resolveIndex_(e);if(n){const r=n.minKey();return r&&r.name}else return this.children_.minKey()}getFirstChild(e){const n=this.getFirstChildName(e);return n?new V(n,this.children_.get(n)):null}getLastChildName(e){const n=this.resolveIndex_(e);if(n){const r=n.maxKey();return r&&r.name}else return this.children_.maxKey()}getLastChild(e){const n=this.getLastChildName(e);return n?new V(n,this.children_.get(n)):null}forEachChild(e,n){const r=this.resolveIndex_(e);return r?r.inorderTraversal(i=>n(i.name,i.node)):this.children_.inorderTraversal(n)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,n){const r=this.resolveIndex_(n);if(r)return r.getIteratorFrom(e,i=>i);{const i=this.children_.getIteratorFrom(e.name,V.Wrap);let s=i.peek();for(;s!=null&&n.compare(s,e)<0;)i.getNext(),s=i.peek();return i}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,n){const r=this.resolveIndex_(n);if(r)return r.getReverseIteratorFrom(e,i=>i);{const i=this.children_.getReverseIteratorFrom(e.name,V.Wrap);let s=i.peek();for(;s!=null&&n.compare(s,e)>0;)i.getNext(),s=i.peek();return i}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===$s?-1:0}withIndex(e){if(e===Qr||this.indexMap_.hasIndex(e))return this;{const n=this.indexMap_.addIndex(e,this.children_);return new B(this.children_,this.priorityNode_,n)}}isIndexed(e){return e===Qr||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority()))if(this.children_.count()===n.children_.count()){const r=this.getIterator(we),i=n.getIterator(we);let s=r.getNext(),o=i.getNext();for(;s&&o;){if(s.name!==o.name||!s.node.equals(o.node))return!1;s=r.getNext(),o=i.getNext()}return s===null&&o===null}else return!1;else return!1}}resolveIndex_(e){return e===Qr?null:this.indexMap_.get(e.toString())}}B.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class iI extends B{constructor(){super(new st(Ad),B.EMPTY_NODE,qt.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return B.EMPTY_NODE}isEmpty(){return!1}}const $s=new iI;Object.defineProperties(V,{MIN:{value:new V(ai,B.EMPTY_NODE)},MAX:{value:new V(pr,$s)}});oy.__EMPTY_NODE=B.EMPTY_NODE;Ae.__childrenNodeConstructor=B;Xx($s);eI($s);/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const sI=!0;function Pe(t,e=null){if(t===null)return B.EMPTY_NODE;if(typeof t=="object"&&".priority"in t&&(e=t[".priority"]),N(e===null||typeof e=="string"||typeof e=="number"||typeof e=="object"&&".sv"in e,"Invalid priority type found: "+typeof e),typeof t=="object"&&".value"in t&&t[".value"]!==null&&(t=t[".value"]),typeof t!="object"||".sv"in t){const n=t;return new Ae(n,Pe(e))}if(!(t instanceof Array)&&sI){const n=[];let r=!1;if(ze(t,(o,l)=>{if(o.substring(0,1)!=="."){const a=Pe(l);a.isEmpty()||(r=r||!a.getPriority().isEmpty(),n.push(new V(o,a)))}}),n.length===0)return B.EMPTY_NODE;const s=fl(n,Jx,o=>o.name,Ad);if(r){const o=fl(n,we.getCompare());return new B(s,Pe(e),new qt({".priority":o},{".priority":we}))}else return new B(s,Pe(e),qt.Default)}else{let n=B.EMPTY_NODE;return ze(t,(r,i)=>{if(Bt(t,r)&&r.substring(0,1)!=="."){const s=Pe(i);(s.isLeafNode()||!s.isEmpty())&&(n=n.updateImmediateChild(r,s))}}),n.updatePriority(Pe(e))}}Zx(Pe);/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class oI extends Ql{constructor(e){super(),this.indexPath_=e,N(!H(e)&&$(e)!==".priority","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,n){const r=this.extractChild(e.node),i=this.extractChild(n.node),s=r.compareTo(i);return s===0?Cr(e.name,n.name):s}makePost(e,n){const r=Pe(e),i=B.EMPTY_NODE.updateChild(this.indexPath_,r);return new V(n,i)}maxPost(){const e=B.EMPTY_NODE.updateChild(this.indexPath_,$s);return new V(pr,e)}toString(){return Es(this.indexPath_,0).join("/")}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class lI extends Ql{compare(e,n){const r=e.node.compareTo(n.node);return r===0?Cr(e.name,n.name):r}isDefinedOn(e){return!0}indexedValueChanged(e,n){return!e.equals(n)}minPost(){return V.MIN}maxPost(){return V.MAX}makePost(e,n){const r=Pe(e);return new V(n,r)}toString(){return".value"}}const aI=new lI;/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function dy(t){return{type:"value",snapshotNode:t}}function ui(t,e){return{type:"child_added",snapshotNode:e,childName:t}}function xs(t,e){return{type:"child_removed",snapshotNode:e,childName:t}}function Is(t,e,n){return{type:"child_changed",snapshotNode:e,childName:t,oldSnap:n}}function uI(t,e){return{type:"child_moved",snapshotNode:e,childName:t}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Od{constructor(e){this.index_=e}updateChild(e,n,r,i,s,o){N(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const l=e.getImmediateChild(n);return l.getChild(i).equals(r.getChild(i))&&l.isEmpty()===r.isEmpty()||(o!=null&&(r.isEmpty()?e.hasChild(n)?o.trackChildChange(xs(n,l)):N(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):l.isEmpty()?o.trackChildChange(ui(n,r)):o.trackChildChange(Is(n,r,l))),e.isLeafNode()&&r.isEmpty())?e:e.updateImmediateChild(n,r).withIndex(this.index_)}updateFullNode(e,n,r){return r!=null&&(e.isLeafNode()||e.forEachChild(we,(i,s)=>{n.hasChild(i)||r.trackChildChange(xs(i,s))}),n.isLeafNode()||n.forEachChild(we,(i,s)=>{if(e.hasChild(i)){const o=e.getImmediateChild(i);o.equals(s)||r.trackChildChange(Is(i,s,o))}else r.trackChildChange(ui(i,s))})),n.withIndex(this.index_)}updatePriority(e,n){return e.isEmpty()?B.EMPTY_NODE:e.updatePriority(n)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class ks{constructor(e){this.indexedFilter_=new Od(e.getIndex()),this.index_=e.getIndex(),this.startPost_=ks.getStartPost_(e),this.endPost_=ks.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const n=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,r=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return n&&r}updateChild(e,n,r,i,s,o){return this.matches(new V(n,r))||(r=B.EMPTY_NODE),this.indexedFilter_.updateChild(e,n,r,i,s,o)}updateFullNode(e,n,r){n.isLeafNode()&&(n=B.EMPTY_NODE);let i=n.withIndex(this.index_);i=i.updatePriority(B.EMPTY_NODE);const s=this;return n.forEachChild(we,(o,l)=>{s.matches(new V(o,l))||(i=i.updateImmediateChild(o,B.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,r)}updatePriority(e,n){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const n=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),n)}else return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const n=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),n)}else return e.getIndex().maxPost()}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class cI{constructor(e){this.withinDirectionalStart=n=>this.reverse_?this.withinEndPost(n):this.withinStartPost(n),this.withinDirectionalEnd=n=>this.reverse_?this.withinStartPost(n):this.withinEndPost(n),this.withinStartPost=n=>{const r=this.index_.compare(this.rangedFilter_.getStartPost(),n);return this.startIsInclusive_?r<=0:r<0},this.withinEndPost=n=>{const r=this.index_.compare(n,this.rangedFilter_.getEndPost());return this.endIsInclusive_?r<=0:r<0},this.rangedFilter_=new ks(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,n,r,i,s,o){return this.rangedFilter_.matches(new V(n,r))||(r=B.EMPTY_NODE),e.getImmediateChild(n).equals(r)?e:e.numChildren()d(v,f)}else o=this.index_.getCompare();const l=e;N(l.numChildren()===this.limit_,"");const a=new V(n,r),u=this.reverse_?l.getFirstChild(this.index_):l.getLastChild(this.index_),h=this.rangedFilter_.matches(a);if(l.hasChild(n)){const d=l.getImmediateChild(n);let f=i.getChildAfterChild(this.index_,u,this.reverse_);for(;f!=null&&(f.name===n||l.hasChild(f.name));)f=i.getChildAfterChild(this.index_,f,this.reverse_);const v=f==null?1:o(f,a);if(h&&!r.isEmpty()&&v>=0)return s!=null&&s.trackChildChange(Is(n,r,d)),l.updateImmediateChild(n,r);{s!=null&&s.trackChildChange(xs(n,d));const _=l.updateImmediateChild(n,B.EMPTY_NODE);return f!=null&&this.rangedFilter_.matches(f)?(s!=null&&s.trackChildChange(ui(f.name,f.node)),_.updateImmediateChild(f.name,f.node)):_}}else return r.isEmpty()?e:h&&o(u,a)>=0?(s!=null&&(s.trackChildChange(xs(u.name,u.node)),s.trackChildChange(ui(n,r))),l.updateImmediateChild(n,r).updateImmediateChild(u.name,B.EMPTY_NODE)):e}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Dd{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_=we}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===""?this.startSet_:this.viewFrom_==="l"}getIndexStartValue(){return N(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return N(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:ai}hasEnd(){return this.endSet_}getIndexEndValue(){return N(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return N(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:pr}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){return N(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_===we}copy(){const e=new Dd;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 dI(t){return t.loadsAllData()?new Od(t.getIndex()):t.hasLimit()?new cI(t):new ks(t)}function sp(t){const e={};if(t.isDefault())return e;let n;if(t.index_===we?n="$priority":t.index_===aI?n="$value":t.index_===Qr?n="$key":(N(t.index_ instanceof oI,"Unrecognized index type!"),n=t.index_.toString()),e.orderBy=Ne(n),t.startSet_){const r=t.startAfterSet_?"startAfter":"startAt";e[r]=Ne(t.indexStartValue_),t.startNameSet_&&(e[r]+=","+Ne(t.indexStartName_))}if(t.endSet_){const r=t.endBeforeSet_?"endBefore":"endAt";e[r]=Ne(t.indexEndValue_),t.endNameSet_&&(e[r]+=","+Ne(t.indexEndName_))}return t.limitSet_&&(t.isViewFromLeft()?e.limitToFirst=t.limit_:e.limitToLast=t.limit_),e}function op(t){const e={};if(t.startSet_&&(e.sp=t.indexStartValue_,t.startNameSet_&&(e.sn=t.indexStartName_),e.sin=!t.startAfterSet_),t.endSet_&&(e.ep=t.indexEndValue_,t.endNameSet_&&(e.en=t.indexEndName_),e.ein=!t.endBeforeSet_),t.limitSet_){e.l=t.limit_;let n=t.viewFrom_;n===""&&(t.isViewFromLeft()?n="l":n="r"),e.vf=n}return t.index_!==we&&(e.i=t.index_.toString()),e}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class pl extends ny{constructor(e,n,r,i){super(),this.repoInfo_=e,this.onDataUpdate_=n,this.authTokenProvider_=r,this.appCheckTokenProvider_=i,this.log_=Ws("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,n){return n!==void 0?"tag$"+n:(N(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,n,r,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const o=pl.getListenId_(e,r),l={};this.listens_[o]=l;const a=sp(e._queryParams);this.restRequest_(s+".json",a,(u,h)=>{let d=h;if(u===404&&(d=null,u=null),u===null&&this.onDataUpdate_(s,d,!1,r),oi(this.listens_,o)===l){let f;u?u===401?f="permission_denied":f="rest_error:"+u:f="ok",i(f,null)}})}unlisten(e,n){const r=pl.getListenId_(e,n);delete this.listens_[r]}get(e){const n=sp(e._queryParams),r=e._path.toString(),i=new Us;return this.restRequest_(r+".json",n,(s,o)=>{let l=o;s===404&&(l=null,s=null),s===null?(this.onDataUpdate_(r,l,!1,null),i.resolve(l)):i.reject(new Error(l))}),i.promise}refreshAuthToken(e){}restRequest_(e,n={},r){return n.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,s])=>{i&&i.accessToken&&(n.auth=i.accessToken),s&&s.token&&(n.ac=s.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+yi(n);this.log_("Sending REST request for "+o);const l=new XMLHttpRequest;l.onreadystatechange=()=>{if(r&&l.readyState===4){this.log_("REST Response for "+o+" received. status:",l.status,"response:",l.responseText);let a=null;if(l.status>=200&&l.status<300){try{a=ws(l.responseText)}catch{Ye("Failed to parse JSON response for "+o+": "+l.responseText)}r(null,a)}else l.status!==401&&l.status!==404&&Ye("Got unsuccessful REST response for "+o+" Status: "+l.status),r(l.status);r=null}},l.open("GET",o,!0),l.send()})}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class hI{constructor(){this.rootNode_=B.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,n){this.rootNode_=this.rootNode_.updateChild(e,n)}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function ml(){return{value:null,children:new Map}}function hy(t,e,n){if(H(e))t.value=n,t.children.clear();else if(t.value!==null)t.value=t.value.updateChild(e,n);else{const r=$(e);t.children.has(r)||t.children.set(r,ml());const i=t.children.get(r);e=ue(e),hy(i,e,n)}}function rc(t,e,n){t.value!==null?n(e,t.value):fI(t,(r,i)=>{const s=new le(e.toString()+"/"+r);rc(i,s,n)})}function fI(t,e){t.children.forEach((n,r)=>{e(r,n)})}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class pI{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),n=Object.assign({},e);return this.last_&&ze(this.last_,(r,i)=>{n[r]=n[r]-i}),this.last_=e,n}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const lp=10*1e3,mI=30*1e3,gI=5*60*1e3;class vI{constructor(e,n){this.server_=n,this.statsToReport_={},this.statsListener_=new pI(e);const r=lp+(mI-lp)*Math.random();Yi(this.reportStats_.bind(this),Math.floor(r))}reportStats_(){const e=this.statsListener_.get(),n={};let r=!1;ze(e,(i,s)=>{s>0&&Bt(this.statsToReport_,i)&&(n[i]=s,r=!0)}),r&&this.server_.reportStats(n),Yi(this.reportStats_.bind(this),Math.floor(Math.random()*2*gI))}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */var Pt;(function(t){t[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"})(Pt||(Pt={}));function Ld(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Md(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function jd(t){return{fromUser:!1,fromServer:!0,queryId:t,tagged:!0}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class gl{constructor(e,n,r){this.path=e,this.affectedTree=n,this.revert=r,this.type=Pt.ACK_USER_WRITE,this.source=Ld()}operationForChild(e){if(H(this.path)){if(this.affectedTree.value!=null)return N(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const n=this.affectedTree.subtree(new le(e));return new gl(ee(),n,this.revert)}}else return N($(this.path)===e,"operationForChild called for unrelated child."),new gl(ue(this.path),this.affectedTree,this.revert)}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Ts{constructor(e,n){this.source=e,this.path=n,this.type=Pt.LISTEN_COMPLETE}operationForChild(e){return H(this.path)?new Ts(this.source,ee()):new Ts(this.source,ue(this.path))}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class mr{constructor(e,n,r){this.source=e,this.path=n,this.snap=r,this.type=Pt.OVERWRITE}operationForChild(e){return H(this.path)?new mr(this.source,ee(),this.snap.getImmediateChild(e)):new mr(this.source,ue(this.path),this.snap)}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class ci{constructor(e,n,r){this.source=e,this.path=n,this.children=r,this.type=Pt.MERGE}operationForChild(e){if(H(this.path)){const n=this.children.subtree(new le(e));return n.isEmpty()?null:n.value?new mr(this.source,ee(),n.value):new ci(this.source,ee(),n)}else return N($(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new ci(this.source,ue(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class $n{constructor(e,n,r){this.node_=e,this.fullyInitialized_=n,this.filtered_=r}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(H(e))return this.isFullyInitialized()&&!this.filtered_;const n=$(e);return this.isCompleteForChild(n)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class yI{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function _I(t,e,n,r){const i=[],s=[];return e.forEach(o=>{o.type==="child_changed"&&t.index_.indexedValueChanged(o.oldSnap,o.snapshotNode)&&s.push(uI(o.childName,o.snapshotNode))}),Li(t,i,"child_removed",e,r,n),Li(t,i,"child_added",e,r,n),Li(t,i,"child_moved",s,r,n),Li(t,i,"child_changed",e,r,n),Li(t,i,"value",e,r,n),i}function Li(t,e,n,r,i,s){const o=r.filter(l=>l.type===n);o.sort((l,a)=>SI(t,l,a)),o.forEach(l=>{const a=wI(t,l,s);i.forEach(u=>{u.respondsTo(l.type)&&e.push(u.createEvent(a,t.query_))})})}function wI(t,e,n){return e.type==="value"||e.type==="child_removed"||(e.prevName=n.getPredecessorChildName(e.childName,e.snapshotNode,t.index_)),e}function SI(t,e,n){if(e.childName==null||n.childName==null)throw vi("Should only compare child_ events.");const r=new V(e.childName,e.snapshotNode),i=new V(n.childName,n.snapshotNode);return t.index_.compare(r,i)}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function Yl(t,e){return{eventCache:t,serverCache:e}}function Ji(t,e,n,r){return Yl(new $n(e,n,r),t.serverCache)}function fy(t,e,n,r){return Yl(t.eventCache,new $n(e,n,r))}function vl(t){return t.eventCache.isFullyInitialized()?t.eventCache.getNode():null}function gr(t){return t.serverCache.isFullyInitialized()?t.serverCache.getNode():null}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */let Ka;const CI=()=>(Ka||(Ka=new st(ox)),Ka);class ae{constructor(e,n=CI()){this.value=e,this.children=n}static fromObject(e){let n=new ae(null);return ze(e,(r,i)=>{n=n.set(new le(r),i)}),n}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,n){if(this.value!=null&&n(this.value))return{path:ee(),value:this.value};if(H(e))return null;{const r=$(e),i=this.children.get(r);if(i!==null){const s=i.findRootMostMatchingPathAndValue(ue(e),n);return s!=null?{path:_e(new le(r),s.path),value:s.value}:null}else return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(H(e))return this;{const n=$(e),r=this.children.get(n);return r!==null?r.subtree(ue(e)):new ae(null)}}set(e,n){if(H(e))return new ae(n,this.children);{const r=$(e),s=(this.children.get(r)||new ae(null)).set(ue(e),n),o=this.children.insert(r,s);return new ae(this.value,o)}}remove(e){if(H(e))return this.children.isEmpty()?new ae(null):new ae(null,this.children);{const n=$(e),r=this.children.get(n);if(r){const i=r.remove(ue(e));let s;return i.isEmpty()?s=this.children.remove(n):s=this.children.insert(n,i),this.value===null&&s.isEmpty()?new ae(null):new ae(this.value,s)}else return this}}get(e){if(H(e))return this.value;{const n=$(e),r=this.children.get(n);return r?r.get(ue(e)):null}}setTree(e,n){if(H(e))return n;{const r=$(e),s=(this.children.get(r)||new ae(null)).setTree(ue(e),n);let o;return s.isEmpty()?o=this.children.remove(r):o=this.children.insert(r,s),new ae(this.value,o)}}fold(e){return this.fold_(ee(),e)}fold_(e,n){const r={};return this.children.inorderTraversal((i,s)=>{r[i]=s.fold_(_e(e,i),n)}),n(e,this.value,r)}findOnPath(e,n){return this.findOnPath_(e,ee(),n)}findOnPath_(e,n,r){const i=this.value?r(n,this.value):!1;if(i)return i;if(H(e))return null;{const s=$(e),o=this.children.get(s);return o?o.findOnPath_(ue(e),_e(n,s),r):null}}foreachOnPath(e,n){return this.foreachOnPath_(e,ee(),n)}foreachOnPath_(e,n,r){if(H(e))return this;{this.value&&r(n,this.value);const i=$(e),s=this.children.get(i);return s?s.foreachOnPath_(ue(e),_e(n,i),r):new ae(null)}}foreach(e){this.foreach_(ee(),e)}foreach_(e,n){this.children.inorderTraversal((r,i)=>{i.foreach_(_e(e,r),n)}),this.value&&n(e,this.value)}foreachChild(e){this.children.inorderTraversal((n,r)=>{r.value&&e(n,r.value)})}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class At{constructor(e){this.writeTree_=e}static empty(){return new At(new ae(null))}}function Xi(t,e,n){if(H(e))return new At(new ae(n));{const r=t.writeTree_.findRootMostValueAndPath(e);if(r!=null){const i=r.path;let s=r.value;const o=Ke(i,e);return s=s.updateChild(o,n),new At(t.writeTree_.set(i,s))}else{const i=new ae(n),s=t.writeTree_.setTree(e,i);return new At(s)}}}function ic(t,e,n){let r=t;return ze(n,(i,s)=>{r=Xi(r,_e(e,i),s)}),r}function ap(t,e){if(H(e))return At.empty();{const n=t.writeTree_.setTree(e,new ae(null));return new At(n)}}function sc(t,e){return Er(t,e)!=null}function Er(t,e){const n=t.writeTree_.findRootMostValueAndPath(e);return n!=null?t.writeTree_.get(n.path).getChild(Ke(n.path,e)):null}function up(t){const e=[],n=t.writeTree_.value;return n!=null?n.isLeafNode()||n.forEachChild(we,(r,i)=>{e.push(new V(r,i))}):t.writeTree_.children.inorderTraversal((r,i)=>{i.value!=null&&e.push(new V(r,i.value))}),e}function jn(t,e){if(H(e))return t;{const n=Er(t,e);return n!=null?new At(new ae(n)):new At(t.writeTree_.subtree(e))}}function oc(t){return t.writeTree_.isEmpty()}function di(t,e){return py(ee(),t.writeTree_,e)}function py(t,e,n){if(e.value!=null)return n.updateChild(t,e.value);{let r=null;return e.children.inorderTraversal((i,s)=>{i===".priority"?(N(s.value!==null,"Priority writes must always be leaf nodes"),r=s.value):n=py(_e(t,i),s,n)}),!n.getChild(t).isEmpty()&&r!==null&&(n=n.updateChild(_e(t,".priority"),r)),n}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function Jl(t,e){return yy(e,t)}function EI(t,e,n,r,i){N(r>t.lastWriteId,"Stacking an older write on top of newer ones"),i===void 0&&(i=!0),t.allWrites.push({path:e,snap:n,writeId:r,visible:i}),i&&(t.visibleWrites=Xi(t.visibleWrites,e,n)),t.lastWriteId=r}function xI(t,e,n,r){N(r>t.lastWriteId,"Stacking an older merge on top of newer ones"),t.allWrites.push({path:e,children:n,writeId:r,visible:!0}),t.visibleWrites=ic(t.visibleWrites,e,n),t.lastWriteId=r}function II(t,e){for(let n=0;nl.writeId===e);N(n>=0,"removeWrite called with nonexistent writeId.");const r=t.allWrites[n];t.allWrites.splice(n,1);let i=r.visible,s=!1,o=t.allWrites.length-1;for(;i&&o>=0;){const l=t.allWrites[o];l.visible&&(o>=n&&TI(l,r.path)?i=!1:yt(r.path,l.path)&&(s=!0)),o--}if(i){if(s)return bI(t),!0;if(r.snap)t.visibleWrites=ap(t.visibleWrites,r.path);else{const l=r.children;ze(l,a=>{t.visibleWrites=ap(t.visibleWrites,_e(r.path,a))})}return!0}else return!1}function TI(t,e){if(t.snap)return yt(t.path,e);for(const n in t.children)if(t.children.hasOwnProperty(n)&&yt(_e(t.path,n),e))return!0;return!1}function bI(t){t.visibleWrites=my(t.allWrites,PI,ee()),t.allWrites.length>0?t.lastWriteId=t.allWrites[t.allWrites.length-1].writeId:t.lastWriteId=-1}function PI(t){return t.visible}function my(t,e,n){let r=At.empty();for(let i=0;i{r=r.updateImmediateChild(s,o)}),r;if(n){const s=jn(t.visibleWrites,e);return n.forEachChild(we,(o,l)=>{const a=di(jn(s,new le(o)),l);r=r.updateImmediateChild(o,a)}),up(s).forEach(o=>{r=r.updateImmediateChild(o.name,o.node)}),r}else{const s=jn(t.visibleWrites,e);return up(s).forEach(o=>{r=r.updateImmediateChild(o.name,o.node)}),r}}function RI(t,e,n,r,i){N(r||i,"Either existingEventSnap or existingServerSnap must exist");const s=_e(e,n);if(sc(t.visibleWrites,s))return null;{const o=jn(t.visibleWrites,s);return oc(o)?i.getChild(n):di(o,i.getChild(n))}}function AI(t,e,n,r){const i=_e(e,n),s=Er(t.visibleWrites,i);if(s!=null)return s;if(r.isCompleteForChild(n)){const o=jn(t.visibleWrites,i);return di(o,r.getNode().getImmediateChild(n))}else return null}function OI(t,e){return Er(t.visibleWrites,e)}function DI(t,e,n,r,i,s,o){let l;const a=jn(t.visibleWrites,e),u=Er(a,ee());if(u!=null)l=u;else if(n!=null)l=di(a,n);else return[];if(l=l.withIndex(o),!l.isEmpty()&&!l.isLeafNode()){const h=[],d=o.getCompare(),f=s?l.getReverseIteratorFrom(r,o):l.getIteratorFrom(r,o);let v=f.getNext();for(;v&&h.length0||!t.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(dy(vl(e)))}}function wy(t,e,n,r,i,s){const o=e.eventCache;if(_l(r,n)!=null)return e;{let l,a;if(H(n))if(N(e.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),e.serverCache.isFiltered()){const u=gr(e),h=u instanceof B?u:B.EMPTY_NODE,d=Fd(r,h);l=t.filter.updateFullNode(e.eventCache.getNode(),d,s)}else{const u=yl(r,gr(e));l=t.filter.updateFullNode(e.eventCache.getNode(),u,s)}else{const u=$(n);if(u===".priority"){N(Wn(n)===1,"Can't have a priority with additional path components");const h=o.getNode();a=e.serverCache.getNode();const d=cp(r,n,h,a);d!=null?l=t.filter.updatePriority(h,d):l=o.getNode()}else{const h=ue(n);let d;if(o.isCompleteForChild(u)){a=e.serverCache.getNode();const f=cp(r,n,o.getNode(),a);f!=null?d=o.getNode().getImmediateChild(u).updateChild(h,f):d=o.getNode().getImmediateChild(u)}else d=Ud(r,u,e.serverCache);d!=null?l=t.filter.updateChild(o.getNode(),u,d,h,i,s):l=o.getNode()}}return Ji(e,l,o.isFullyInitialized()||H(n),t.filter.filtersNodes())}}function wl(t,e,n,r,i,s,o,l){const a=e.serverCache;let u;const h=o?t.filter:t.filter.getIndexedFilter();if(H(n))u=h.updateFullNode(a.getNode(),r,null);else if(h.filtersNodes()&&!a.isFiltered()){const v=a.getNode().updateChild(n,r);u=h.updateFullNode(a.getNode(),v,null)}else{const v=$(n);if(!a.isCompleteForPath(n)&&Wn(n)>1)return e;const w=ue(n),E=a.getNode().getImmediateChild(v).updateChild(w,r);v===".priority"?u=h.updatePriority(a.getNode(),E):u=h.updateChild(a.getNode(),v,E,w,_y,null)}const d=fy(e,u,a.isFullyInitialized()||H(n),h.filtersNodes()),f=new zd(i,d,s);return wy(t,d,n,i,f,l)}function lc(t,e,n,r,i,s,o){const l=e.eventCache;let a,u;const h=new zd(i,e,s);if(H(n))u=t.filter.updateFullNode(e.eventCache.getNode(),r,o),a=Ji(e,u,!0,t.filter.filtersNodes());else{const d=$(n);if(d===".priority")u=t.filter.updatePriority(e.eventCache.getNode(),r),a=Ji(e,u,l.isFullyInitialized(),l.isFiltered());else{const f=ue(n),v=l.getNode().getImmediateChild(d);let w;if(H(f))w=r;else{const _=h.getCompleteChild(d);_!=null?Pd(f)===".priority"&&_.getChild(iy(f)).isEmpty()?w=_:w=_.updateChild(f,r):w=B.EMPTY_NODE}if(v.equals(w))a=e;else{const _=t.filter.updateChild(l.getNode(),d,w,f,h,o);a=Ji(e,_,l.isFullyInitialized(),t.filter.filtersNodes())}}}return a}function dp(t,e){return t.eventCache.isCompleteForChild(e)}function $I(t,e,n,r,i,s,o){let l=e;return r.foreach((a,u)=>{const h=_e(n,a);dp(e,$(h))&&(l=lc(t,l,h,u,i,s,o))}),r.foreach((a,u)=>{const h=_e(n,a);dp(e,$(h))||(l=lc(t,l,h,u,i,s,o))}),l}function hp(t,e,n){return n.foreach((r,i)=>{e=e.updateChild(r,i)}),e}function ac(t,e,n,r,i,s,o,l){if(e.serverCache.getNode().isEmpty()&&!e.serverCache.isFullyInitialized())return e;let a=e,u;H(n)?u=r:u=new ae(null).setTree(n,r);const h=e.serverCache.getNode();return u.children.inorderTraversal((d,f)=>{if(h.hasChild(d)){const v=e.serverCache.getNode().getImmediateChild(d),w=hp(t,v,f);a=wl(t,a,new le(d),w,i,s,o,l)}}),u.children.inorderTraversal((d,f)=>{const v=!e.serverCache.isCompleteForChild(d)&&f.value===null;if(!h.hasChild(d)&&!v){const w=e.serverCache.getNode().getImmediateChild(d),_=hp(t,w,f);a=wl(t,a,new le(d),_,i,s,o,l)}}),a}function VI(t,e,n,r,i,s,o){if(_l(i,n)!=null)return e;const l=e.serverCache.isFiltered(),a=e.serverCache;if(r.value!=null){if(H(n)&&a.isFullyInitialized()||a.isCompleteForPath(n))return wl(t,e,n,a.getNode().getChild(n),i,s,l,o);if(H(n)){let u=new ae(null);return a.getNode().forEachChild(Qr,(h,d)=>{u=u.set(new le(h),d)}),ac(t,e,n,u,i,s,l,o)}else return e}else{let u=new ae(null);return r.foreach((h,d)=>{const f=_e(n,h);a.isCompleteForPath(f)&&(u=u.set(h,a.getNode().getChild(f)))}),ac(t,e,n,u,i,s,l,o)}}function HI(t,e,n,r,i){const s=e.serverCache,o=fy(e,s.getNode(),s.isFullyInitialized()||H(n),s.isFiltered());return wy(t,o,n,r,_y,i)}function GI(t,e,n,r,i,s){let o;if(_l(r,n)!=null)return e;{const l=new zd(r,e,i),a=e.eventCache.getNode();let u;if(H(n)||$(n)===".priority"){let h;if(e.serverCache.isFullyInitialized())h=yl(r,gr(e));else{const d=e.serverCache.getNode();N(d instanceof B,"serverChildren would be complete if leaf node"),h=Fd(r,d)}h=h,u=t.filter.updateFullNode(a,h,s)}else{const h=$(n);let d=Ud(r,h,e.serverCache);d==null&&e.serverCache.isCompleteForChild(h)&&(d=a.getImmediateChild(h)),d!=null?u=t.filter.updateChild(a,h,d,ue(n),l,s):e.eventCache.getNode().hasChild(h)?u=t.filter.updateChild(a,h,B.EMPTY_NODE,ue(n),l,s):u=a,u.isEmpty()&&e.serverCache.isFullyInitialized()&&(o=yl(r,gr(e)),o.isLeafNode()&&(u=t.filter.updateFullNode(u,o,s)))}return o=e.serverCache.isFullyInitialized()||_l(r,ee())!=null,Ji(e,u,o,t.filter.filtersNodes())}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class qI{constructor(e,n){this.query_=e,this.eventRegistrations_=[];const r=this.query_._queryParams,i=new Od(r.getIndex()),s=dI(r);this.processor_=UI(s);const o=n.serverCache,l=n.eventCache,a=i.updateFullNode(B.EMPTY_NODE,o.getNode(),null),u=s.updateFullNode(B.EMPTY_NODE,l.getNode(),null),h=new $n(a,o.isFullyInitialized(),i.filtersNodes()),d=new $n(u,l.isFullyInitialized(),s.filtersNodes());this.viewCache_=Yl(d,h),this.eventGenerator_=new yI(this.query_)}get query(){return this.query_}}function KI(t){return t.viewCache_.serverCache.getNode()}function QI(t){return vl(t.viewCache_)}function YI(t,e){const n=gr(t.viewCache_);return n&&(t.query._queryParams.loadsAllData()||!H(e)&&!n.getImmediateChild($(e)).isEmpty())?n.getChild(e):null}function fp(t){return t.eventRegistrations_.length===0}function JI(t,e){t.eventRegistrations_.push(e)}function pp(t,e,n){const r=[];if(n){N(e==null,"A cancel should cancel all event registrations.");const i=t.query._path;t.eventRegistrations_.forEach(s=>{const o=s.createCancelEvent(n,i);o&&r.push(o)})}if(e){let i=[];for(let s=0;s{r.push(ui(s,o))}),n.isFullyInitialized()&&r.push(dy(n.getNode())),Sy(t,r,n.getNode(),e)}function Sy(t,e,n,r){const i=r?[r]:t.eventRegistrations_;return _I(t.eventGenerator_,e,n,i)}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */let Sl;class Cy{constructor(){this.views=new Map}}function ZI(t){N(!Sl,"__referenceConstructor has already been defined"),Sl=t}function ek(){return N(Sl,"Reference.ts has not been loaded"),Sl}function tk(t){return t.views.size===0}function Bd(t,e,n,r){const i=e.source.queryId;if(i!==null){const s=t.views.get(i);return N(s!=null,"SyncTree gave us an op for an invalid query."),mp(s,e,n,r)}else{let s=[];for(const o of t.views.values())s=s.concat(mp(o,e,n,r));return s}}function Ey(t,e,n,r,i){const s=e._queryIdentifier,o=t.views.get(s);if(!o){let l=yl(n,i?r:null),a=!1;l?a=!0:r instanceof B?(l=Fd(n,r),a=!1):(l=B.EMPTY_NODE,a=!1);const u=Yl(new $n(l,a,!1),new $n(r,i,!1));return new qI(e,u)}return o}function nk(t,e,n,r,i,s){const o=Ey(t,e,r,i,s);return t.views.has(e._queryIdentifier)||t.views.set(e._queryIdentifier,o),JI(o,n),XI(o,n)}function rk(t,e,n,r){const i=e._queryIdentifier,s=[];let o=[];const l=Vn(t);if(i==="default")for(const[a,u]of t.views.entries())o=o.concat(pp(u,n,r)),fp(u)&&(t.views.delete(a),u.query._queryParams.loadsAllData()||s.push(u.query));else{const a=t.views.get(i);a&&(o=o.concat(pp(a,n,r)),fp(a)&&(t.views.delete(i),a.query._queryParams.loadsAllData()||s.push(a.query)))}return l&&!Vn(t)&&s.push(new(ek())(e._repo,e._path)),{removed:s,events:o}}function xy(t){const e=[];for(const n of t.views.values())n.query._queryParams.loadsAllData()||e.push(n);return e}function Fn(t,e){let n=null;for(const r of t.views.values())n=n||YI(r,e);return n}function Iy(t,e){if(e._queryParams.loadsAllData())return Xl(t);{const r=e._queryIdentifier;return t.views.get(r)}}function ky(t,e){return Iy(t,e)!=null}function Vn(t){return Xl(t)!=null}function Xl(t){for(const e of t.views.values())if(e.query._queryParams.loadsAllData())return e;return null}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */let Cl;function ik(t){N(!Cl,"__referenceConstructor has already been defined"),Cl=t}function sk(){return N(Cl,"Reference.ts has not been loaded"),Cl}let ok=1;class gp{constructor(e){this.listenProvider_=e,this.syncPointTree_=new ae(null),this.pendingWriteTree_=LI(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Ty(t,e,n,r,i){return EI(t.pendingWriteTree_,e,n,r,i),i?Si(t,new mr(Ld(),e,n)):[]}function lk(t,e,n,r){xI(t.pendingWriteTree_,e,n,r);const i=ae.fromObject(n);return Si(t,new ci(Ld(),e,i))}function In(t,e,n=!1){const r=II(t.pendingWriteTree_,e);if(kI(t.pendingWriteTree_,e)){let s=new ae(null);return r.snap!=null?s=s.set(ee(),!0):ze(r.children,o=>{s=s.set(new le(o),!0)}),Si(t,new gl(r.path,s,n))}else return[]}function Vs(t,e,n){return Si(t,new mr(Md(),e,n))}function ak(t,e,n){const r=ae.fromObject(n);return Si(t,new ci(Md(),e,r))}function uk(t,e){return Si(t,new Ts(Md(),e))}function ck(t,e,n){const r=$d(t,n);if(r){const i=Vd(r),s=i.path,o=i.queryId,l=Ke(s,e),a=new Ts(jd(o),l);return Hd(t,s,a)}else return[]}function El(t,e,n,r,i=!1){const s=e._path,o=t.syncPointTree_.get(s);let l=[];if(o&&(e._queryIdentifier==="default"||ky(o,e))){const a=rk(o,e,n,r);tk(o)&&(t.syncPointTree_=t.syncPointTree_.remove(s));const u=a.removed;if(l=a.events,!i){const h=u.findIndex(f=>f._queryParams.loadsAllData())!==-1,d=t.syncPointTree_.findOnPath(s,(f,v)=>Vn(v));if(h&&!d){const f=t.syncPointTree_.subtree(s);if(!f.isEmpty()){const v=fk(f);for(let w=0;w0&&!r&&(h?t.listenProvider_.stopListening(Zi(e),null):u.forEach(f=>{const v=t.queryToTagMap.get(Zl(f));t.listenProvider_.stopListening(Zi(f),v)}))}pk(t,u)}return l}function by(t,e,n,r){const i=$d(t,r);if(i!=null){const s=Vd(i),o=s.path,l=s.queryId,a=Ke(o,e),u=new mr(jd(l),a,n);return Hd(t,o,u)}else return[]}function dk(t,e,n,r){const i=$d(t,r);if(i){const s=Vd(i),o=s.path,l=s.queryId,a=Ke(o,e),u=ae.fromObject(n),h=new ci(jd(l),a,u);return Hd(t,o,h)}else return[]}function uc(t,e,n,r=!1){const i=e._path;let s=null,o=!1;t.syncPointTree_.foreachOnPath(i,(f,v)=>{const w=Ke(f,i);s=s||Fn(v,w),o=o||Vn(v)});let l=t.syncPointTree_.get(i);l?(o=o||Vn(l),s=s||Fn(l,ee())):(l=new Cy,t.syncPointTree_=t.syncPointTree_.set(i,l));let a;s!=null?a=!0:(a=!1,s=B.EMPTY_NODE,t.syncPointTree_.subtree(i).foreachChild((v,w)=>{const _=Fn(w,ee());_&&(s=s.updateImmediateChild(v,_))}));const u=ky(l,e);if(!u&&!e._queryParams.loadsAllData()){const f=Zl(e);N(!t.queryToTagMap.has(f),"View does not exist, but we have a tag");const v=mk();t.queryToTagMap.set(f,v),t.tagToQueryMap.set(v,f)}const h=Jl(t.pendingWriteTree_,i);let d=nk(l,e,n,h,s,a);if(!u&&!o&&!r){const f=Iy(l,e);d=d.concat(gk(t,e,f))}return d}function Wd(t,e,n){const i=t.pendingWriteTree_,s=t.syncPointTree_.findOnPath(e,(o,l)=>{const a=Ke(o,e),u=Fn(l,a);if(u)return u});return gy(i,e,s,n,!0)}function hk(t,e){const n=e._path;let r=null;t.syncPointTree_.foreachOnPath(n,(u,h)=>{const d=Ke(u,n);r=r||Fn(h,d)});let i=t.syncPointTree_.get(n);i?r=r||Fn(i,ee()):(i=new Cy,t.syncPointTree_=t.syncPointTree_.set(n,i));const s=r!=null,o=s?new $n(r,!0,!1):null,l=Jl(t.pendingWriteTree_,e._path),a=Ey(i,e,l,s?o.getNode():B.EMPTY_NODE,s);return QI(a)}function Si(t,e){return Py(e,t.syncPointTree_,null,Jl(t.pendingWriteTree_,ee()))}function Py(t,e,n,r){if(H(t.path))return Ny(t,e,n,r);{const i=e.get(ee());n==null&&i!=null&&(n=Fn(i,ee()));let s=[];const o=$(t.path),l=t.operationForChild(o),a=e.children.get(o);if(a&&l){const u=n?n.getImmediateChild(o):null,h=vy(r,o);s=s.concat(Py(l,a,u,h))}return i&&(s=s.concat(Bd(i,t,r,n))),s}}function Ny(t,e,n,r){const i=e.get(ee());n==null&&i!=null&&(n=Fn(i,ee()));let s=[];return e.children.inorderTraversal((o,l)=>{const a=n?n.getImmediateChild(o):null,u=vy(r,o),h=t.operationForChild(o);h&&(s=s.concat(Ny(h,l,a,u)))}),i&&(s=s.concat(Bd(i,t,r,n))),s}function Ry(t,e){const n=e.query,r=bs(t,n);return{hashFn:()=>(KI(e)||B.EMPTY_NODE).hash(),onComplete:i=>{if(i==="ok")return r?ck(t,n._path,r):uk(t,n._path);{const s=ux(i,n);return El(t,n,null,s)}}}}function bs(t,e){const n=Zl(e);return t.queryToTagMap.get(n)}function Zl(t){return t._path.toString()+"$"+t._queryIdentifier}function $d(t,e){return t.tagToQueryMap.get(e)}function Vd(t){const e=t.indexOf("$");return N(e!==-1&&e{if(n&&Vn(n))return[Xl(n)];{let i=[];return n&&(i=xy(n)),ze(r,(s,o)=>{i=i.concat(o)}),i}})}function Zi(t){return t._queryParams.loadsAllData()&&!t._queryParams.isDefault()?new(sk())(t._repo,t._path):t}function pk(t,e){for(let n=0;n{if(!H(u)&&h&&Vn(h))return[Xl(h).query];{let f=[];return h&&(f=f.concat(xy(h).map(v=>v.query))),ze(d,(v,w)=>{f=f.concat(w)}),f}});for(let u=0;u{const u=Kd(a,e.getImmediateChild(l),n);u!==a&&(s=s.updateImmediateChild(l,u))}),s}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Qd{constructor(e="",n=null,r={children:{},childCount:0}){this.name=e,this.parent=n,this.node=r}}function Yd(t,e){let n=e instanceof le?e:new le(e),r=t,i=$(n);for(;i!==null;){const s=oi(r.node.children,i)||{children:{},childCount:0};r=new Qd(i,r,s),n=ue(n),i=$(n)}return r}function Ci(t){return t.node.value}function Dy(t,e){t.node.value=e,cc(t)}function Ly(t){return t.node.childCount>0}function wk(t){return Ci(t)===void 0&&!Ly(t)}function ea(t,e){ze(t.node.children,(n,r)=>{e(new Qd(n,t,r))})}function My(t,e,n,r){n&&e(t),ea(t,i=>{My(i,e,!0)})}function Sk(t,e,n){let r=t.parent;for(;r!==null;){if(e(r))return!0;r=r.parent}return!1}function Hs(t){return new le(t.parent===null?t.name:Hs(t.parent)+"/"+t.name)}function cc(t){t.parent!==null&&Ck(t.parent,t.name,t)}function Ck(t,e,n){const r=wk(n),i=Bt(t.node.children,e);r&&i?(delete t.node.children[e],t.node.childCount--,cc(t)):!r&&!i&&(t.node.children[e]=n.node,t.node.childCount++,cc(t))}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Ek=/[\[\].#$\/\u0000-\u001F\u007F]/,xk=/[\[\].#$\u0000-\u001F\u007F]/,Qa=10*1024*1024,Jd=function(t){return typeof t=="string"&&t.length!==0&&!Ek.test(t)},jy=function(t){return typeof t=="string"&&t.length!==0&&!xk.test(t)},Ik=function(t){return t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),jy(t)},kk=function(t){return t===null||typeof t=="string"||typeof t=="number"&&!xd(t)||t&&typeof t=="object"&&Bt(t,".sv")},Tk=function(t,e,n,r){ta(ql(t,"value"),e,n)},ta=function(t,e,n){const r=n instanceof le?new $x(n,t):n;if(e===void 0)throw new Error(t+"contains undefined "+er(r));if(typeof e=="function")throw new Error(t+"contains a function "+er(r)+" with contents = "+e.toString());if(xd(e))throw new Error(t+"contains "+e.toString()+" "+er(r));if(typeof e=="string"&&e.length>Qa/3&&Kl(e)>Qa)throw new Error(t+"contains a string greater than "+Qa+" utf8 bytes "+er(r)+" ('"+e.substring(0,50)+"...')");if(e&&typeof e=="object"){let i=!1,s=!1;if(ze(e,(o,l)=>{if(o===".value")i=!0;else if(o!==".priority"&&o!==".sv"&&(s=!0,!Jd(o)))throw new Error(t+" contains an invalid key ("+o+") "+er(r)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);Vx(r,o),ta(t,l,r),Hx(r)}),i&&s)throw new Error(t+' contains ".value" child '+er(r)+" in addition to actual children.")}},bk=function(t,e){let n,r;for(n=0;n{const a=new le(o);if(ta(i,l,_e(n,a)),Pd(a)===".priority"&&!kk(l))throw new Error(i+"contains an invalid value for '"+a.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(a)}),bk(i,s)},Fy=function(t,e,n,r){if(!jy(n))throw new Error(ql(t,e)+'was an invalid path = "'+n+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},Nk=function(t,e,n,r){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),Fy(t,e,n)},Uy=function(t,e){if($(e)===".info")throw new Error(t+" failed = Can't modify data under /.info/")},Rk=function(t,e){const n=e.path.toString();if(typeof e.repoInfo.host!="string"||e.repoInfo.host.length===0||!Jd(e.repoInfo.namespace)&&e.repoInfo.host.split(":")[0]!=="localhost"||n.length!==0&&!Ik(n))throw new Error(ql(t,"url")+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)};/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Ak{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function na(t,e){let n=null;for(let r=0;rNd(r,e))}function Ct(t,e,n){na(t,n),By(t,r=>yt(r,e)||yt(e,r))}function By(t,e){t.recursionDepth_++;let n=!0;for(let r=0;r{yp(t,r,i,s,o)},t.authTokenProvider_,t.appCheckProvider_),setTimeout(()=>_p(t,!0),0);else{if(typeof n<"u"&&n!==null){if(typeof n!="object")throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{Ne(n)}catch(r){throw new Error("Invalid authOverride provided: "+r)}}t.persistentConnection_=new Xt(t.repoInfo_,e,(r,i,s,o)=>{yp(t,r,i,s,o)},r=>{_p(t,r)},r=>{Uk(t,r)},t.authTokenProvider_,t.appCheckProvider_,n),t.server_=t.persistentConnection_}t.authTokenProvider_.addTokenChangeListener(r=>{t.server_.refreshAuthToken(r)}),t.appCheckProvider_.addTokenChangeListener(r=>{t.server_.refreshAppCheckToken(r.token)}),t.statsReporter_=yx(t.repoInfo_,()=>new vI(t.stats_,t.server_)),t.infoData_=new hI,t.infoSyncTree_=new gp({startListening:(r,i,s,o)=>{let l=[];const a=t.infoData_.getNode(r._path);return a.isEmpty()||(l=Vs(t.infoSyncTree_,r._path,a),setTimeout(()=>{o("ok")},0)),l},stopListening:()=>{}}),Xd(t,"connected",!1),t.serverSyncTree_=new gp({startListening:(r,i,s,o)=>(t.server_.listen(r,s,i,(l,a)=>{const u=o(l,a);Ct(t.eventQueue_,r._path,u)}),[]),stopListening:(r,i)=>{t.server_.unlisten(r,i)}})}function Fk(t){const n=t.infoData_.getNode(new le(".info/serverTimeOffset")).val()||0;return new Date().getTime()+n}function ra(t){return vk({timestamp:Fk(t)})}function yp(t,e,n,r,i){t.dataUpdateCount++;const s=new le(e);n=t.interceptServerDataCallback_?t.interceptServerDataCallback_(e,n):n;let o=[];if(i)if(r){const a=al(n,u=>Pe(u));o=dk(t.serverSyncTree_,s,a,i)}else{const a=Pe(n);o=by(t.serverSyncTree_,s,a,i)}else if(r){const a=al(n,u=>Pe(u));o=ak(t.serverSyncTree_,s,a)}else{const a=Pe(n);o=Vs(t.serverSyncTree_,s,a)}let l=s;o.length>0&&(l=hi(t,s)),Ct(t.eventQueue_,l,o)}function _p(t,e){Xd(t,"connected",e),e===!1&&$k(t)}function Uk(t,e){ze(e,(n,r)=>{Xd(t,n,r)})}function Xd(t,e,n){const r=new le("/.info/"+e),i=Pe(n);t.infoData_.updateSnapshot(r,i);const s=Vs(t.infoSyncTree_,r,i);Ct(t.eventQueue_,r,s)}function Zd(t){return t.nextWriteId_++}function zk(t,e,n){const r=hk(t.serverSyncTree_,e);return r!=null?Promise.resolve(r):t.server_.get(e).then(i=>{const s=Pe(i).withIndex(e._queryParams.getIndex());uc(t.serverSyncTree_,e,n,!0);let o;if(e._queryParams.loadsAllData())o=Vs(t.serverSyncTree_,e._path,s);else{const l=bs(t.serverSyncTree_,e);o=by(t.serverSyncTree_,e._path,s,l)}return Ct(t.eventQueue_,e._path,o),El(t.serverSyncTree_,e,n,null,!0),s},i=>(Gs(t,"get for query "+Ne(e)+" failed: "+i),Promise.reject(new Error(i))))}function Bk(t,e,n,r,i){Gs(t,"set",{path:e.toString(),value:n,priority:r});const s=ra(t),o=Pe(n,r),l=Wd(t.serverSyncTree_,e),a=Oy(o,l,s),u=Zd(t),h=Ty(t.serverSyncTree_,e,a,u,!0);na(t.eventQueue_,h),t.server_.put(e.toString(),o.val(!0),(f,v)=>{const w=f==="ok";w||Ye("set at "+e+" failed: "+f);const _=In(t.serverSyncTree_,u,!w);Ct(t.eventQueue_,e,_),dc(t,i,f,v)});const d=th(t,e);hi(t,d),Ct(t.eventQueue_,d,[])}function Wk(t,e,n,r){Gs(t,"update",{path:e.toString(),value:n});let i=!0;const s=ra(t),o={};if(ze(n,(l,a)=>{i=!1,o[l]=Ay(_e(e,l),Pe(a),t.serverSyncTree_,s)}),i)je("update() called with empty data. Don't do anything."),dc(t,r,"ok",void 0);else{const l=Zd(t),a=lk(t.serverSyncTree_,e,o,l);na(t.eventQueue_,a),t.server_.merge(e.toString(),n,(u,h)=>{const d=u==="ok";d||Ye("update at "+e+" failed: "+u);const f=In(t.serverSyncTree_,l,!d),v=f.length>0?hi(t,e):e;Ct(t.eventQueue_,v,f),dc(t,r,u,h)}),ze(n,u=>{const h=th(t,_e(e,u));hi(t,h)}),Ct(t.eventQueue_,e,[])}}function $k(t){Gs(t,"onDisconnectEvents");const e=ra(t),n=ml();rc(t.onDisconnect_,ee(),(i,s)=>{const o=Ay(i,s,t.serverSyncTree_,e);hy(n,i,o)});let r=[];rc(n,ee(),(i,s)=>{r=r.concat(Vs(t.serverSyncTree_,i,s));const o=th(t,i);hi(t,o)}),t.onDisconnect_=ml(),Ct(t.eventQueue_,ee(),r)}function Vk(t,e,n){let r;$(e._path)===".info"?r=uc(t.infoSyncTree_,e,n):r=uc(t.serverSyncTree_,e,n),zy(t.eventQueue_,e._path,r)}function Hk(t,e,n){let r;$(e._path)===".info"?r=El(t.infoSyncTree_,e,n):r=El(t.serverSyncTree_,e,n),zy(t.eventQueue_,e._path,r)}function Gk(t){t.persistentConnection_&&t.persistentConnection_.interrupt(Dk)}function Gs(t,...e){let n="";t.persistentConnection_&&(n=t.persistentConnection_.id+":"),je(n,...e)}function dc(t,e,n,r){e&&wi(()=>{if(n==="ok")e(null);else{const i=(n||"error").toUpperCase();let s=i;r&&(s+=": "+r);const o=new Error(s);o.code=i,e(o)}})}function Wy(t,e,n){return Wd(t.serverSyncTree_,e,n)||B.EMPTY_NODE}function eh(t,e=t.transactionQueueTree_){if(e||ia(t,e),Ci(e)){const n=Vy(t,e);N(n.length>0,"Sending zero length transaction queue"),n.every(i=>i.status===0)&&qk(t,Hs(e),n)}else Ly(e)&&ea(e,n=>{eh(t,n)})}function qk(t,e,n){const r=n.map(u=>u.currentWriteId),i=Wy(t,e,r);let s=i;const o=i.hash();for(let u=0;u{Gs(t,"transaction put response",{path:a.toString(),status:u});let h=[];if(u==="ok"){const d=[];for(let f=0;fn[f].onComplete(null,!0,n[f].currentOutputSnapshotResolved)),n[f].unwatcher();ia(t,Yd(t.transactionQueueTree_,e)),eh(t,t.transactionQueueTree_),Ct(t.eventQueue_,e,h);for(let f=0;fl.status===0).map(l=>l.currentWriteId);for(let l=0;l=Lk)h=!0,d="maxretry",i=i.concat(In(t.serverSyncTree_,a.currentWriteId,!0));else{const f=Wy(t,a.path,o);a.currentInputSnapshot=f;const v=e[l].update(f.val());if(v!==void 0){ta("transaction failed: Data returned ",v,a.path);let w=Pe(v);typeof v=="object"&&v!=null&&Bt(v,".priority")||(w=w.updatePriority(f.getPriority()));const E=a.currentWriteId,g=ra(t),p=Oy(w,f,g);a.currentOutputSnapshotRaw=w,a.currentOutputSnapshotResolved=p,a.currentWriteId=Zd(t),o.splice(o.indexOf(E),1),i=i.concat(Ty(t.serverSyncTree_,a.path,p,a.currentWriteId,a.applyLocally)),i=i.concat(In(t.serverSyncTree_,E,!0))}else h=!0,d="nodata",i=i.concat(In(t.serverSyncTree_,a.currentWriteId,!0))}Ct(t.eventQueue_,n,i),i=[],h&&(e[l].status=2,function(f){setTimeout(f,Math.floor(0))}(e[l].unwatcher),e[l].onComplete&&(d==="nodata"?r.push(()=>e[l].onComplete(null,!1,e[l].currentInputSnapshot)):r.push(()=>e[l].onComplete(new Error(d),!1,null))))}ia(t,t.transactionQueueTree_);for(let l=0;lr.order-i.order),n}function Hy(t,e,n){const r=Ci(e);if(r)for(let i=0;i{Hy(t,i,n)})}function ia(t,e){const n=Ci(e);if(n){let r=0;for(let i=0;i0?n:void 0)}ea(e,r=>{ia(t,r)})}function th(t,e){const n=Hs($y(t,e)),r=Yd(t.transactionQueueTree_,e);return Sk(r,i=>{Ya(t,i)}),Ya(t,r),My(r,i=>{Ya(t,i)}),n}function Ya(t,e){const n=Ci(e);if(n){const r=[];let i=[],s=-1;for(let o=0;o0){let i=n[r];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch{}e+="/"+i}return e}function Yk(t){const e={};t.charAt(0)==="?"&&(t=t.substring(1));for(const n of t.split("&")){if(n.length===0)continue;const r=n.split("=");r.length===2?e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):Ye(`Invalid query segment '${n}' in query '${t}'`)}return e}const wp=function(t,e){const n=Jk(t),r=n.namespace;n.domain==="firebase.com"&&sn(n.host+" is no longer supported. Please use .firebaseio.com instead"),(!r||r==="undefined")&&n.domain!=="localhost"&&sn("Cannot parse Firebase url. Please use https://.firebaseio.com"),n.secure||ix();const i=n.scheme==="ws"||n.scheme==="wss";return{repoInfo:new Qv(n.host,n.secure,r,i,e,"",r!==n.subdomain),path:new le(n.pathString)}},Jk=function(t){let e="",n="",r="",i="",s="",o=!0,l="https",a=443;if(typeof t=="string"){let u=t.indexOf("//");u>=0&&(l=t.substring(0,u-1),t=t.substring(u+2));let h=t.indexOf("/");h===-1&&(h=t.length);let d=t.indexOf("?");d===-1&&(d=t.length),e=t.substring(0,Math.min(h,d)),h=0?(o=l==="https"||l==="wss",a=parseInt(e.substring(u+1),10)):u=e.length;const v=e.slice(0,u);if(v.toLowerCase()==="localhost")n="localhost";else if(v.split(".").length<=2)n=v;else{const w=e.indexOf(".");r=e.substring(0,w).toLowerCase(),n=e.substring(w+1),s=r}"ns"in f&&(s=f.ns)}return{host:e,port:a,domain:n,subdomain:r,secure:o,scheme:l,pathString:i,namespace:s}};/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Xk{constructor(e,n,r,i){this.eventType=e,this.eventRegistration=n,this.snapshot=r,this.prevName=i}getPath(){const e=this.snapshot.ref;return this.eventType==="value"?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+Ne(this.snapshot.exportVal())}}class Zk{constructor(e,n,r){this.eventRegistration=e,this.error=n,this.path=r}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Gy{constructor(e,n){this.snapshotCallback=e,this.cancelCallback=n}onValue(e,n){this.snapshotCallback.call(null,e,n)}onCancel(e){return N(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||this.snapshotCallback.userCallback!==void 0&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class nh{constructor(e,n,r,i){this._repo=e,this._path=n,this._queryParams=r,this._orderByCalled=i}get key(){return H(this._path)?null:Pd(this._path)}get ref(){return new cn(this._repo,this._path)}get _queryIdentifier(){const e=op(this._queryParams),n=Id(e);return n==="{}"?"default":n}get _queryObject(){return op(this._queryParams)}isEqual(e){if(e=Et(e),!(e instanceof nh))return!1;const n=this._repo===e._repo,r=Nd(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return n&&r&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+Bx(this._path)}}class cn extends nh{constructor(e,n){super(e,n,new Dd,!1)}get parent(){const e=iy(this._path);return e===null?null:new cn(this._repo,e)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}}class Ps{constructor(e,n,r){this._node=e,this.ref=n,this._index=r}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const n=new le(e),r=hc(this.ref,e);return new Ps(this._node.getChild(n),r,we)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(r,i)=>e(new Ps(i,hc(this.ref,r),we)))}hasChild(e){const n=new le(e);return!this._node.getChild(n).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function ne(t,e){return t=Et(t),t._checkNotDeleted("ref"),e!==void 0?hc(t._root,e):t._root}function hc(t,e){return t=Et(t),$(t._path)===null?Nk("child","path",e):Fy("child","path",e),new cn(t._repo,_e(t._path,e))}function vr(t){return Uy("remove",t._path),on(t,null)}function on(t,e){t=Et(t),Uy("set",t._path),Tk("set",e,t._path);const n=new Us;return Bk(t._repo,t._path,e,null,n.wrapCallback(()=>{})),n.promise}function sa(t,e){Pk("update",e,t._path);const n=new Us;return Wk(t._repo,t._path,e,n.wrapCallback(()=>{})),n.promise}function Ns(t){t=Et(t);const e=new Gy(()=>{}),n=new oa(e);return zk(t._repo,t,n).then(r=>new Ps(r,new cn(t._repo,t._path),t._queryParams.getIndex()))}class oa{constructor(e){this.callbackContext=e}respondsTo(e){return e==="value"}createEvent(e,n){const r=n._queryParams.getIndex();return new Xk("value",this,new Ps(e.snapshotNode,new cn(n._repo,n._path),r))}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,n){return this.callbackContext.hasCancelCallback?new Zk(this,e,n):null}matches(e){return e instanceof oa?!e.callbackContext||!this.callbackContext?!0:e.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}}function eT(t,e,n,r,i){const s=new Gy(n,void 0),o=new oa(s);return Vk(t._repo,t,o),()=>Hk(t._repo,t,o)}function xr(t,e,n,r){return eT(t,"value",e)}ZI(cn);ik(cn);/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const tT="FIREBASE_DATABASE_EMULATOR_HOST",fc={};let nT=!1;function rT(t,e,n,r){t.repoInfo_=new Qv(`${e}:${n}`,!1,t.repoInfo_.namespace,t.repoInfo_.webSocketOnly,t.repoInfo_.nodeAdmin,t.repoInfo_.persistenceKey,t.repoInfo_.includeNamespaceInQueryParams,!0),r&&(t.authTokenProvider_=r)}function iT(t,e,n,r,i){let s=r||t.options.databaseURL;s===void 0&&(t.options.projectId||sn("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),je("Using default host for project ",t.options.projectId),s=`${t.options.projectId}-default-rtdb.firebaseio.com`);let o=wp(s,i),l=o.repoInfo,a;typeof process<"u"&&Wf&&(a=Wf[tT]),a?(s=`http://${a}?ns=${l.namespace}`,o=wp(s,i),l=o.repoInfo):o.repoInfo.secure;const u=new mx(t.name,t.options,e);Rk("Invalid Firebase Database URL",o),H(o.path)||sn("Database URL must point to the root of a Firebase Database (not including a child path).");const h=oT(l,t,u,new px(t.name,n));return new lT(h,t)}function sT(t,e){const n=fc[e];(!n||n[t.key]!==t)&&sn(`Database ${e}(${t.repoInfo_}) has already been deleted.`),Gk(t),delete n[t.key]}function oT(t,e,n,r){let i=fc[e.name];i||(i={},fc[e.name]=i);let s=i[t.toURLString()];return s&&sn("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new Mk(t,nT,n,r),i[t.toURLString()]=s,s}class lT{constructor(e,n){this._repoInternal=e,this.app=n,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(jk(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new cn(this._repo,ee())),this._rootInternal}_delete(){return this._rootInternal!==null&&(sT(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&sn("Cannot call "+e+" on a deleted database.")}}function aT(t=Av(),e){const n=Ed(t,"database").getImmediate({identifier:e});if(!n._instanceStarted){const r=IC("database");r&&uT(n,...r)}return n}function uT(t,e,n,r={}){t=Et(t),t._checkNotDeleted("useEmulator"),t._instanceStarted&&sn("Cannot call useEmulator() after instance has already been initialized.");const i=t._repoInternal;let s;if(i.repoInfo_.nodeAdmin)r.mockUserToken&&sn('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 Po(Po.OWNER);else if(r.mockUserToken){const o=typeof r.mockUserToken=="string"?r.mockUserToken:kC(r.mockUserToken,t.app.options.projectId);s=new Po(o)}rT(i,e,n,s)}/** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function cT(t){XE(_i),li(new fr("database",(e,{instanceIdentifier:n})=>{const r=e.getProvider("app").getImmediate(),i=e.getProvider("auth-internal"),s=e.getProvider("app-check-internal");return iT(r,i,s,n)},"PUBLIC").setMultipleInstances(!0)),Mn($f,Vf,t),Mn($f,Vf,"esm2017")}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const dT={".sv":"timestamp"};function Sp(){return dT}Xt.prototype.simpleListen=function(t,e){this.sendRequest("q",{p:t},e)};Xt.prototype.echo=function(t,e){this.sendRequest("echo",{d:t},e)};cT();function rh(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i"u")return null;const t=navigator;return t.languages&&t.languages[0]||t.language||null}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class qs{constructor(e,n){this.shortDelay=e,this.longDelay=n,an(n>e,"Short delay should be less than long delay!"),this.isMobile=wd()||Tv()}get(){return mT()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function sh(t,e){an(t.emulator,"Emulator should always be set here");const{url:n}=t.emulator;return e?`${n}${e.startsWith("/")?e.slice(1):e}`:n}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Yy{static initialize(e,n,r){this.fetchImpl=e,n&&(this.headersImpl=n),r&&(this.responseImpl=r)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;Kt("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl)return this.headersImpl;if(typeof self<"u"&&"Headers"in self)return self.Headers;if(typeof globalThis<"u"&&globalThis.Headers)return globalThis.Headers;if(typeof Headers<"u")return Headers;Kt("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl)return this.responseImpl;if(typeof self<"u"&&"Response"in self)return self.Response;if(typeof globalThis<"u"&&globalThis.Response)return globalThis.Response;if(typeof Response<"u")return Response;Kt("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const vT={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"};/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const yT=new qs(3e4,6e4);function la(t,e){return t.tenantId&&!e.tenantId?Object.assign(Object.assign({},e),{tenantId:t.tenantId}):e}async function Ei(t,e,n,r,i={}){return Jy(t,i,async()=>{let s={},o={};r&&(e==="GET"?o=r:s={body:JSON.stringify(r)});const l=yi(Object.assign({key:t.config.apiKey},o)).slice(1),a=await t._getAdditionalHeaders();a["Content-Type"]="application/json",t.languageCode&&(a["X-Firebase-Locale"]=t.languageCode);const u=Object.assign({method:e,headers:a},s);return TC()||(u.referrerPolicy="no-referrer"),Yy.fetch()(Zy(t,t.config.apiHost,n,l),u)})}async function Jy(t,e,n){t._canInitEmulator=!1;const r=Object.assign(Object.assign({},vT),e);try{const i=new _T(t),s=await Promise.race([n(),i.promise]);i.clearNetworkTimeout();const o=await s.json();if("needConfirmation"in o)throw go(t,"account-exists-with-different-credential",o);if(s.ok&&!("errorMessage"in o))return o;{const l=s.ok?o.errorMessage:o.error.message,[a,u]=l.split(" : ");if(a==="FEDERATED_USER_ID_ALREADY_LINKED")throw go(t,"credential-already-in-use",o);if(a==="EMAIL_EXISTS")throw go(t,"email-already-in-use",o);if(a==="USER_DISABLED")throw go(t,"user-disabled",o);const h=r[a]||a.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw Qy(t,h,u);ln(t,h)}}catch(i){if(i instanceof Yn)throw i;ln(t,"network-request-failed",{message:String(i)})}}async function Xy(t,e,n,r,i={}){const s=await Ei(t,e,n,r,i);return"mfaPendingCredential"in s&&ln(t,"multi-factor-auth-required",{_serverResponse:s}),s}function Zy(t,e,n,r){const i=`${e}${n}?${r}`;return t.config.emulator?sh(t.config,i):`${t.config.apiScheme}://${i}`}class _T{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((n,r)=>{this.timer=setTimeout(()=>r(Ut(this.auth,"network-request-failed")),yT.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function go(t,e,n){const r={appName:t.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=Ut(t,e,r);return i.customData._tokenResponse=n,i}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function wT(t,e){return Ei(t,"POST","/v1/accounts:delete",e)}async function e_(t,e){return Ei(t,"POST","/v1/accounts:lookup",e)}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function es(t){if(t)try{const e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function ST(t,e=!1){const n=Et(t),r=await n.getIdToken(e),i=oh(r);W(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");const s=typeof i.firebase=="object"?i.firebase:void 0,o=s==null?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:es(Ja(i.auth_time)),issuedAtTime:es(Ja(i.iat)),expirationTime:es(Ja(i.exp)),signInProvider:o||null,signInSecondFactor:(s==null?void 0:s.sign_in_second_factor)||null}}function Ja(t){return Number(t)*1e3}function oh(t){const[e,n,r]=t.split(".");if(e===void 0||n===void 0||r===void 0)return No("JWT malformed, contained fewer than 3 sections"),null;try{const i=ll(n);return i?JSON.parse(i):(No("Failed to decode base64 JWT payload"),null)}catch(i){return No("Caught error parsing JWT payload as JSON",i==null?void 0:i.toString()),null}}function Ep(t){const e=oh(t);return W(e,"internal-error"),W(typeof e.exp<"u","internal-error"),W(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function Rs(t,e,n=!1){if(n)return e;try{return await e}catch(r){throw r instanceof Yn&&CT(r)&&t.auth.currentUser===t&&await t.auth.signOut(),r}}function CT({code:t}){return t==="auth/user-disabled"||t==="auth/user-token-expired"}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class ET{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,this.timerId!==null&&clearTimeout(this.timerId))}getInterval(e){var n;if(e){const r=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),r}else{this.errorBackoff=3e4;const i=((n=this.user.stsTokenManager.expirationTime)!==null&&n!==void 0?n:0)-Date.now()-3e5;return Math.max(0,i)}}schedule(e=!1){if(!this.isRunning)return;const n=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},n)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){(e==null?void 0:e.code)==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class mc{constructor(e,n){this.createdAt=e,this.lastLoginAt=n,this._initializeTime()}_initializeTime(){this.lastSignInTime=es(this.lastLoginAt),this.creationTime=es(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function Il(t){var e;const n=t.auth,r=await t.getIdToken(),i=await Rs(t,e_(n,{idToken:r}));W(i==null?void 0:i.users.length,n,"internal-error");const s=i.users[0];t._notifyReloadListener(s);const o=!((e=s.providerUserInfo)===null||e===void 0)&&e.length?t_(s.providerUserInfo):[],l=IT(t.providerData,o),a=t.isAnonymous,u=!(t.email&&s.passwordHash)&&!(l!=null&&l.length),h=a?u:!1,d={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:l,metadata:new mc(s.createdAt,s.lastLoginAt),isAnonymous:h};Object.assign(t,d)}async function xT(t){const e=Et(t);await Il(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function IT(t,e){return[...t.filter(r=>!e.some(i=>i.providerId===r.providerId)),...e]}function t_(t){return t.map(e=>{var{providerId:n}=e,r=rh(e,["providerId"]);return{providerId:n,uid:r.rawId||"",displayName:r.displayName||null,email:r.email||null,phoneNumber:r.phoneNumber||null,photoURL:r.photoUrl||null}})}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function kT(t,e){const n=await Jy(t,{},async()=>{const r=yi({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:i,apiKey:s}=t.config,o=Zy(t,i,"/v1/token",`key=${s}`),l=await t._getAdditionalHeaders();return l["Content-Type"]="application/x-www-form-urlencoded",Yy.fetch()(o,{method:"POST",headers:l,body:r})});return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function TT(t,e){return Ei(t,"POST","/v2/accounts:revokeToken",la(t,e))}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Yr{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){W(e.idToken,"internal-error"),W(typeof e.idToken<"u","internal-error"),W(typeof e.refreshToken<"u","internal-error");const n="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):Ep(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}updateFromIdToken(e){W(e.length!==0,"internal-error");const n=Ep(e);this.updateTokensAndExpiration(e,null,n)}async getToken(e,n=!1){return!n&&this.accessToken&&!this.isExpired?this.accessToken:(W(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(e,n){const{accessToken:r,refreshToken:i,expiresIn:s}=await kT(e,n);this.updateTokensAndExpiration(r,i,Number(s))}updateTokensAndExpiration(e,n,r){this.refreshToken=n||null,this.accessToken=e||null,this.expirationTime=Date.now()+r*1e3}static fromJSON(e,n){const{refreshToken:r,accessToken:i,expirationTime:s}=n,o=new Yr;return r&&(W(typeof r=="string","internal-error",{appName:e}),o.refreshToken=r),i&&(W(typeof i=="string","internal-error",{appName:e}),o.accessToken=i),s&&(W(typeof s=="number","internal-error",{appName:e}),o.expirationTime=s),o}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 Yr,this.toJSON())}_performRefresh(){return Kt("not implemented")}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function hn(t,e){W(typeof t=="string"||typeof t>"u","internal-error",{appName:e})}class Qt{constructor(e){var{uid:n,auth:r,stsTokenManager:i}=e,s=rh(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new ET(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=n,this.auth=r,this.stsTokenManager=i,this.accessToken=i.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new mc(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const n=await Rs(this,this.stsTokenManager.getToken(this.auth,e));return W(n,this.auth,"internal-error"),this.accessToken!==n&&(this.accessToken=n,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),n}getIdTokenResult(e){return ST(this,e)}reload(){return xT(this)}_assign(e){this!==e&&(W(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(n=>Object.assign({},n)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const n=new Qt(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return n.metadata._copy(this.metadata),n}_onReload(e){W(!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,n=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),n&&await Il(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(Gt(this.auth.app))return Promise.reject(Un(this.auth));const e=await this.getIdToken();return await Rs(this,wT(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({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=>Object.assign({},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,n){var r,i,s,o,l,a,u,h;const d=(r=n.displayName)!==null&&r!==void 0?r:void 0,f=(i=n.email)!==null&&i!==void 0?i:void 0,v=(s=n.phoneNumber)!==null&&s!==void 0?s:void 0,w=(o=n.photoURL)!==null&&o!==void 0?o:void 0,_=(l=n.tenantId)!==null&&l!==void 0?l:void 0,E=(a=n._redirectEventId)!==null&&a!==void 0?a:void 0,g=(u=n.createdAt)!==null&&u!==void 0?u:void 0,p=(h=n.lastLoginAt)!==null&&h!==void 0?h:void 0,{uid:m,emailVerified:S,isAnonymous:I,providerData:P,stsTokenManager:b}=n;W(m&&b,e,"internal-error");const A=Yr.fromJSON(this.name,b);W(typeof m=="string",e,"internal-error"),hn(d,e.name),hn(f,e.name),W(typeof S=="boolean",e,"internal-error"),W(typeof I=="boolean",e,"internal-error"),hn(v,e.name),hn(w,e.name),hn(_,e.name),hn(E,e.name),hn(g,e.name),hn(p,e.name);const q=new Qt({uid:m,auth:e,email:f,emailVerified:S,displayName:d,isAnonymous:I,photoURL:w,phoneNumber:v,tenantId:_,stsTokenManager:A,createdAt:g,lastLoginAt:p});return P&&Array.isArray(P)&&(q.providerData=P.map(z=>Object.assign({},z))),E&&(q._redirectEventId=E),q}static async _fromIdTokenResponse(e,n,r=!1){const i=new Yr;i.updateFromServerResponse(n);const s=new Qt({uid:n.localId,auth:e,stsTokenManager:i,isAnonymous:r});return await Il(s),s}static async _fromGetAccountInfoResponse(e,n,r){const i=n.users[0];W(i.localId!==void 0,"internal-error");const s=i.providerUserInfo!==void 0?t_(i.providerUserInfo):[],o=!(i.email&&i.passwordHash)&&!(s!=null&&s.length),l=new Yr;l.updateFromIdToken(r);const a=new Qt({uid:i.localId,auth:e,stsTokenManager:l,isAnonymous:o}),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:s,metadata:new mc(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!(s!=null&&s.length)};return Object.assign(a,u),a}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const xp=new Map;function Yt(t){an(t instanceof Function,"Expected a class definition");let e=xp.get(t);return e?(an(e instanceof t,"Instance stored in cache mismatched with class"),e):(e=new t,xp.set(t,e),e)}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class n_{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,n){this.storage[e]=n}async _get(e){const n=this.storage[e];return n===void 0?null:n}async _remove(e){delete this.storage[e]}_addListener(e,n){}_removeListener(e,n){}}n_.type="NONE";const Ip=n_;/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function Ro(t,e,n){return`firebase:${t}:${e}:${n}`}class Jr{constructor(e,n,r){this.persistence=e,this.auth=n,this.userKey=r;const{config:i,name:s}=this.auth;this.fullUserKey=Ro(this.userKey,i.apiKey,s),this.fullPersistenceKey=Ro("persistence",i.apiKey,s),this.boundEventHandler=n._onStorageEvent.bind(n),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);return e?Qt._fromJSON(this.auth,e):null}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 n=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,n)return this.setCurrentUser(n)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,n,r="authUser"){if(!n.length)return new Jr(Yt(Ip),e,r);const i=(await Promise.all(n.map(async u=>{if(await u._isAvailable())return u}))).filter(u=>u);let s=i[0]||Yt(Ip);const o=Ro(r,e.config.apiKey,e.name);let l=null;for(const u of n)try{const h=await u._get(o);if(h){const d=Qt._fromJSON(e,h);u!==s&&(l=d),s=u;break}}catch{}const a=i.filter(u=>u._shouldAllowMigration);return!s._shouldAllowMigration||!a.length?new Jr(s,e,r):(s=a[0],l&&await s._set(o,l.toJSON()),await Promise.all(n.map(async u=>{if(u!==s)try{await u._remove(o)}catch{}})),new Jr(s,e,r))}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function kp(t){const e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(o_(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(r_(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(a_(e))return"Blackberry";if(u_(e))return"Webos";if(i_(e))return"Safari";if((e.includes("chrome/")||s_(e))&&!e.includes("edge/"))return"Chrome";if(l_(e))return"Android";{const n=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=t.match(n);if((r==null?void 0:r.length)===2)return r[1]}return"Other"}function r_(t=Je()){return/firefox\//i.test(t)}function i_(t=Je()){const e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function s_(t=Je()){return/crios\//i.test(t)}function o_(t=Je()){return/iemobile/i.test(t)}function l_(t=Je()){return/android/i.test(t)}function a_(t=Je()){return/blackberry/i.test(t)}function u_(t=Je()){return/webos/i.test(t)}function lh(t=Je()){return/iphone|ipad|ipod/i.test(t)||/macintosh/i.test(t)&&/mobile/i.test(t)}function bT(t=Je()){var e;return lh(t)&&!!(!((e=window.navigator)===null||e===void 0)&&e.standalone)}function PT(){return PC()&&document.documentMode===10}function c_(t=Je()){return lh(t)||l_(t)||u_(t)||a_(t)||/windows phone/i.test(t)||o_(t)}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function d_(t,e=[]){let n;switch(t){case"Browser":n=kp(Je());break;case"Worker":n=`${kp(Je())}-${t}`;break;default:n=t}const r=e.length?e.join(","):"FirebaseCore-web";return`${n}/JsCore/${_i}/${r}`}/** - * @license - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class NT{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,n){const r=s=>new Promise((o,l)=>{try{const a=e(s);o(a)}catch(a){l(a)}});r.onAbort=n,this.queue.push(r);const i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const n=[];try{for(const r of this.queue)await r(e),r.onAbort&&n.push(r.onAbort)}catch(r){n.reverse();for(const i of n)try{i()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:r==null?void 0:r.message})}}}/** - * @license - * Copyright 2023 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function RT(t,e={}){return Ei(t,"GET","/v2/passwordPolicy",la(t,e))}/** - * @license - * Copyright 2023 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const AT=6;class OT{constructor(e){var n,r,i,s;const o=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=(n=o.minPasswordLength)!==null&&n!==void 0?n:AT,o.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=o.maxPasswordLength),o.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=o.containsLowercaseCharacter),o.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=o.containsUppercaseCharacter),o.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=o.containsNumericCharacter),o.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=o.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=(i=(r=e.allowedNonAlphanumericCharacters)===null||r===void 0?void 0:r.join(""))!==null&&i!==void 0?i:"",this.forceUpgradeOnSignin=(s=e.forceUpgradeOnSignin)!==null&&s!==void 0?s:!1,this.schemaVersion=e.schemaVersion}validatePassword(e){var n,r,i,s,o,l;const a={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,a),this.validatePasswordCharacterOptions(e,a),a.isValid&&(a.isValid=(n=a.meetsMinPasswordLength)!==null&&n!==void 0?n:!0),a.isValid&&(a.isValid=(r=a.meetsMaxPasswordLength)!==null&&r!==void 0?r:!0),a.isValid&&(a.isValid=(i=a.containsLowercaseLetter)!==null&&i!==void 0?i:!0),a.isValid&&(a.isValid=(s=a.containsUppercaseLetter)!==null&&s!==void 0?s:!0),a.isValid&&(a.isValid=(o=a.containsNumericCharacter)!==null&&o!==void 0?o:!0),a.isValid&&(a.isValid=(l=a.containsNonAlphanumericCharacter)!==null&&l!==void 0?l:!0),a}validatePasswordLengthOptions(e,n){const r=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;r&&(n.meetsMinPasswordLength=e.length>=r),i&&(n.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,n){this.updatePasswordCharacterOptionsStatuses(n,!1,!1,!1,!1);let r;for(let i=0;i="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,n,r,i,s){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=n)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=s))}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class DT{constructor(e,n,r,i){this.app=e,this.heartbeatServiceProvider=n,this.appCheckServiceProvider=r,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Tp(this),this.idTokenSubscription=new Tp(this),this.beforeStateQueue=new NT(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=Ky,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion}_initializeWithPersistence(e,n){return n&&(this._popupRedirectResolver=Yt(n)),this._initializationPromise=this.queue(async()=>{var r,i;if(!this._deleted&&(this.persistenceManager=await Jr.create(this,e),!this._deleted)){if(!((r=this._popupRedirectResolver)===null||r===void 0)&&r._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(n),this.lastNotifiedUid=((i=this.currentUser)===null||i===void 0?void 0:i.uid)||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();if(!(!this.currentUser&&!e)){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{const n=await e_(this,{idToken:e}),r=await Qt._fromGetAccountInfoResponse(this,n,e);await this.directlySetCurrentUser(r)}catch(n){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",n),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){var n;if(Gt(this.app)){const o=this.app.settings.authIdToken;return o?new Promise(l=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(o).then(l,l))}):this.directlySetCurrentUser(null)}const r=await this.assertedPersistence.getCurrentUser();let i=r,s=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const o=(n=this.redirectUser)===null||n===void 0?void 0:n._redirectEventId,l=i==null?void 0:i._redirectEventId,a=await this.tryRedirectSignIn(e);(!o||o===l)&&(a!=null&&a.user)&&(i=a.user,s=!0)}if(!i)return this.directlySetCurrentUser(null);if(!i._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(i)}catch(o){i=r,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(o))}return i?this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}return W(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)}async tryRedirectSignIn(e){let n=null;try{n=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return n}async reloadAndSetCurrentUserOrClear(e){try{await Il(e)}catch(n){if((n==null?void 0:n.code)!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=gT()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(Gt(this.app))return Promise.reject(Un(this));const n=e?Et(e):null;return n&&W(n.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(n&&n._clone(this))}async _updateCurrentUser(e,n=!1){if(!this._deleted)return e&&W(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),n||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return Gt(this.app)?Promise.reject(Un(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return Gt(this.app)?Promise.reject(Un(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(Yt(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const n=this._getPasswordPolicyInternal();return n.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):n.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await RT(this),n=new OT(e);this.tenantId===null?this._projectPasswordPolicy=n:this._tenantPasswordPolicies[this.tenantId]=n}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new zs("auth","Firebase",e())}onAuthStateChanged(e,n,r){return this.registerStateListener(this.authStateSubscription,e,n,r)}beforeAuthStateChanged(e,n){return this.beforeStateQueue.pushCallback(e,n)}onIdTokenChanged(e,n,r){return this.registerStateListener(this.idTokenSubscription,e,n,r)}authStateReady(){return new Promise((e,n)=>{if(this.currentUser)e();else{const r=this.onAuthStateChanged(()=>{r(),e()},n)}})}async revokeAccessToken(e){if(this.currentUser){const n=await this.currentUser.getIdToken(),r={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:n};this.tenantId!=null&&(r.tenantId=this.tenantId),await TT(this,r)}}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:(e=this._currentUser)===null||e===void 0?void 0:e.toJSON()}}async _setRedirectUser(e,n){const r=await this.getOrInitRedirectPersistenceManager(n);return e===null?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const n=e&&Yt(e)||this._popupRedirectResolver;W(n,this,"argument-error"),this.redirectPersistenceManager=await Jr.create(this,[Yt(n._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var n,r;return this._isInitialized&&await this.queue(async()=>{}),((n=this._currentUser)===null||n===void 0?void 0:n._redirectEventId)===e?this._currentUser:((r=this.redirectUser)===null||r===void 0?void 0:r._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,n;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const r=(n=(e=this.currentUser)===null||e===void 0?void 0:e.uid)!==null&&n!==void 0?n:null;this.lastNotifiedUid!==r&&(this.lastNotifiedUid=r,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,n,r,i){if(this._deleted)return()=>{};const s=typeof n=="function"?n:n.next.bind(n);let o=!1;const l=this._isInitialized?Promise.resolve():this._initializationPromise;if(W(l,this,"internal-error"),l.then(()=>{o||s(this.currentUser)}),typeof n=="function"){const a=e.addObserver(n,r,i);return()=>{o=!0,a()}}else{const a=e.addObserver(n);return()=>{o=!0,a()}}}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 W(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=d_(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const n={"X-Client-Version":this.clientVersion};this.app.options.appId&&(n["X-Firebase-gmpid"]=this.app.options.appId);const r=await((e=this.heartbeatServiceProvider.getImmediate({optional:!0}))===null||e===void 0?void 0:e.getHeartbeatsHeader());r&&(n["X-Firebase-Client"]=r);const i=await this._getAppCheckToken();return i&&(n["X-Firebase-AppCheck"]=i),n}async _getAppCheckToken(){var e;const n=await((e=this.appCheckServiceProvider.getImmediate({optional:!0}))===null||e===void 0?void 0:e.getToken());return n!=null&&n.error&&fT(`Error while retrieving App Check token: ${n.error}`),n==null?void 0:n.token}}function aa(t){return Et(t)}class Tp{constructor(e){this.auth=e,this.observer=null,this.addObserver=UC(n=>this.observer=n)}get next(){return W(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */let ah={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function LT(t){ah=t}function MT(t){return ah.loadJS(t)}function jT(){return ah.gapiScript}function FT(t){return`__${t}${Math.floor(Math.random()*1e6)}`}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function UT(t,e){const n=Ed(t,"auth");if(n.isInitialized()){const i=n.getImmediate(),s=n.getOptions();if(ul(s,e??{}))return i;ln(i,"already-initialized")}return n.initialize({options:e})}function zT(t,e){const n=(e==null?void 0:e.persistence)||[],r=(Array.isArray(n)?n:[n]).map(Yt);e!=null&&e.errorMap&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(r,e==null?void 0:e.popupRedirectResolver)}function BT(t,e,n){const r=aa(t);W(r._canInitEmulator,r,"emulator-config-failed"),W(/^https?:\/\//.test(e),r,"invalid-emulator-scheme");const i=!1,s=h_(e),{host:o,port:l}=WT(e),a=l===null?"":`:${l}`;r.config.emulator={url:`${s}//${o}${a}/`},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:o,port:l,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),$T()}function h_(t){const e=t.indexOf(":");return e<0?"":t.substr(0,e+1)}function WT(t){const e=h_(t),n=/(\/\/)?([^?#/]+)/.exec(t.substr(e.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);if(i){const s=i[1];return{host:s,port:bp(r.substr(s.length+1))}}else{const[s,o]=r.split(":");return{host:s,port:bp(o)}}}function bp(t){if(!t)return null;const e=Number(t);return isNaN(e)?null:e}function $T(){function t(){const e=document.createElement("p"),n=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",n.position="fixed",n.width="100%",n.backgroundColor="#ffffff",n.border=".1em solid #000000",n.color="#b50000",n.bottom="0px",n.left="0px",n.margin="0px",n.zIndex="10000",n.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}typeof console<"u"&&typeof console.info=="function"&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?window.addEventListener("DOMContentLoaded",t):t())}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class f_{constructor(e,n){this.providerId=e,this.signInMethod=n}toJSON(){return Kt("not implemented")}_getIdTokenResponse(e){return Kt("not implemented")}_linkToIdToken(e,n){return Kt("not implemented")}_getReauthenticationResolver(e){return Kt("not implemented")}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function Xr(t,e){return Xy(t,"POST","/v1/accounts:signInWithIdp",la(t,e))}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const VT="http://localhost";class yr extends f_{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const n=new yr(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(n.idToken=e.idToken),e.accessToken&&(n.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(n.nonce=e.nonce),e.pendingToken&&(n.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(n.accessToken=e.oauthToken,n.secret=e.oauthTokenSecret):ln("argument-error"),n}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 n=typeof e=="string"?JSON.parse(e):e,{providerId:r,signInMethod:i}=n,s=rh(n,["providerId","signInMethod"]);if(!r||!i)return null;const o=new yr(r,i);return o.idToken=s.idToken||void 0,o.accessToken=s.accessToken||void 0,o.secret=s.secret,o.nonce=s.nonce,o.pendingToken=s.pendingToken||null,o}_getIdTokenResponse(e){const n=this.buildRequest();return Xr(e,n)}_linkToIdToken(e,n){const r=this.buildRequest();return r.idToken=n,Xr(e,r)}_getReauthenticationResolver(e){const n=this.buildRequest();return n.autoCreate=!1,Xr(e,n)}buildRequest(){const e={requestUri:VT,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const n={};this.idToken&&(n.id_token=this.idToken),this.accessToken&&(n.access_token=this.accessToken),this.secret&&(n.oauth_token_secret=this.secret),n.providerId=this.providerId,this.nonce&&!this.pendingToken&&(n.nonce=this.nonce),e.postBody=yi(n)}return e}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class p_{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}}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Ks extends p_{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class yn extends Ks{constructor(){super("facebook.com")}static credential(e){return yr._fromParams({providerId:yn.PROVIDER_ID,signInMethod:yn.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return yn.credentialFromTaggedObject(e)}static credentialFromError(e){return yn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return yn.credential(e.oauthAccessToken)}catch{return null}}}yn.FACEBOOK_SIGN_IN_METHOD="facebook.com";yn.PROVIDER_ID="facebook.com";/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class _n extends Ks{constructor(){super("google.com"),this.addScope("profile")}static credential(e,n){return yr._fromParams({providerId:_n.PROVIDER_ID,signInMethod:_n.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:n})}static credentialFromResult(e){return _n.credentialFromTaggedObject(e)}static credentialFromError(e){return _n.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:n,oauthAccessToken:r}=e;if(!n&&!r)return null;try{return _n.credential(n,r)}catch{return null}}}_n.GOOGLE_SIGN_IN_METHOD="google.com";_n.PROVIDER_ID="google.com";/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class wn extends Ks{constructor(){super("github.com")}static credential(e){return yr._fromParams({providerId:wn.PROVIDER_ID,signInMethod:wn.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return wn.credentialFromTaggedObject(e)}static credentialFromError(e){return wn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return wn.credential(e.oauthAccessToken)}catch{return null}}}wn.GITHUB_SIGN_IN_METHOD="github.com";wn.PROVIDER_ID="github.com";/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Sn extends Ks{constructor(){super("twitter.com")}static credential(e,n){return yr._fromParams({providerId:Sn.PROVIDER_ID,signInMethod:Sn.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:n})}static credentialFromResult(e){return Sn.credentialFromTaggedObject(e)}static credentialFromError(e){return Sn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:n,oauthTokenSecret:r}=e;if(!n||!r)return null;try{return Sn.credential(n,r)}catch{return null}}}Sn.TWITTER_SIGN_IN_METHOD="twitter.com";Sn.PROVIDER_ID="twitter.com";/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function HT(t,e){return Xy(t,"POST","/v1/accounts:signUp",la(t,e))}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class Hn{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,n,r,i=!1){const s=await Qt._fromIdTokenResponse(e,r,i),o=Pp(r);return new Hn({user:s,providerId:o,_tokenResponse:r,operationType:n})}static async _forOperation(e,n,r){await e._updateTokensIfNecessary(r,!0);const i=Pp(r);return new Hn({user:e,providerId:i,_tokenResponse:r,operationType:n})}}function Pp(t){return t.providerId?t.providerId:"phoneNumber"in t?"phone":null}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function GT(t){var e;if(Gt(t.app))return Promise.reject(Un(t));const n=aa(t);if(await n._initializationPromise,!((e=n.currentUser)===null||e===void 0)&&e.isAnonymous)return new Hn({user:n.currentUser,providerId:null,operationType:"signIn"});const r=await HT(n,{returnSecureToken:!0}),i=await Hn._fromIdTokenResponse(n,"signIn",r,!0);return await n._updateCurrentUser(i.user),i}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class kl extends Yn{constructor(e,n,r,i){var s;super(n.code,n.message),this.operationType=r,this.user=i,Object.setPrototypeOf(this,kl.prototype),this.customData={appName:e.name,tenantId:(s=e.tenantId)!==null&&s!==void 0?s:void 0,_serverResponse:n.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,n,r,i){return new kl(e,n,r,i)}}function m_(t,e,n,r){return(e==="reauthenticate"?n._getReauthenticationResolver(t):n._getIdTokenResponse(t)).catch(s=>{throw s.code==="auth/multi-factor-auth-required"?kl._fromErrorAndOperation(t,s,e,r):s})}async function qT(t,e,n=!1){const r=await Rs(t,e._linkToIdToken(t.auth,await t.getIdToken()),n);return Hn._forOperation(t,"link",r)}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function KT(t,e,n=!1){const{auth:r}=t;if(Gt(r.app))return Promise.reject(Un(r));const i="reauthenticate";try{const s=await Rs(t,m_(r,i,e,t),n);W(s.idToken,r,"internal-error");const o=oh(s.idToken);W(o,r,"internal-error");const{sub:l}=o;return W(t.uid===l,r,"user-mismatch"),Hn._forOperation(t,i,s)}catch(s){throw(s==null?void 0:s.code)==="auth/user-not-found"&&ln(r,"user-mismatch"),s}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function QT(t,e,n=!1){if(Gt(t.app))return Promise.reject(Un(t));const r="signIn",i=await m_(t,r,e),s=await Hn._fromIdTokenResponse(t,r,i);return n||await t._updateCurrentUser(s.user),s}function YT(t,e,n,r){return Et(t).onIdTokenChanged(e,n,r)}function JT(t,e,n){return Et(t).beforeAuthStateChanged(e,n)}const Tl="__sak";/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class g_{constructor(e,n){this.storageRetriever=e,this.type=n}_isAvailable(){try{return this.storage?(this.storage.setItem(Tl,"1"),this.storage.removeItem(Tl),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,n){return this.storage.setItem(e,JSON.stringify(n)),Promise.resolve()}_get(e){const n=this.storage.getItem(e);return Promise.resolve(n?JSON.parse(n):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const XT=1e3,ZT=10;class v_ extends g_{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,n)=>this.onStorageEvent(e,n),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=c_(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const n of Object.keys(this.listeners)){const r=this.storage.getItem(n),i=this.localCache[n];r!==i&&e(n,i,r)}}onStorageEvent(e,n=!1){if(!e.key){this.forAllChangedKeys((o,l,a)=>{this.notifyListeners(o,a)});return}const r=e.key;n?this.detachListener():this.stopPolling();const i=()=>{const o=this.storage.getItem(r);!n&&this.localCache[r]===o||this.notifyListeners(r,o)},s=this.storage.getItem(r);PT()&&s!==e.newValue&&e.newValue!==e.oldValue?setTimeout(i,ZT):i()}notifyListeners(e,n){this.localCache[e]=n;const r=this.listeners[e];if(r)for(const i of Array.from(r))i(n&&JSON.parse(n))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,n,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:n,newValue:r}),!0)})},XT)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,n){Object.keys(this.listeners).length===0&&(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(n)}_removeListener(e,n){this.listeners[e]&&(this.listeners[e].delete(n),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&(this.detachListener(),this.stopPolling())}async _set(e,n){await super._set(e,n),this.localCache[e]=JSON.stringify(n)}async _get(e){const n=await super._get(e);return this.localCache[e]=JSON.stringify(n),n}async _remove(e){await super._remove(e),delete this.localCache[e]}}v_.type="LOCAL";const e1=v_;/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class y_ extends g_{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,n){}_removeListener(e,n){}}y_.type="SESSION";const __=y_;/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function t1(t){return Promise.all(t.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(n){return{fulfilled:!1,reason:n}}}))}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class ua{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const n=this.receivers.find(i=>i.isListeningto(e));if(n)return n;const r=new ua(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const n=e,{eventId:r,eventType:i,data:s}=n.data,o=this.handlersMap[i];if(!(o!=null&&o.size))return;n.ports[0].postMessage({status:"ack",eventId:r,eventType:i});const l=Array.from(o).map(async u=>u(n.origin,s)),a=await t1(l);n.ports[0].postMessage({status:"done",eventId:r,eventType:i,response:a})}_subscribe(e,n){Object.keys(this.handlersMap).length===0&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(n)}_unsubscribe(e,n){this.handlersMap[e]&&n&&this.handlersMap[e].delete(n),(!n||this.handlersMap[e].size===0)&&delete this.handlersMap[e],Object.keys(this.handlersMap).length===0&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}ua.receivers=[];/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function uh(t="",e=10){let n="";for(let r=0;r{const u=uh("",20);i.port1.start();const h=setTimeout(()=>{a(new Error("unsupported_event"))},r);o={messageChannel:i,onMessage(d){const f=d;if(f.data.eventId===u)switch(f.data.status){case"ack":clearTimeout(h),s=setTimeout(()=>{a(new Error("timeout"))},3e3);break;case"done":clearTimeout(s),l(f.data.response);break;default:clearTimeout(h),clearTimeout(s),a(new Error("invalid_response"));break}}},this.handlers.add(o),i.port1.addEventListener("message",o.onMessage),this.target.postMessage({eventType:e,eventId:u,data:n},[i.port2])}).finally(()=>{o&&this.removeMessageHandler(o)})}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function zt(){return window}function r1(t){zt().location.href=t}/** - * @license - * Copyright 2020 Google LLC. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function w_(){return typeof zt().WorkerGlobalScope<"u"&&typeof zt().importScripts=="function"}async function i1(){if(!(navigator!=null&&navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}function s1(){var t;return((t=navigator==null?void 0:navigator.serviceWorker)===null||t===void 0?void 0:t.controller)||null}function o1(){return w_()?self:null}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const S_="firebaseLocalStorageDb",l1=1,bl="firebaseLocalStorage",C_="fbase_key";class Qs{constructor(e){this.request=e}toPromise(){return new Promise((e,n)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{n(this.request.error)})})}}function ca(t,e){return t.transaction([bl],e?"readwrite":"readonly").objectStore(bl)}function a1(){const t=indexedDB.deleteDatabase(S_);return new Qs(t).toPromise()}function gc(){const t=indexedDB.open(S_,l1);return new Promise((e,n)=>{t.addEventListener("error",()=>{n(t.error)}),t.addEventListener("upgradeneeded",()=>{const r=t.result;try{r.createObjectStore(bl,{keyPath:C_})}catch(i){n(i)}}),t.addEventListener("success",async()=>{const r=t.result;r.objectStoreNames.contains(bl)?e(r):(r.close(),await a1(),e(await gc()))})})}async function Np(t,e,n){const r=ca(t,!0).put({[C_]:e,value:n});return new Qs(r).toPromise()}async function u1(t,e){const n=ca(t,!1).get(e),r=await new Qs(n).toPromise();return r===void 0?null:r.value}function Rp(t,e){const n=ca(t,!0).delete(e);return new Qs(n).toPromise()}const c1=800,d1=3;class E_{constructor(){this.type="LOCAL",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.db?this.db:(this.db=await gc(),this.db)}async _withRetries(e){let n=0;for(;;)try{const r=await this._openDb();return await e(r)}catch(r){if(n++>d1)throw r;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return w_()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=ua._getInstance(o1()),this.receiver._subscribe("keyChanged",async(e,n)=>({keyProcessed:(await this._poll()).includes(n.key)})),this.receiver._subscribe("ping",async(e,n)=>["keyChanged"])}async initializeSender(){var e,n;if(this.activeServiceWorker=await i1(),!this.activeServiceWorker)return;this.sender=new n1(this.activeServiceWorker);const r=await this.sender._send("ping",{},800);r&&!((e=r[0])===null||e===void 0)&&e.fulfilled&&!((n=r[0])===null||n===void 0)&&n.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(!(!this.sender||!this.activeServiceWorker||s1()!==this.activeServiceWorker))try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await gc();return await Np(e,Tl,"1"),await Rp(e,Tl),!0}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,n){return this._withPendingWrite(async()=>(await this._withRetries(r=>Np(r,e,n)),this.localCache[e]=n,this.notifyServiceWorker(e)))}async _get(e){const n=await this._withRetries(r=>u1(r,e));return this.localCache[e]=n,n}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(n=>Rp(n,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){const e=await this._withRetries(i=>{const s=ca(i,!1).getAll();return new Qs(s).toPromise()});if(!e)return[];if(this.pendingWrites!==0)return[];const n=[],r=new Set;if(e.length!==0)for(const{fbase_key:i,value:s}of e)r.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(s)&&(this.notifyListeners(i,s),n.push(i));for(const i of Object.keys(this.localCache))this.localCache[i]&&!r.has(i)&&(this.notifyListeners(i,null),n.push(i));return n}notifyListeners(e,n){this.localCache[e]=n;const r=this.listeners[e];if(r)for(const i of Array.from(r))i(n)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),c1)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,n){Object.keys(this.listeners).length===0&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(n)}_removeListener(e,n){this.listeners[e]&&(this.listeners[e].delete(n),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&this.stopPolling()}}E_.type="LOCAL";const h1=E_;new qs(3e4,6e4);/** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function f1(t,e){return e?Yt(e):(W(t._popupRedirectResolver,t,"argument-error"),t._popupRedirectResolver)}/** - * @license - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class ch extends f_{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Xr(e,this._buildIdpRequest())}_linkToIdToken(e,n){return Xr(e,this._buildIdpRequest(n))}_getReauthenticationResolver(e){return Xr(e,this._buildIdpRequest())}_buildIdpRequest(e){const n={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&&(n.idToken=e),n}}function p1(t){return QT(t.auth,new ch(t),t.bypassAuthState)}function m1(t){const{auth:e,user:n}=t;return W(n,e,"internal-error"),KT(n,new ch(t),t.bypassAuthState)}async function g1(t){const{auth:e,user:n}=t;return W(n,e,"internal-error"),qT(n,new ch(t),t.bypassAuthState)}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class x_{constructor(e,n,r,i,s=!1){this.auth=e,this.resolver=r,this.user=i,this.bypassAuthState=s,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(n)?n:[n]}execute(){return new Promise(async(e,n)=>{this.pendingPromise={resolve:e,reject:n};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(r){this.reject(r)}})}async onAuthEvent(e){const{urlResponse:n,sessionId:r,postBody:i,tenantId:s,error:o,type:l}=e;if(o){this.reject(o);return}const a={auth:this.auth,requestUri:n,sessionId:r,tenantId:s||void 0,postBody:i||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(l)(a))}catch(u){this.reject(u)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return p1;case"linkViaPopup":case"linkViaRedirect":return g1;case"reauthViaPopup":case"reauthViaRedirect":return m1;default:ln(this.auth,"internal-error")}}resolve(e){an(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){an(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()}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const v1=new qs(2e3,1e4);class Br extends x_{constructor(e,n,r,i,s){super(e,n,i,s),this.provider=r,this.authWindow=null,this.pollId=null,Br.currentPopupAction&&Br.currentPopupAction.cancel(),Br.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return W(e,this.auth,"internal-error"),e}async onExecution(){an(this.filter.length===1,"Popup operations only handle one event");const e=uh();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(n=>{this.reject(n)}),this.resolver._isIframeWebStorageSupported(this.auth,n=>{n||this.reject(Ut(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return((e=this.authWindow)===null||e===void 0?void 0:e.associatedEvent)||null}cancel(){this.reject(Ut(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Br.currentPopupAction=null}pollUserCancellation(){const e=()=>{var n,r;if(!((r=(n=this.authWindow)===null||n===void 0?void 0:n.window)===null||r===void 0)&&r.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Ut(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(e,v1.get())};e()}}Br.currentPopupAction=null;/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const y1="pendingRedirect",Ao=new Map;class _1 extends x_{constructor(e,n,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],n,void 0,r),this.eventId=null}async execute(){let e=Ao.get(this.auth._key());if(!e){try{const r=await w1(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(r)}catch(n){e=()=>Promise.reject(n)}Ao.set(this.auth._key(),e)}return this.bypassAuthState||Ao.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if(e.type==="signInViaRedirect")return super.onAuthEvent(e);if(e.type==="unknown"){this.resolve(null);return}if(e.eventId){const n=await this.auth._redirectUserForId(e.eventId);if(n)return this.user=n,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function w1(t,e){const n=E1(e),r=C1(t);if(!await r._isAvailable())return!1;const i=await r._get(n)==="true";return await r._remove(n),i}function S1(t,e){Ao.set(t._key(),e)}function C1(t){return Yt(t._redirectPersistence)}function E1(t){return Ro(y1,t.config.apiKey,t.name)}async function x1(t,e,n=!1){if(Gt(t.app))return Promise.reject(Un(t));const r=aa(t),i=f1(r,e),o=await new _1(r,i,n).execute();return o&&!n&&(delete o.user._redirectEventId,await r._persistUserIfCurrent(o.user),await r._setRedirectUser(null,e)),o}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const I1=10*60*1e3;class k1{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 n=!1;return this.consumers.forEach(r=>{this.isEventForConsumer(e,r)&&(n=!0,this.sendToConsumer(e,r),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!T1(e)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=e,n=!0)),n}sendToConsumer(e,n){var r;if(e.error&&!I_(e)){const i=((r=e.error.code)===null||r===void 0?void 0:r.split("auth/")[1])||"internal-error";n.onError(Ut(this.auth,i))}else n.onAuthEvent(e)}isEventForConsumer(e,n){const r=n.eventId===null||!!e.eventId&&e.eventId===n.eventId;return n.filter.includes(e.type)&&r}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=I1&&this.cachedEventUids.clear(),this.cachedEventUids.has(Ap(e))}saveEventToCache(e){this.cachedEventUids.add(Ap(e)),this.lastProcessedEventTime=Date.now()}}function Ap(t){return[t.type,t.eventId,t.sessionId,t.tenantId].filter(e=>e).join("-")}function I_({type:t,error:e}){return t==="unknown"&&(e==null?void 0:e.code)==="auth/no-auth-event"}function T1(t){switch(t.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return I_(t);default:return!1}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */async function b1(t,e={}){return Ei(t,"GET","/v1/projects",e)}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const P1=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,N1=/^https?/;async function R1(t){if(t.config.emulator)return;const{authorizedDomains:e}=await b1(t);for(const n of e)try{if(A1(n))return}catch{}ln(t,"unauthorized-domain")}function A1(t){const e=pc(),{protocol:n,hostname:r}=new URL(e);if(t.startsWith("chrome-extension://")){const o=new URL(t);return o.hostname===""&&r===""?n==="chrome-extension:"&&t.replace("chrome-extension://","")===e.replace("chrome-extension://",""):n==="chrome-extension:"&&o.hostname===r}if(!N1.test(n))return!1;if(P1.test(t))return r===t;const i=t.replace(/\./g,"\\.");return new RegExp("^(.+\\."+i+"|"+i+")$","i").test(r)}/** - * @license - * Copyright 2020 Google LLC. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const O1=new qs(3e4,6e4);function Op(){const t=zt().___jsl;if(t!=null&&t.H){for(const e of Object.keys(t.H))if(t.H[e].r=t.H[e].r||[],t.H[e].L=t.H[e].L||[],t.H[e].r=[...t.H[e].L],t.CP)for(let n=0;n{var r,i,s;function o(){Op(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Op(),n(Ut(t,"network-request-failed"))},timeout:O1.get()})}if(!((i=(r=zt().gapi)===null||r===void 0?void 0:r.iframes)===null||i===void 0)&&i.Iframe)e(gapi.iframes.getContext());else if(!((s=zt().gapi)===null||s===void 0)&&s.load)o();else{const l=FT("iframefcb");return zt()[l]=()=>{gapi.load?o():n(Ut(t,"network-request-failed"))},MT(`${jT()}?onload=${l}`).catch(a=>n(a))}}).catch(e=>{throw Oo=null,e})}let Oo=null;function L1(t){return Oo=Oo||D1(t),Oo}/** - * @license - * Copyright 2020 Google LLC. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const M1=new qs(5e3,15e3),j1="__/auth/iframe",F1="emulator/auth/iframe",U1={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},z1=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function B1(t){const e=t.config;W(e.authDomain,t,"auth-domain-config-required");const n=e.emulator?sh(e,F1):`https://${t.config.authDomain}/${j1}`,r={apiKey:e.apiKey,appName:t.name,v:_i},i=z1.get(t.config.apiHost);i&&(r.eid=i);const s=t._getFrameworks();return s.length&&(r.fw=s.join(",")),`${n}?${yi(r).slice(1)}`}async function W1(t){const e=await L1(t),n=zt().gapi;return W(n,t,"internal-error"),e.open({where:document.body,url:B1(t),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:U1,dontclear:!0},r=>new Promise(async(i,s)=>{await r.restyle({setHideOnLeave:!1});const o=Ut(t,"network-request-failed"),l=zt().setTimeout(()=>{s(o)},M1.get());function a(){zt().clearTimeout(l),i(r)}r.ping(a).then(a,()=>{s(o)})}))}/** - * @license - * Copyright 2020 Google LLC. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const $1={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"},V1=500,H1=600,G1="_blank",q1="http://localhost";class Dp{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch{}}}function K1(t,e,n,r=V1,i=H1){const s=Math.max((window.screen.availHeight-i)/2,0).toString(),o=Math.max((window.screen.availWidth-r)/2,0).toString();let l="";const a=Object.assign(Object.assign({},$1),{width:r.toString(),height:i.toString(),top:s,left:o}),u=Je().toLowerCase();n&&(l=s_(u)?G1:n),r_(u)&&(e=e||q1,a.scrollbars="yes");const h=Object.entries(a).reduce((f,[v,w])=>`${f}${v}=${w},`,"");if(bT(u)&&l!=="_self")return Q1(e||"",l),new Dp(null);const d=window.open(e||"",l,h);W(d,t,"popup-blocked");try{d.focus()}catch{}return new Dp(d)}function Q1(t,e){const n=document.createElement("a");n.href=t,n.target=e;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}/** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Y1="__/auth/handler",J1="emulator/auth/handler",X1=encodeURIComponent("fac");async function Lp(t,e,n,r,i,s){W(t.config.authDomain,t,"auth-domain-config-required"),W(t.config.apiKey,t,"invalid-api-key");const o={apiKey:t.config.apiKey,appName:t.name,authType:n,redirectUrl:r,v:_i,eventId:i};if(e instanceof p_){e.setDefaultLanguage(t.languageCode),o.providerId=e.providerId||"",Ku(e.getCustomParameters())||(o.customParameters=JSON.stringify(e.getCustomParameters()));for(const[h,d]of Object.entries({}))o[h]=d}if(e instanceof Ks){const h=e.getScopes().filter(d=>d!=="");h.length>0&&(o.scopes=h.join(","))}t.tenantId&&(o.tid=t.tenantId);const l=o;for(const h of Object.keys(l))l[h]===void 0&&delete l[h];const a=await t._getAppCheckToken(),u=a?`#${X1}=${encodeURIComponent(a)}`:"";return`${Z1(t)}?${yi(l).slice(1)}${u}`}function Z1({config:t}){return t.emulator?sh(t,J1):`https://${t.authDomain}/${Y1}`}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const Xa="webStorageSupport";class eb{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=__,this._completeRedirectFn=x1,this._overrideRedirectResult=S1}async _openPopup(e,n,r,i){var s;an((s=this.eventManagers[e._key()])===null||s===void 0?void 0:s.manager,"_initialize() not called before _openPopup()");const o=await Lp(e,n,r,pc(),i);return K1(e,o,uh())}async _openRedirect(e,n,r,i){await this._originValidation(e);const s=await Lp(e,n,r,pc(),i);return r1(s),new Promise(()=>{})}_initialize(e){const n=e._key();if(this.eventManagers[n]){const{manager:i,promise:s}=this.eventManagers[n];return i?Promise.resolve(i):(an(s,"If manager is not set, promise should be"),s)}const r=this.initAndGetManager(e);return this.eventManagers[n]={promise:r},r.catch(()=>{delete this.eventManagers[n]}),r}async initAndGetManager(e){const n=await W1(e),r=new k1(e);return n.register("authEvent",i=>(W(i==null?void 0:i.authEvent,e,"invalid-auth-event"),{status:r.onEvent(i.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:r},this.iframes[e._key()]=n,r}_isIframeWebStorageSupported(e,n){this.iframes[e._key()].send(Xa,{type:Xa},i=>{var s;const o=(s=i==null?void 0:i[0])===null||s===void 0?void 0:s[Xa];o!==void 0&&n(!!o),ln(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const n=e._key();return this.originValidationPromises[n]||(this.originValidationPromises[n]=R1(e)),this.originValidationPromises[n]}get _shouldInitProactively(){return c_()||i_()||lh()}}const tb=eb;var Mp="@firebase/auth",jp="1.7.9";/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */class nb{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),((e=this.auth.currentUser)===null||e===void 0?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const n=this.auth.onIdTokenChanged(r=>{e((r==null?void 0:r.stsTokenManager.accessToken)||null)});this.internalListeners.set(e,n),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const n=this.internalListeners.get(e);n&&(this.internalListeners.delete(e),n(),this.updateProactiveRefresh())}assertAuthConfigured(){W(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */function rb(t){switch(t){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function ib(t){li(new fr("auth",(e,{options:n})=>{const r=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),s=e.getProvider("app-check-internal"),{apiKey:o,authDomain:l}=r.options;W(o&&!o.includes(":"),"invalid-api-key",{appName:r.name});const a={apiKey:o,authDomain:l,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:d_(t)},u=new DT(r,i,s,a);return zT(u,n),u},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,n,r)=>{e.getProvider("auth-internal").initialize()})),li(new fr("auth-internal",e=>{const n=aa(e.getProvider("auth").getImmediate());return(r=>new nb(r))(n)},"PRIVATE").setInstantiationMode("EXPLICIT")),Mn(Mp,jp,rb(t)),Mn(Mp,jp,"esm2017")}/** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */const sb=5*60,ob=kv("authIdTokenMaxAge")||sb;let Fp=null;const lb=t=>async e=>{const n=e&&await e.getIdTokenResult(),r=n&&(new Date().getTime()-Date.parse(n.issuedAtTime))/1e3;if(r&&r>ob)return;const i=n==null?void 0:n.token;Fp!==i&&(Fp=i,await fetch(t,{method:i?"POST":"DELETE",headers:i?{Authorization:`Bearer ${i}`}:{}}))};function ab(t=Av()){const e=Ed(t,"auth");if(e.isInitialized())return e.getImmediate();const n=UT(t,{popupRedirectResolver:tb,persistence:[h1,e1,__]}),r=kv("authTokenSyncURL");if(r&&typeof isSecureContext=="boolean"&&isSecureContext){const s=new URL(r,location.origin);if(location.origin===s.origin){const o=lb(s.toString());JT(n,o,()=>o(n.currentUser)),YT(n,l=>o(l))}}const i=xv("auth");return i&&BT(n,`http://${i}`),n}function ub(){var t,e;return(e=(t=document.getElementsByTagName("head"))===null||t===void 0?void 0:t[0])!==null&&e!==void 0?e:document}LT({loadJS(t){return new Promise((e,n)=>{const r=document.createElement("script");r.setAttribute("src",t),r.onload=e,r.onerror=i=>{const s=Ut("internal-error");s.customData=i,n(s)},r.type="text/javascript",r.charset="UTF-8",ub().appendChild(r)})},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="});ib("Browser");const cb={apiKey:"AIzaSyBiZSV4Z_3-L0z8RP5yY_2xXlw5fKOy2jc",authDomain:"classroom-polling-dd344.firebaseapp.com",databaseURL:"https://classroom-polling-dd344-default-rtdb.firebaseio.com",projectId:"classroom-polling-dd344",storageBucket:"classroom-polling-dd344.firebasestorage.app",messagingSenderId:"528103899828",appId:"1:528103899828:web:f74274640de611a61d0de1"},k_=Rv(cb),re=aT(k_),db=ab(k_);GT(db).catch(console.error);function T_(t){const e=new Date().toLocaleDateString("en-CA");return on(ne(re,`session/students/${t}`),{joinedAt:Sp(),date:e}),on(ne(re,`sessionStudents/${e}_${t}`),{name:t,date:e,joinedAt:Sp()})}function vc(t){return vr(ne(re,`session/students/${t}`))}function b_(t,e,n){return sa(ne(re,"session/activePoll/responses"),{[t]:n})}function Pl({question:t,options:e,correctIndex:n,duration:r,resultPolicy:i,correctPolicy:s}){const o=`poll_${Date.now()}`;return on(ne(re,"session/activePoll"),{id:o,question:t,options:e,correctIndex:n??null,duration:r,resultPolicy:i,correctPolicy:s,startedAt:Date.now(),responses:{},ended:!1,revealResults:!1,revealCorrect:!1})}async function Do(t,e){const[n,r]=await Promise.all([Ns(ne(re,"session/activePoll")),Ns(ne(re,"session/queue"))]),i=n.val(),s=r.val();if(!i)return;const o={...i,revealResults:t,revealCorrect:e,endedAt:Date.now()};return s&&(o.setId=s.setId,o.setName=s.setName,o.setPosition=s.currentIndex,o.sessionKey=s.sessionKey),await on(ne(re,`pollHistory/${i.id}`),o),vr(ne(re,"session/activePoll"))}function P_(){return sa(ne(re,"session/activePoll"),{ended:!0})}function yc(t,e){return sa(ne(re,"session/activePoll"),{revealResults:t,revealCorrect:e})}function dh(t){const e=ne(re,"session/activePoll");return xr(e,n=>t(n.val()))}function N_(t){const e=ne(re,"session/students");return xr(e,n=>{const r=n.val()||{};t(Object.keys(r).map(i=>({name:i,...r[i]})))})}function R_(t){const e=ne(re,"pollHistory");return xr(e,n=>{const r=n.val()||{},i=Object.values(r).sort((s,o)=>(o.startedAt||0)-(s.startedAt||0));t(i)})}function A_(t){const e=ne(re,"pollSets");return xr(e,n=>{const r=n.val()||{},i=Object.entries(r).map(([s,o])=>({id:s,...o})).sort((s,o)=>(o.createdAt||0)-(s.createdAt||0));t(i)})}async function _c({name:t,defaults:e,polls:n}){const r=`set_${Date.now()}`;return await on(ne(re,`pollSets/${r}`),{id:r,name:t,createdAt:Date.now(),defaults:e,polls:n||[]}),r}function Lo(t,e){return Ns(ne(re,`pollSets/${t}`)).then(n=>{const r=n.val()||{};return on(ne(re,`pollSets/${t}`),{...r,...e})})}function O_(t){return vr(ne(re,`pollSets/${t}`))}function D_(t,e){const n=ne(re,`pollSets/${t}`);return xr(n,r=>e(r.val()))}function L_(t,e,n){const r=`run_${Date.now()}`;return on(ne(re,"session/queue"),{setId:t,setName:e,currentIndex:0,totalPolls:n,sessionKey:r})}function M_(t){return sa(ne(re,"session/queue"),{currentIndex:t})}function wc(){return vr(ne(re,"session/queue"))}function j_(t){const e=ne(re,"session/queue");return xr(e,n=>t(n.val()))}async function F_(t,e){const r=(await Ns(ne(re,"session/activePoll"))).val(),s=(await Ns(ne(re,"session/queue"))).val();if(!r)return;const o={...r,revealResults:t,revealCorrect:e,endedAt:Date.now()};return s&&(o.setId=s.setId,o.setName=s.setName,o.setPosition=s.currentIndex,o.sessionKey=s.sessionKey),await on(ne(re,`pollHistory/${r.id}`),o),vr(ne(re,"session/activePoll"))}const hb=Object.freeze(Object.defineProperty({__proto__:null,advanceQueue:M_,clearQueue:wc,closePoll:F_,createPollSet:_c,deletePollSet:O_,endPoll:Do,expirePoll:P_,joinSession:T_,launchSet:L_,leaveSession:vc,revealPollResults:yc,startPoll:Pl,submitAnswer:b_,updatePollSet:Lo,watchActivePoll:dh,watchPollHistory:R_,watchPollSet:D_,watchPollSets:A_,watchQueue:j_,watchStudents:N_},Symbol.toStringTag,{value:"Module"})),Up=60,fb=[{value:"on_submit",label:"After they submit"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}],pb=[{value:"with_results",label:"With results"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}];function mb(){var Ge;const t=Sr(),[e,n]=C.useState([]),[r,i]=C.useState(null),[s,o]=C.useState(0),[l,a]=C.useState("dashboard"),[u,h]=C.useState(null),[d,f]=C.useState(null),v=C.useRef(null),w=C.useRef(null),_=C.useRef(null),[E,g]=C.useState(""),[p,m]=C.useState(["",""]),[S,I]=C.useState(null),[P,b]=C.useState(Up),[A,q]=C.useState("on_submit"),[z,pe]=C.useState("with_results");C.useEffect(()=>{localStorage.getItem("role")!=="instructor"&&t("/")},[]),C.useEffect(()=>{const L=dh(xe=>{xe&&(_.current=xe),i(xe),xe&&!xe.ended&&o(Math.max(0,Math.round(xe.duration-(Date.now()-xe.startedAt)/1e3)))}),te=N_(n),Te=j_(xe=>{h(xe),xe!=null&&xe.setId?(w.current&&w.current(),gC(async()=>{const{watchPollSet:Ir}=await Promise.resolve().then(()=>hb);return{watchPollSet:Ir}},void 0).then(({watchPollSet:Ir})=>{w.current=Ir(xe.setId,f)})):(f(null),_.current=null,w.current&&(w.current(),w.current=null))});return()=>{L(),te(),Te()}},[]),C.useEffect(()=>(clearInterval(v.current),r&&!r.ended&&(v.current=setInterval(()=>{const L=Math.max(0,Math.round(r.duration-(Date.now()-r.startedAt)/1e3));o(L),L===0&&(clearInterval(v.current),P_())},500)),()=>clearInterval(v.current)),[r==null?void 0:r.id,r==null?void 0:r.ended]);function D(){p.length<6&&m([...p,""])}function Y(L,te){m(p.map((Te,xe)=>xe===L?te:Te))}function X(L){if(p.length<=2)return;const te=p.filter((Te,xe)=>xe!==L);m(te),S===L?I(null):S>L&&I(S-1)}function et(L){L.preventDefault();const te=p.filter(Te=>Te.trim());!E.trim()||te.length<2||(Pl({question:E.trim(),options:te,correctIndex:S,duration:P,resultPolicy:A,correctPolicy:z}),g(""),m(["",""]),I(null),b(Up),q("on_submit"),pe("with_results"),a("dashboard"))}async function Ee(){if(!u||!d)return;const L=u.currentIndex+1;if(r&&await Do(r.revealResults||!1,r.revealCorrect||!1),L>=u.totalPolls){await wc();return}await M_(L);const te=d.defaults||{},Te=(d.polls||[])[L];Te&&await Pl({question:Te.question,options:Te.options,correctIndex:Te.correctIndex??null,duration:Te.duration??te.duration??60,resultPolicy:Te.resultPolicy??te.resultPolicy??"on_submit",correctPolicy:Te.correctPolicy??te.correctPolicy??"with_results"})}async function Be(){r&&await Do(r.revealResults||!1,r.revealCorrect||!1),await wc()}const R=r?Object.keys(r.responses||{}).length:Object.keys(((Ge=_.current)==null?void 0:Ge.responses)||{}).length,U=r==null?void 0:r.ended,y=!!u,x=u&&u.currentIndex>=u.totalPolls-1,T=r||(y?_.current:null),O=!r&&T;function K(L){return L.revealResults?!0:!(L.resultPolicy==="never"||L.resultPolicy==="manual")}function tt(L){return L.revealCorrect?!0:L.correctPolicy==="never"||L.correctPolicy==="manual"?!1:!!(L.correctPolicy==="with_results"&&K(L))}return c.jsxs("div",{style:j.page,children:[c.jsxs("aside",{style:j.sidebar,children:[c.jsxs("div",{style:j.logo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsxs("nav",{style:j.nav,children:[c.jsx("button",{style:{...j.navBtn,...l==="dashboard"?j.navActive:{}},onClick:()=>a("dashboard"),children:"πŸ“Š Dashboard"}),c.jsx("button",{style:{...j.navBtn,...l==="create"?j.navActive:{},...r?j.navDisabled:{}},onClick:()=>!r&&a("create"),disabled:!!r,children:"βž• New Poll"}),c.jsx("button",{style:j.navBtn,onClick:()=>t("/pollsets"),children:"πŸ“š Poll Sets"}),c.jsx("button",{style:j.navBtn,onClick:()=>t("/history"),children:"πŸ• History"})]}),c.jsxs("div",{style:j.sidebarBottom,children:[c.jsxs("div",{style:j.studentCount,children:[c.jsx("span",{style:j.dot}),c.jsx("strong",{children:e.length})," student",e.length!==1?"s":""," online"]}),c.jsx("div",{style:j.studentList,children:e.map(L=>c.jsx("div",{style:j.studentChip,children:L.name},L.name))}),c.jsx("button",{className:"btn btn-secondary",style:{width:"100%",marginTop:"auto",fontSize:"0.8rem"},onClick:()=>{localStorage.removeItem("role"),localStorage.removeItem("historyAuth"),t("/")},children:"Exit"})]})]}),c.jsxs("main",{style:j.main,children:[l==="create"&&c.jsxs("div",{style:j.content,className:"fade-up",children:[c.jsx("h2",{style:j.pageTitle,children:"Create a Poll"}),c.jsxs("form",{onSubmit:et,style:j.form,children:[c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Question"}),c.jsx("textarea",{className:"input",rows:2,placeholder:"e.g. Which process converts sunlight into energy?",value:E,onChange:L=>g(L.target.value),style:{resize:"vertical",width:"100%"},required:!0})]}),c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Answer Options"}),c.jsx("p",{style:j.hint,children:"Click a letter circle to mark the correct answer (optional)"}),c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:p.map((L,te)=>c.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[c.jsx("button",{type:"button",style:{...j.correctBtn,...S===te?j.correctBtnActive:{}},onClick:()=>I(S===te?null:te),children:S===te?"βœ“":String.fromCharCode(65+te)}),c.jsx("input",{className:"input",style:{flex:1},placeholder:`Option ${String.fromCharCode(65+te)}`,value:L,onChange:Te=>Y(te,Te.target.value),required:!0}),c.jsx("button",{type:"button",style:j.removeBtn,onClick:()=>X(te),disabled:p.length<=2,children:"βœ•"})]},te))}),p.length<6&&c.jsx("button",{type:"button",className:"btn btn-ghost",style:{marginTop:"0.5rem",fontSize:"0.85rem"},onClick:D,children:"+ Add option"})]}),c.jsxs("div",{style:j.policySection,children:[c.jsx("label",{className:"label",children:"Show results to students"}),c.jsx("div",{style:j.policyRow,children:fb.map(L=>c.jsx("button",{type:"button",style:{...j.policyBtn,...A===L.value?j.policyBtnActive:{}},onClick:()=>q(L.value),children:c.jsx("span",{style:j.policyLabel,children:L.label})},L.value))})]}),S!=null&&c.jsxs("div",{style:j.policySection,children:[c.jsx("label",{className:"label",children:"Reveal correct answer to students"}),c.jsx("div",{style:j.policyRow,children:pb.map(L=>c.jsx("button",{type:"button",style:{...j.policyBtn,...z===L.value?j.policyBtnActive:{}},onClick:()=>pe(L.value),children:c.jsx("span",{style:j.policyLabel,children:L.label})},L.value))})]}),c.jsxs("div",{style:{display:"flex",gap:"1rem",alignItems:"flex-end"},children:[c.jsxs("div",{style:{flex:1},children:[c.jsx("label",{className:"label",children:"Duration (seconds)"}),c.jsx("input",{className:"input",type:"number",min:10,max:300,value:P,onChange:L=>b(Number(L.target.value))})]}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{padding:"0.65rem 2rem"},children:"Start Poll β†’"})]})]})]}),l==="dashboard"&&c.jsxs("div",{style:j.content,className:"fade-up",children:[y&&c.jsxs("div",{style:j.queueBanner,children:[c.jsx("span",{style:j.queueIcon,children:"πŸ“š"}),c.jsxs("div",{style:{flex:1},children:[c.jsx("div",{style:j.queueName,children:u.setName}),c.jsxs("div",{style:j.queueProgress,children:["Poll ",u.currentIndex+1," of ",u.totalPolls]})]}),c.jsx("div",{style:j.queueDots,children:Array.from({length:u.totalPolls},(L,te)=>c.jsx("div",{style:{...j.queueDot,background:tea("create"),children:"Create one β†’"})," ","or"," ",c.jsx("button",{style:j.link,onClick:()=>t("/pollsets"),children:"launch a set β†’"})]})]}),T&&c.jsxs("div",{style:j.pollCard,children:[c.jsxs("div",{style:j.timerRow,children:[r&&!U?c.jsx(gb,{timeLeft:s,total:r.duration}):c.jsx("div",{style:j.expiredBadge,children:"⏰"}),c.jsxs("div",{style:{flex:1},children:[c.jsx("div",{style:j.pollQuestion,children:T.question}),c.jsxs("div",{style:j.responseMeta,children:[R," / ",e.length," responded",(U||O)&&c.jsx("span",{style:j.expiredTag,children:O?" Β· Poll ended":" Β· Stopped accepting answers"})]})]})]}),c.jsx("div",{style:{marginTop:"1.25rem",display:"flex",flexDirection:"column",gap:"0.6rem"},children:T.options.map((L,te)=>{const Te=Object.values(T.responses||{}).filter(z_=>z_===te).length,xe=Object.keys(T.responses||{}).length,Ir=xe>0?Math.round(Te/xe*100):0,da=T.correctIndex===te;return c.jsxs("div",{style:j.optionRow,children:[c.jsxs("div",{style:{...j.optionLabel,...da?j.correctLabel:{}},children:[String.fromCharCode(65+te),da?"βœ“":""]}),c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"0.25rem"},children:[c.jsx("span",{style:{fontSize:"0.9rem"},children:L}),c.jsxs("span",{style:{fontSize:"0.85rem",color:"var(--muted)"},children:[Te," (",Ir,"%)"]})]}),c.jsx("div",{style:j.barBg,children:c.jsx("div",{style:{...j.barFill,width:`${Ir}%`,background:da?"var(--success)":"var(--accent2)"}})})]})]},te)})}),R>0&&c.jsxs("div",{style:{marginTop:"1rem"},children:[c.jsx("label",{className:"label",children:"Responded"}),c.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.4rem"},children:Object.keys(T.responses).map(L=>c.jsx("span",{style:j.answeredChip,children:L},L))})]}),c.jsxs("div",{style:j.controls,children:[c.jsx("label",{className:"label",style:{marginBottom:"0.75rem"},children:"Student display"}),c.jsxs("div",{style:j.controlGrid,children:[r&&r.resultPolicy==="manual"&&c.jsxs("div",{style:j.controlItem,children:[c.jsx("span",{style:j.controlLabel,children:"Results visible"}),c.jsx(zp,{active:!!r.revealResults,onChange:L=>yc(L,r.revealCorrect)})]}),r&&r.correctPolicy==="manual"&&r.correctIndex!=null&&c.jsxs("div",{style:j.controlItem,children:[c.jsx("span",{style:j.controlLabel,children:"Correct answer visible"}),c.jsx(zp,{active:!!r.revealCorrect,onChange:L=>yc(r.revealResults,L)})]}),c.jsxs("div",{style:j.statusSummary,children:[c.jsx(Bp,{label:"Results",state:T.resultPolicy==="never"?"never":T.resultPolicy==="on_submit"?"auto":T.revealResults?"shown":"hidden"}),T.correctIndex!=null&&c.jsx(Bp,{label:"Answer",state:T.correctPolicy==="never"?"never":tt(T)?"shown":"hidden"})]}),c.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"0.5rem",alignItems:"center"},children:[r&&c.jsx("button",{className:"btn btn-secondary",onClick:()=>y?F_(r.revealResults,r.revealCorrect):Do(r.revealResults,r.revealCorrect),children:y?"End Poll":"Close Poll"}),y&&c.jsx("button",{className:"btn btn-primary",onClick:Ee,children:x?"Finish Set βœ“":`Next Poll β†’ (${u.currentIndex+2} of ${u.totalPolls})`})]})]})]})]})]})]})]})}function zp({active:t,onChange:e}){return c.jsx("button",{onClick:()=>e(!t),style:{position:"relative",width:48,height:26,borderRadius:13,border:"none",background:t?"var(--success)":"var(--border)",cursor:"pointer",transition:"background 0.2s",flexShrink:0},children:c.jsx("span",{style:{position:"absolute",top:3,left:t?22:3,width:20,height:20,borderRadius:"50%",background:"white",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})})}function Bp({label:t,state:e}){const n={shown:{bg:"#dcfce7",color:"#15803d"},hidden:{bg:"#fee2e2",color:"#b91c1c"},auto:{bg:"#dbeafe",color:"#1d4ed8"},never:{bg:"var(--cream)",color:"var(--muted)"}},r={shown:"Shown",hidden:"Hidden",auto:"Auto",never:"Never"},i=n[e]||n.never;return c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem"},children:[c.jsxs("span",{style:{fontSize:"0.78rem",color:"var(--muted)"},children:[t,":"]}),c.jsx("span",{style:{background:i.bg,color:i.color,borderRadius:4,padding:"0.15rem 0.5rem",fontSize:"0.75rem",fontWeight:600},children:r[e]})]})}function gb({timeLeft:t,total:e}){const r=2*Math.PI*28,i=e>0?t/e:0,s=r*(1-i),o=i>.4?"var(--accent2)":i>.15?"#f59e0b":"var(--accent)";return c.jsxs("div",{style:{position:"relative",width:72,height:72,flexShrink:0},children:[c.jsxs("svg",{width:"72",height:"72",style:{transform:"rotate(-90deg)"},children:[c.jsx("circle",{cx:"36",cy:"36",r:28,fill:"none",stroke:"var(--cream)",strokeWidth:"5"}),c.jsx("circle",{cx:"36",cy:"36",r:28,fill:"none",stroke:o,strokeWidth:"5",strokeDasharray:r,strokeDashoffset:s,strokeLinecap:"round",style:{transition:"stroke-dashoffset 0.5s linear, stroke 0.5s"}})]}),c.jsx("span",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.1rem"},children:t})]})}const j={page:{display:"flex",minHeight:"100vh",background:"var(--paper)"},sidebar:{width:220,minHeight:"100vh",background:"var(--ink)",color:"white",display:"flex",flexDirection:"column",padding:"1.5rem 1rem",gap:"0.5rem",position:"sticky",top:0,flexShrink:0},logo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",padding:"0 0.5rem",marginBottom:"1rem"},nav:{display:"flex",flexDirection:"column",gap:"0.25rem"},navBtn:{background:"transparent",color:"rgba(255,255,255,0.7)",border:"none",borderRadius:8,padding:"0.6rem 0.75rem",textAlign:"left",cursor:"pointer",fontSize:"0.9rem",transition:"all 0.15s"},navActive:{background:"rgba(255,255,255,0.12)",color:"white"},navDisabled:{opacity:.4,cursor:"not-allowed"},sidebarBottom:{marginTop:"auto",display:"flex",flexDirection:"column",gap:"0.75rem"},studentCount:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem",color:"rgba(255,255,255,0.6)"},dot:{width:8,height:8,borderRadius:"50%",background:"#4ade80",flexShrink:0,boxShadow:"0 0 6px #4ade80"},studentList:{display:"flex",flexWrap:"wrap",gap:"0.35rem",maxHeight:120,overflowY:"auto"},studentChip:{background:"rgba(255,255,255,0.1)",borderRadius:4,padding:"0.2rem 0.5rem",fontSize:"0.78rem",color:"rgba(255,255,255,0.8)"},main:{flex:1,padding:"2rem",overflowY:"auto"},content:{maxWidth:"100%",margin:"0 auto"},pageTitle:{fontSize:"1.6rem",marginBottom:"1.5rem"},form:{display:"flex",flexDirection:"column",gap:"1.25rem",background:"white",padding:"1.5rem",borderRadius:12,border:"1px solid var(--border)"},hint:{fontSize:"0.82rem",color:"var(--muted)",marginBottom:"0.5rem"},policySection:{display:"flex",flexDirection:"column",gap:"0.5rem"},policyRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},policyBtn:{display:"flex",flexDirection:"column",gap:"0.2rem",padding:"0.6rem 0.85rem",borderRadius:8,border:"1.5px solid var(--border)",background:"var(--paper)",cursor:"pointer",textAlign:"left",transition:"all 0.15s",flex:1,minWidth:120},policyBtnActive:{borderColor:"var(--accent2)",background:"#eff6ff"},policyLabel:{fontSize:"0.88rem",fontWeight:600,color:"var(--ink)"},empty:{textAlign:"center",padding:"4rem 2rem",color:"var(--muted)",display:"flex",flexDirection:"column",alignItems:"center",gap:"0.75rem"},link:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"inherit",textDecoration:"underline"},queueBanner:{display:"flex",alignItems:"center",gap:"0.75rem",background:"#eff6ff",border:"1.5px solid var(--accent2)",borderRadius:12,padding:"0.75rem 1rem",marginBottom:"1.25rem"},queueIcon:{fontSize:"1.4rem"},queueName:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"0.95rem"},queueProgress:{color:"var(--accent2)",fontSize:"0.82rem",marginTop:"0.1rem"},queueDots:{display:"flex",gap:"0.35rem",alignItems:"center"},queueDot:{width:10,height:10,borderRadius:"50%",transition:"background 0.3s"},queueExit:{background:"none",border:"1px solid var(--border)",borderRadius:6,padding:"0.3rem 0.6rem",fontSize:"0.78rem",cursor:"pointer",color:"var(--muted)"},pollCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1.5rem"},timerRow:{display:"flex",alignItems:"center",gap:"1rem"},pollQuestion:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.1rem"},responseMeta:{color:"var(--muted)",fontSize:"0.85rem",marginTop:"0.2rem"},expiredBadge:{width:72,height:72,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.8rem",flexShrink:0},expiredTag:{color:"var(--accent)",fontWeight:500},optionRow:{display:"flex",alignItems:"center",gap:"0.75rem"},optionLabel:{width:28,height:28,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.8rem",fontWeight:700,flexShrink:0},correctLabel:{background:"#dcfce7",color:"var(--success)"},barBg:{height:8,borderRadius:4,background:"var(--cream)",overflow:"hidden"},barFill:{height:"100%",borderRadius:4,transition:"width 0.4s ease"},answeredChip:{background:"#dbeafe",color:"var(--accent2)",borderRadius:4,padding:"0.15rem 0.5rem",fontSize:"0.78rem"},correctBtn:{width:32,height:32,borderRadius:"50%",border:"2px solid var(--border)",background:"var(--cream)",cursor:"pointer",fontWeight:700,fontSize:"0.8rem",flexShrink:0,transition:"all 0.15s"},correctBtnActive:{background:"var(--success)",color:"white",borderColor:"var(--success)"},removeBtn:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",fontSize:"0.9rem",padding:"0.25rem",borderRadius:4},controls:{marginTop:"1.25rem",paddingTop:"1.25rem",borderTop:"1px solid var(--border)"},controlGrid:{display:"flex",gap:"1rem",alignItems:"center",flexWrap:"wrap"},controlItem:{display:"flex",alignItems:"center",gap:"0.6rem"},controlLabel:{fontSize:"0.85rem",color:"var(--muted)"},statusSummary:{display:"flex",gap:"0.75rem",flexWrap:"wrap"}};function vb(){var D;const t=Sr(),[e,n]=C.useState(""),[r,i]=C.useState(!1),[s,o]=C.useState(null),[l,a]=C.useState(null),[u,h]=C.useState(!1),[d,f]=C.useState(0),[v,w]=C.useState(null),_=C.useRef(null),E=C.useRef(null);C.useEffect(()=>dh(X=>{!X&&s&&(w(s),setTimeout(()=>w(null),1e4)),X&&X.id!==E.current&&(a(null),h(!1),E.current=X.id),o(X),X&&!X.ended&&f(Math.max(0,Math.round(X.duration-(Date.now()-X.startedAt)/1e3)))}),[s]),C.useEffect(()=>(clearInterval(_.current),s&&!s.ended&&(_.current=setInterval(()=>{const Y=Math.max(0,Math.round(s.duration-(Date.now()-s.startedAt)/1e3));f(Y),Y===0&&clearInterval(_.current)},500)),()=>clearInterval(_.current)),[s==null?void 0:s.id,s==null?void 0:s.ended]),C.useEffect(()=>{if(!r||!e)return;const Y=()=>vc(e);return window.addEventListener("beforeunload",Y),()=>{Y(),window.removeEventListener("beforeunload",Y)}},[r,e]);function g(Y){Y.preventDefault();const X=e.trim();X&&T_(X).then(()=>i(!0))}function p(Y){u||d===0||s!=null&&s.ended||a(Y)}function m(){l===null||u||!s||(b_(e,s.id,l),h(!0))}const S=s&&((D=s.responses)==null?void 0:D[e])!==void 0,I=S?s.responses[e]:l,P=s?Object.keys(s.responses||{}).length:0,b=(s==null?void 0:s.ended)||d===0;function A(){return s?s.revealResults?!0:s.resultPolicy==="never"||s.resultPolicy==="manual"?!1:s.resultPolicy==="on_submit"?u||S:!1:!1}function q(){return!s||s.correctIndex==null?!1:s.revealCorrect?!0:s.correctPolicy==="never"||s.correctPolicy==="manual"?!1:s.correctPolicy==="with_results"?A():!1}const z=A(),pe=q();return r?!s&&!v?c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.waitCard,className:"fade-up",children:[c.jsx("div",{style:se.pulse}),c.jsxs("h2",{style:{fontFamily:"var(--font-display)",fontSize:"1.5rem"},children:["Hi, ",e,"! πŸ‘‹"]}),c.jsx("p",{style:{color:"var(--muted)"},children:"Waiting for the teacher to start a poll…"}),c.jsx("button",{style:se.backLink,onClick:()=>{vc(e),t("/")},children:"Leave session"})]})}):!s&&v?c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.waitCard,className:"fade-up",children:[c.jsx("span",{style:{fontSize:"2.5rem"},children:"βœ…"}),c.jsx("h2",{style:{fontFamily:"var(--font-display)"},children:"Poll closed!"}),c.jsx("p",{style:{color:"var(--muted)",textAlign:"center"},children:c.jsx("em",{children:v.question})}),v.correctIndex!=null&&v.revealCorrect&&c.jsxs("p",{style:{color:"var(--success)",fontWeight:600},children:["Correct answer: ",v.options[v.correctIndex]]}),c.jsx("p",{style:{color:"var(--muted)",fontSize:"0.85rem"},children:"Waiting for next poll…"})]})}):c.jsxs("div",{style:se.pollPage,children:[c.jsxs("header",{style:se.pollHeader,children:[c.jsxs("span",{style:{fontFamily:"var(--font-display)",fontWeight:700},children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsxs("span",{style:{color:"var(--muted)",fontSize:"0.9rem"},children:["Signed in as ",c.jsx("strong",{children:e})]})]}),c.jsxs("div",{style:se.pollContent,className:"fade-up",children:[!s.ended&&c.jsxs(c.Fragment,{children:[c.jsx("div",{style:se.timerBar,children:c.jsx("div",{style:{...se.timerFill,width:`${d/s.duration*100}%`,background:d>s.duration*.4?"var(--accent2)":d>s.duration*.15?"#f59e0b":"var(--accent)"}})}),c.jsxs("div",{style:se.timerLabel,children:[d,"s remaining Β· ",P," responded"]})]}),s.ended&&c.jsx("div",{style:se.stoppedBanner,children:"⏰ Time's up β€” waiting for teacher"}),c.jsx("h2",{style:se.questionText,children:s.question}),c.jsx("div",{style:se.optionGrid,children:s.options.map((Y,X)=>{const et=I===X,Ee=s.correctIndex===X,Be=Object.values(s.responses||{}).filter(U=>U===X).length,R=P>0?Math.round(Be/P*100):0;return c.jsxs("button",{style:{...se.optionBtn,...et?se.optionSelected:{},...pe&&Ee?se.optionCorrect:{},...b||S?{cursor:"default"}:{}},onClick:()=>p(X),disabled:b||S,children:[c.jsx("span",{style:se.optionLetter,children:String.fromCharCode(65+X)}),c.jsx("span",{style:{flex:1,textAlign:"left"},children:Y}),z&&c.jsxs("span",{style:se.optionPct,children:[R,"%"]}),z&&c.jsx("div",{style:{...se.optionBar,width:`${R}%`,background:pe&&Ee?"rgba(22,163,74,0.15)":"rgba(37,99,235,0.1)"}})]},X)})}),!S&&!u&&!b&&c.jsx("button",{className:"btn btn-primary",style:{width:"100%",justifyContent:"center",padding:"0.85rem",fontSize:"1rem",marginTop:"0.5rem"},onClick:m,disabled:l===null,children:"Submit Answer"}),(u||S)&&!b&&c.jsx("div",{style:se.submittedBadge,children:"βœ“ Answer submitted"}),b&&!S&&!u&&c.jsx("div",{style:{...se.submittedBadge,background:"#fef9c3",color:"#854d0e",borderColor:"#fef08a"},children:"⏰ Time's up β€” no answer recorded"}),b&&(S||u)&&c.jsx("div",{style:se.submittedBadge,children:"βœ“ Answer submitted β€” waiting for teacher"})]})]}):c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.joinCard,className:"fade-up",children:[c.jsxs("div",{style:se.joinLogo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsx("h1",{style:{fontSize:"1.8rem",marginBottom:"0.25rem"},children:"Join Session"}),c.jsx("p",{style:{color:"var(--muted)",marginBottom:"1.5rem"},children:"Enter your name to start answering polls"}),c.jsxs("form",{onSubmit:g,style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[c.jsx("input",{className:"input",placeholder:"Your first name",value:e,onChange:Y=>n(Y.target.value),autoFocus:!0,style:{fontSize:"1.1rem",textAlign:"center"},required:!0}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{justifyContent:"center",padding:"0.75rem"},children:"Join β†’"})]}),c.jsx("button",{style:se.backLink,onClick:()=>t("/"),children:"← Back"})]})})}const se={center:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"var(--paper)"},joinCard:{background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"2.5rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},joinLogo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",marginBottom:"1.5rem",display:"block"},backLink:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",marginTop:"1rem",fontSize:"0.85rem",display:"block",textAlign:"center"},waitCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:"0.75rem",background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"3rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},pulse:{width:16,height:16,borderRadius:"50%",background:"var(--accent2)",boxShadow:"0 0 0 0 rgba(37,99,235,0.4)",animation:"pulse-ring 1.5s ease-out infinite"},pollPage:{minHeight:"100vh",background:"var(--paper)",display:"flex",flexDirection:"column"},pollHeader:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",display:"flex",justifyContent:"space-between",alignItems:"center",background:"white"},pollContent:{maxWidth:620,margin:"0 auto",padding:"2rem 1rem",width:"100%"},timerBar:{height:6,background:"var(--cream)",borderRadius:3,overflow:"hidden",marginBottom:"0.4rem"},timerFill:{height:"100%",borderRadius:3,transition:"width 0.5s linear, background 0.5s"},timerLabel:{color:"var(--muted)",fontSize:"0.82rem",marginBottom:"1.5rem"},stoppedBanner:{background:"#fef9c3",color:"#854d0e",border:"1px solid #fef08a",borderRadius:8,padding:"0.6rem 1rem",fontSize:"0.9rem",marginBottom:"1.5rem",textAlign:"center"},questionText:{fontFamily:"var(--font-display)",fontSize:"clamp(1.2rem, 3vw, 1.6rem)",lineHeight:1.25,marginBottom:"1.25rem"},optionGrid:{display:"flex",flexDirection:"column",gap:"0.6rem"},optionBtn:{position:"relative",overflow:"hidden",display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.9rem 1rem",borderRadius:10,border:"2px solid var(--border)",background:"white",cursor:"pointer",transition:"all 0.15s",textAlign:"left",fontFamily:"var(--font-body)",fontSize:"0.95rem"},optionSelected:{borderColor:"var(--accent2)",background:"#eff6ff"},optionCorrect:{borderColor:"var(--success)",background:"#f0fdf4"},optionLetter:{width:28,height:28,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.8rem",fontWeight:700,flexShrink:0},optionPct:{color:"var(--muted)",fontSize:"0.82rem",fontWeight:600,flexShrink:0,zIndex:1},optionBar:{position:"absolute",left:0,top:0,height:"100%",transition:"width 0.4s ease",zIndex:0,pointerEvents:"none"},submittedBadge:{marginTop:"1rem",padding:"0.75rem",borderRadius:8,background:"#f0fdf4",color:"var(--success)",textAlign:"center",fontWeight:500,fontSize:"0.9rem",border:"1px solid #bbf7d0"}};function U_(t,e={}){const{duration:n=60,resultPolicy:r="on_submit",correctPolicy:i="with_results"}=e,s=t.split(/^---$/m).map(l=>l.trim()).filter(Boolean),o=[];for(const l of s){const a=l.split(` -`);let u="",h=[],d=null,f=n,v=r,w=i,_=0;for(;_=a.length)){for(u=a[_].replace(/^Q:\s*/i,"").trim(),_++;_{const r=[];return n.duration!==e.duration&&r.push(`duration: ${n.duration}`),n.resultPolicy!==e.resultPolicy&&r.push(`results: ${n.resultPolicy}`),n.correctPolicy!==e.correctPolicy&&r.push(`correct: ${n.correctPolicy}`),r.push(`Q: ${n.question}`),r.push(""),n.options.forEach((i,s)=>{const o=n.correctIndex===s?"* ":" ";r.push(`${o}${String.fromCharCode(65+s)}. ${i}`)}),r.join(` -`)}).join(` ---- -`)}const _b=[{value:"on_submit",label:"After they submit"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}],wb=[{value:"with_results",label:"With results"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}];function Sb(){const{id:t}=HS(),e=Sr(),[n,r]=C.useState(null),[i,s]=C.useState([]),[o,l]=C.useState(0),[a,u]=C.useState("form"),[h,d]=C.useState(""),[f,v]=C.useState(!1),[w,_]=C.useState(""),[E,g]=C.useState(!1),[p,m]=C.useState(!1),[S,I]=C.useState("");C.useEffect(()=>(localStorage.getItem("role")!=="teacher"&&e("/"),D_(t,y=>{y&&(r(y),s(y.polls||[]),I(y.name||""))})),[t]),C.useEffect(()=>{a==="text"&&n&&(d(yb(i,n.defaults||{})),v(!1),_(""))},[a]);function P(y){const x=(n==null?void 0:n.defaults)||{};return{...y,duration:y.duration??x.duration??60,resultPolicy:y.resultPolicy??x.resultPolicy??"on_submit",correctPolicy:y.correctPolicy??x.correctPolicy??"with_results"}}function b(y,x){s(i.map((T,O)=>O===o?{...T,[y]:x}:T))}function A(y,x){const T=P(i[o]).options.map((O,K)=>K===y?x:O);b("options",T)}function q(){const y=[...i[o].options||[],""];y.length<=6&&b("options",y)}function z(y){const x=i[o],T=x.options.filter((K,tt)=>tt!==y);if(T.length<2)return;let O=x.correctIndex;O===y?O=null:O>y&&(O=O-1),s(i.map((K,tt)=>tt===o?{...K,options:T,correctIndex:O}:K))}function pe(){const y=[...i,{question:"",options:["",""],correctIndex:null}];s(y),l(y.length-1)}function D(y){if(i.length<=1)return;const x=i.filter((T,O)=>O!==y);s(x),l(Math.min(y,x.length-1))}function Y(y,x){const T=y+x;if(T<0||T>=i.length)return;const O=[...i];[O[y],O[T]]=[O[T],O[y]],s(O),l(T)}function X(){_("");try{const y=U_(h,n.defaults||{});if(y.length===0){_("No polls found. Check your formatting.");return}s(y),v(!1),u("form"),l(0)}catch(y){_(y.message)}}async function et(){await Lo(t,{polls:i}),g(!0),setTimeout(()=>g(!1),2e3)}async function Ee(){await Lo(t,{name:S.trim()}),m(!1)}async function Be(){if(!i||i.length===0){alert("No polls in this set.");return}await Lo(t,{polls:i});const y=n.defaults||{},x=i[0];await L_(n.id,n.name,i.length),await Pl({question:x.question,options:x.options,correctIndex:x.correctIndex??null,duration:x.duration??y.duration??60,resultPolicy:x.resultPolicy??y.resultPolicy??"on_submit",correctPolicy:x.correctPolicy??y.correctPolicy??"with_results"}),e("/teacher")}if(!n)return c.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"var(--muted)"},children:"Loading…"});const R=i[o]?P(i[o]):null,U=n.defaults||{};return c.jsxs("div",{style:Z.page,children:[c.jsxs("header",{style:Z.header,children:[c.jsx("button",{style:Z.back,onClick:()=>e("/pollsets"),children:"← Poll Sets"}),c.jsx("div",{style:Z.titleArea,children:p?c.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[c.jsx("input",{className:"input",value:S,onChange:y=>I(y.target.value),style:{fontSize:"1rem",padding:"0.4rem 0.6rem"},autoFocus:!0,onKeyDown:y=>{y.key==="Enter"&&Ee(),y.key==="Escape"&&m(!1)}}),c.jsx("button",{className:"btn btn-primary",style:{padding:"0.4rem 0.8rem",fontSize:"0.85rem"},onClick:Ee,children:"Save"}),c.jsx("button",{className:"btn btn-secondary",style:{padding:"0.4rem 0.8rem",fontSize:"0.85rem"},onClick:()=>m(!1),children:"Cancel"})]}):c.jsxs("span",{style:Z.title,onClick:()=>m(!0),title:"Click to rename",children:[n.name," ✎"]})}),c.jsxs("div",{style:Z.viewToggle,children:[c.jsx("button",{style:{...Z.toggleBtn,...a==="form"?Z.toggleActive:{}},onClick:()=>u("form"),children:"Form view"}),c.jsx("button",{style:{...Z.toggleBtn,...a==="text"?Z.toggleActive:{}},onClick:()=>u("text"),children:"Text view"})]}),c.jsx("button",{className:"btn btn-secondary",onClick:et,style:{background:E?"#dcfce7":void 0,borderColor:E?"var(--success)":void 0,color:E?"var(--success)":void 0},children:E?"βœ“ Saved":"Save Changes"}),c.jsx("button",{className:"btn btn-primary",onClick:Be,children:"Launch β†’"})]}),c.jsxs("div",{style:Z.body,children:[a==="form"&&c.jsxs(c.Fragment,{children:[c.jsxs("aside",{style:Z.pollList,children:[c.jsxs("div",{style:Z.pollListHeader,children:[c.jsxs("span",{style:{fontSize:"0.8rem",color:"var(--muted)",fontWeight:600},children:[i.length," POLL",i.length!==1?"S":""]}),c.jsx("button",{className:"btn btn-ghost",style:{fontSize:"0.78rem",padding:"0.3rem 0.6rem"},onClick:pe,children:"+ Add"})]}),i.map((y,x)=>c.jsxs("div",{style:{...Z.pollItem,...o===x?Z.pollItemActive:{}},onClick:()=>l(x),children:[c.jsx("span",{style:Z.pollItemNum,children:x+1}),c.jsx("span",{style:Z.pollItemQ,children:y.question||c.jsx("em",{style:{color:"var(--muted)"},children:"Untitled"})}),c.jsxs("div",{style:Z.pollItemActions,children:[c.jsx("button",{style:Z.microBtn,onClick:T=>{T.stopPropagation(),Y(x,-1)},disabled:x===0,children:"↑"}),c.jsx("button",{style:Z.microBtn,onClick:T=>{T.stopPropagation(),Y(x,1)},disabled:x===i.length-1,children:"↓"}),c.jsx("button",{style:Z.microBtn,onClick:T=>{T.stopPropagation(),D(x)},disabled:i.length<=1,children:"βœ•"})]})]},x))]}),c.jsx("main",{style:Z.editor,children:R&&c.jsxs("div",{style:Z.editorInner,className:"fade-up",children:[c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Question"}),c.jsx("textarea",{className:"input",rows:3,placeholder:"Enter your question…",value:i[o].question,onChange:y=>b("question",y.target.value),style:{resize:"vertical",width:"100%"}})]}),c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Answer Options"}),c.jsx("p",{style:Z.hint,children:"Click a letter circle to mark the correct answer (optional)"}),c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:R.options.map((y,x)=>c.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[c.jsx("button",{type:"button",style:{...Z.correctBtn,...i[o].correctIndex===x?Z.correctBtnActive:{}},onClick:()=>b("correctIndex",i[o].correctIndex===x?null:x),children:i[o].correctIndex===x?"βœ“":String.fromCharCode(65+x)}),c.jsx("input",{className:"input",style:{flex:1},placeholder:`Option ${String.fromCharCode(65+x)}`,value:y,onChange:T=>A(x,T.target.value)}),c.jsx("button",{style:Z.removeBtn,onClick:()=>z(x),disabled:R.options.length<=2,children:"βœ•"})]},x))}),R.options.length<6&&c.jsx("button",{className:"btn btn-ghost",style:{marginTop:"0.5rem",fontSize:"0.85rem"},onClick:q,children:"+ Add option"})]}),c.jsxs("div",{style:Z.overridesBox,children:[c.jsxs("label",{className:"label",children:["Per-poll overrides",c.jsx("span",{style:{color:"var(--muted)",textTransform:"none",letterSpacing:0,marginLeft:"0.5rem",fontWeight:400,fontSize:"0.78rem"},children:"(leave blank to use set defaults)"})]}),c.jsxs("div",{style:Z.overridesRow,children:[c.jsxs("div",{children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Duration (s)"}),c.jsx("input",{className:"input",type:"number",min:10,max:300,placeholder:`default: ${U.duration??60}`,value:i[o].duration??"",onChange:y=>b("duration",y.target.value===""?null:Number(y.target.value)),style:{width:100}})]}),c.jsxs("div",{children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Show results"}),c.jsxs("select",{className:"input",value:i[o].resultPolicy??"",onChange:y=>b("resultPolicy",y.target.value||null),children:[c.jsxs("option",{value:"",children:["Set default (",U.resultPolicy??"on_submit",")"]}),_b.map(y=>c.jsx("option",{value:y.value,children:y.label},y.value))]})]}),c.jsxs("div",{children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Reveal answer"}),c.jsxs("select",{className:"input",value:i[o].correctPolicy??"",onChange:y=>b("correctPolicy",y.target.value||null),children:[c.jsxs("option",{value:"",children:["Set default (",U.correctPolicy??"with_results",")"]}),wb.map(y=>c.jsx("option",{value:y.value,children:y.label},y.value))]})]})]})]})]})})]}),a==="text"&&c.jsxs("div",{style:Z.textView,children:[c.jsxs("p",{style:Z.textHint,children:["Edit all polls as plain text. Use ",c.jsx("code",{children:"---"})," to separate polls. Per-poll overrides: ",c.jsx("code",{children:"duration: 90"}),", ",c.jsx("code",{children:"results: manual"}),", ",c.jsx("code",{children:"correct: never"}),". Click ",c.jsx("strong",{children:"Apply Changes"})," to update the form view, then ",c.jsx("strong",{children:"Save Changes"})," to persist."]}),c.jsx("textarea",{className:"input",value:h,onChange:y=>{d(y.target.value),v(!0),_("")},style:{fontFamily:"monospace",fontSize:"0.88rem",minHeight:"60vh",resize:"vertical",width:"100%"}}),w&&c.jsx("p",{style:Z.err,children:w}),c.jsxs("div",{style:{display:"flex",gap:"0.75rem",marginTop:"0.75rem"},children:[c.jsx("button",{className:"btn btn-primary",onClick:X,disabled:!f,children:"Apply Changes β†’"}),c.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("form"),_("")},children:"Cancel"})]})]})]})]})}const Z={page:{minHeight:"100vh",background:"var(--paper)",display:"flex",flexDirection:"column"},header:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",background:"white",display:"flex",alignItems:"center",gap:"0.75rem",flexWrap:"wrap"},back:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"0.9rem"},titleArea:{flex:1},title:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.15rem",cursor:"pointer",borderBottom:"1px dashed var(--border)"},viewToggle:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:8,padding:"0.25rem"},toggleBtn:{background:"none",border:"none",padding:"0.35rem 0.85rem",borderRadius:6,cursor:"pointer",fontSize:"0.85rem",color:"var(--muted)"},toggleActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},body:{display:"flex",flex:1,overflow:"hidden"},pollList:{width:220,borderRight:"1px solid var(--border)",background:"white",display:"flex",flexDirection:"column",overflowY:"auto"},pollListHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",borderBottom:"1px solid var(--border)"},pollItem:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.75rem 1rem",cursor:"pointer",borderBottom:"1px solid var(--cream)",transition:"background 0.1s"},pollItemActive:{background:"#eff6ff",borderLeft:"3px solid var(--accent2)"},pollItemNum:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"0.8rem",color:"var(--muted)",flexShrink:0,marginTop:"0.1rem"},pollItemQ:{fontSize:"0.82rem",flex:1,lineHeight:1.4,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},pollItemActions:{display:"flex",flexDirection:"column",gap:"0.15rem",flexShrink:0},microBtn:{background:"none",border:"none",cursor:"pointer",fontSize:"0.7rem",color:"var(--muted)",padding:"0.1rem 0.2rem",lineHeight:1},editor:{flex:1,overflowY:"auto",padding:"1.5rem"},editorInner:{maxWidth:"100%",display:"flex",flexDirection:"column",gap:"1.25rem"},hint:{fontSize:"0.82rem",color:"var(--muted)",marginBottom:"0.5rem"},overridesBox:{background:"var(--cream)",borderRadius:10,padding:"1rem",display:"flex",flexDirection:"column",gap:"0.75rem"},overridesRow:{display:"flex",gap:"1rem",flexWrap:"wrap",alignItems:"flex-end"},correctBtn:{width:32,height:32,borderRadius:"50%",border:"2px solid var(--border)",background:"var(--cream)",cursor:"pointer",fontWeight:700,fontSize:"0.8rem",flexShrink:0,transition:"all 0.15s"},correctBtnActive:{background:"var(--success)",color:"white",borderColor:"var(--success)"},removeBtn:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",fontSize:"0.9rem",padding:"0.25rem",borderRadius:4},textView:{flex:1,padding:"1.5rem",display:"flex",flexDirection:"column",gap:"0.75rem"},textHint:{fontSize:"0.85rem",color:"var(--muted)",lineHeight:1.6},err:{color:"var(--accent)",fontSize:"0.85rem"}},$p={duration:60,resultPolicy:"on_submit",correctPolicy:"with_results"},Vp=[{value:"on_submit",label:"After they submit"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}],Hp=[{value:"with_results",label:"With results"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}];function Cb(){const t=Sr(),[e,n]=C.useState([]),[r,i]=C.useState("list"),[s,o]=C.useState(null),[l,a]=C.useState(!1),[u,h]=C.useState(""),[d,f]=C.useState(""),[v,w]=C.useState($p),[_,E]=C.useState("text"),[g,p]=C.useState(""),[m,S]=C.useState(null),[I,P]=C.useState("");C.useEffect(()=>(localStorage.getItem("role")!=="teacher"&&t("/"),A_(n)),[]);function b(){f(""),w($p),E("text"),p(""),S(null),P(""),h("")}function A(){P("");try{const D=U_(g,v);if(D.length===0){P("No polls found. Check your formatting.");return}S(D)}catch(D){P(D.message)}}async function q(){if(h(""),!d.trim()){h("Please enter a set name.");return}if(!m||m.length===0){h("Preview your polls first.");return}a(!0);try{const D=await _c({name:d.trim(),defaults:v,polls:m});b(),i("list"),t(`/pollsets/${D}`)}catch(D){h("Error saving: "+D.message)}finally{a(!1)}}async function z(){if(h(""),!d.trim()){h("Please enter a set name.");return}a(!0);try{const D=await _c({name:d.trim(),defaults:v,polls:[]});b(),i("list"),t(`/pollsets/${D}`)}catch(D){h("Error saving: "+D.message)}finally{a(!1)}}function pe(D){O_(D),o(null)}return c.jsxs("div",{style:Q.page,children:[c.jsxs("header",{style:Q.header,children:[c.jsx("button",{style:Q.back,onClick:()=>t("/teacher"),children:"← Dashboard"}),c.jsx("span",{style:Q.title,children:"Poll Sets"}),r==="list"&&c.jsx("button",{className:"btn btn-primary",onClick:()=>i("create"),children:"+ New Set"}),r==="create"&&c.jsx("button",{className:"btn btn-secondary",onClick:()=>{i("list"),b()},children:"Cancel"})]}),c.jsxs("main",{style:Q.main,children:[r==="list"&&c.jsxs("div",{className:"fade-up",children:[e.length===0&&c.jsxs("div",{style:Q.empty,children:[c.jsx("span",{style:{fontSize:"2.5rem"},children:"πŸ“š"}),c.jsx("p",{children:"No poll sets yet."}),c.jsx("button",{className:"btn btn-primary",onClick:()=>i("create"),children:"Create your first set β†’"})]}),e.map(D=>{const Y=s===D.id;return c.jsxs("div",{style:Q.setCard,children:[c.jsxs("button",{style:Q.setCardBtn,onClick:()=>t(`/pollsets/${D.id}`),children:[c.jsxs("div",{children:[c.jsx("div",{style:Q.setName,children:D.name}),c.jsxs("div",{style:Q.setMeta,children:[(D.polls||[]).length," poll",(D.polls||[]).length!==1?"s":""," Β· Created ",new Date(D.createdAt).toLocaleDateString()]})]}),c.jsx("span",{style:{color:"var(--muted)"},children:"β†’"})]}),c.jsx("div",{style:Q.setActions,children:Y?c.jsxs("div",{style:Q.confirmRow,children:[c.jsx("span",{style:Q.confirmText,children:"Delete?"}),c.jsx("button",{className:"btn btn-primary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem",background:"#dc2626"},onClick:()=>pe(D.id),children:"Yes"}),c.jsx("button",{className:"btn btn-secondary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem"},onClick:()=>o(null),children:"Cancel"})]}):c.jsx("button",{style:Q.deleteBtn,onClick:()=>o(D.id),children:"πŸ—‘"})})]},D.id)})]}),r==="create"&&c.jsxs("div",{className:"fade-up",style:Q.createForm,children:[c.jsx("h2",{style:Q.sectionTitle,children:"New Poll Set"}),c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Set Name"}),c.jsx("input",{className:"input",placeholder:"e.g. Chapter 5 Review",value:d,onChange:D=>f(D.target.value),autoFocus:!0})]}),c.jsxs("div",{style:Q.defaultsBox,children:[c.jsx("label",{className:"label",children:"Default settings for all polls in this set"}),c.jsxs("div",{style:Q.defaultsRow,children:[c.jsxs("div",{children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Duration (seconds)"}),c.jsx("input",{className:"input",type:"number",min:10,max:300,value:v.duration,onChange:D=>w({...v,duration:Number(D.target.value)}),style:{width:100}})]}),c.jsxs("div",{style:{flex:1},children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Show results to students"}),c.jsx("select",{className:"input",value:v.resultPolicy,onChange:D=>w({...v,resultPolicy:D.target.value}),children:Vp.map(D=>c.jsx("option",{value:D.value,children:D.label},D.value))})]}),c.jsxs("div",{style:{flex:1},children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Reveal correct answer"}),c.jsx("select",{className:"input",value:v.correctPolicy,onChange:D=>w({...v,correctPolicy:D.target.value}),children:Hp.map(D=>c.jsx("option",{value:D.value,children:D.label},D.value))})]})]})]}),c.jsxs("div",{children:[c.jsxs("div",{style:Q.modeTabs,children:[c.jsx("button",{style:{...Q.modeTab,..._==="text"?Q.modeTabActive:{}},onClick:()=>E("text"),children:"Paste text"}),c.jsx("button",{style:{...Q.modeTab,..._==="manual"?Q.modeTabActive:{}},onClick:()=>E("manual"),children:"Build manually"})]}),_==="text"&&c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[c.jsx("textarea",{className:"input",rows:14,placeholder:`Q: What is photosynthesis? - -* A. Converts sunlight into energy - B. Breaks down glucose - C. Absorbs water through roots - D. Releases CO2 ---- -Q: Which organelle contains chlorophyll? -duration: 90 - - A. Mitochondria -* B. Chloroplast - C. Nucleus - D. Vacuole`,value:g,onChange:D=>{p(D.target.value),S(null),P("")},style:{fontFamily:"monospace",fontSize:"0.85rem",resize:"vertical",minHeight:"320px",width:"100%"}}),c.jsxs("div",{style:{display:"flex",gap:"0.75rem",alignItems:"center"},children:[c.jsx("button",{className:"btn btn-secondary",onClick:A,children:"Preview β†’"}),I&&c.jsx("span",{style:Q.err,children:I})]})]}),_==="manual"&&c.jsxs("div",{style:Q.manualBox,children:[c.jsx("p",{children:"The set will be created empty. You can add and edit polls one by one in the set detail view."}),u&&c.jsx("p",{style:Q.err,children:u}),c.jsx("button",{className:"btn btn-primary",style:{marginTop:"0.5rem"},onClick:z,disabled:l,children:l?"Creating…":"Create empty set β†’"})]})]}),_==="text"&&m&&c.jsxs("div",{style:Q.previewBox,children:[c.jsxs("label",{className:"label",children:["Preview β€” ",m.length," poll",m.length!==1?"s":""," found"]}),m.map((D,Y)=>{var X,et;return c.jsxs("div",{style:Q.previewPoll,children:[c.jsxs("div",{style:Q.previewQ,children:[Y+1,". ",D.question]}),c.jsx("div",{style:Q.previewOptions,children:D.options.map((Ee,Be)=>c.jsxs("div",{style:{...Q.previewOpt,...D.correctIndex===Be?Q.previewOptCorrect:{}},children:[D.correctIndex===Be?"βœ“":String.fromCharCode(65+Be),". ",Ee]},Be))}),c.jsxs("div",{style:Q.previewMeta,children:[D.duration,"s Β· Results: ",(X=Vp.find(Ee=>Ee.value===D.resultPolicy))==null?void 0:X.label," Β· Answer: ",(et=Hp.find(Ee=>Ee.value===D.correctPolicy))==null?void 0:et.label]})]},Y)}),u&&c.jsx("p",{style:Q.err,children:u}),c.jsx("button",{className:"btn btn-primary",onClick:q,disabled:l,children:l?"Saving…":"Save Set β†’"})]})]})]})]})}const Q={page:{minHeight:"100vh",background:"var(--paper)"},header:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",background:"white",display:"flex",alignItems:"center",gap:"1rem"},back:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"0.9rem"},title:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.2rem",flex:1},main:{maxWidth:960,margin:"0 auto",padding:"1.5rem 1rem"},empty:{textAlign:"center",padding:"4rem 2rem",color:"var(--muted)",display:"flex",flexDirection:"column",alignItems:"center",gap:"1rem"},setCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",marginBottom:"0.75rem",display:"flex",alignItems:"center",overflow:"hidden"},setCardBtn:{display:"flex",alignItems:"center",justifyContent:"space-between",flex:1,padding:"1rem",background:"none",border:"none",cursor:"pointer",textAlign:"left"},setName:{fontFamily:"var(--font-display)",fontWeight:600,fontSize:"1rem"},setMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},setActions:{padding:"0 0.75rem",display:"flex",alignItems:"center",gap:"0.4rem"},deleteBtn:{background:"none",border:"none",cursor:"pointer",fontSize:"1.1rem",padding:"0.25rem 0.4rem",borderRadius:6,opacity:.5},confirmRow:{display:"flex",alignItems:"center",gap:"0.4rem"},confirmText:{fontSize:"0.82rem",color:"var(--muted)",whiteSpace:"nowrap"},createForm:{display:"flex",flexDirection:"column",gap:"1.25rem"},sectionTitle:{fontSize:"1.4rem"},defaultsBox:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1rem",display:"flex",flexDirection:"column",gap:"0.75rem"},defaultsRow:{display:"flex",gap:"0.75rem",flexWrap:"wrap",alignItems:"flex-end"},modeTabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:8,padding:"0.25rem",marginBottom:"0.75rem",width:"fit-content"},modeTab:{background:"none",border:"none",padding:"0.35rem 0.85rem",borderRadius:6,cursor:"pointer",fontSize:"0.9rem",color:"var(--muted)"},modeTabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},manualBox:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1.25rem",color:"var(--muted)",fontSize:"0.9rem",display:"flex",flexDirection:"column",gap:"0.5rem"},previewBox:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1.25rem",display:"flex",flexDirection:"column",gap:"0.75rem"},previewPoll:{borderBottom:"1px solid var(--border)",paddingBottom:"0.75rem",display:"flex",flexDirection:"column",gap:"0.4rem"},previewQ:{fontWeight:600,fontSize:"0.95rem"},previewOptions:{display:"flex",flexDirection:"column",gap:"0.2rem",paddingLeft:"0.75rem"},previewOpt:{fontSize:"0.88rem",color:"var(--muted)"},previewOptCorrect:{color:"var(--success)",fontWeight:600},previewMeta:{fontSize:"0.75rem",color:"var(--muted)",marginTop:"0.25rem"},err:{color:"var(--accent)",fontSize:"0.85rem"}};function Eb(t,e=40){return t.length>e?t.slice(0,e)+"...":t}function xb(t){if(t==null)return"";const e=String(t);return e.includes(",")||e.includes('"')||e.includes(` -`)?`"${e.replace(/"/g,'""')}"`:e}function nt(t){return t.map(xb).join(",")}function Ib(t){const e=t.responses||{},n=t.correctIndex!=null,r=[];r.push(nt(["Question",t.question])),r.push(nt(["Date",new Date(t.startedAt).toLocaleString()])),n&&r.push(nt(["Correct Answer",`${String.fromCharCode(65+t.correctIndex)}. ${t.options[t.correctIndex]}`])),r.push("");const i=["Student","Response"];n&&i.push("Correct (1=yes 0=no)"),r.push(nt(i));const s=Object.keys(e).sort();return s.length===0?r.push(nt(["(no responses)","",""])):s.forEach(o=>{const l=e[o],a=l!=null?`${String.fromCharCode(65+l)}. ${t.options[l]}`:"(no answer)",u=[o,a];n&&u.push(l===t.correctIndex?"1":"0"),r.push(nt(u))}),r.join(` -`)}function kb(t,e){if(!e||e.length===0)return"";const n=new Set;e.forEach(o=>{Object.keys(o.responses||{}).forEach(l=>n.add(l))});const r=[...n].sort(),i=[];i.push(nt(["Set",t])),i.push(nt(["Date",new Date(e[0].startedAt).toLocaleString()])),i.push(nt(["Polls",e.length])),i.push("");const s=["Student"];return e.forEach((o,l)=>{const a=`Q${l+1}: ${Eb(o.question)}`;s.push(a),o.correctIndex!=null&&s.push(`Q${l+1} Correct (1=yes 0=no)`)}),i.push(nt(s)),r.forEach(o=>{const l=[o];e.forEach(a=>{const h=(a.responses||{})[o],d=h!=null?`${String.fromCharCode(65+h)}. ${a.options[h]}`:"(no answer)";l.push(d),a.correctIndex!=null&&l.push(h===a.correctIndex?"1":"0")}),i.push(nt(l))}),i.push(""),i.push(nt(["Summary"])),e.forEach((o,l)=>{const a=o.responses||{},u=Object.keys(a).length;i.push(""),i.push(nt([`Q${l+1}`,o.question])),o.options.forEach((h,d)=>{const f=Object.values(a).filter(_=>_===d).length,v=u>0?Math.round(f/u*100):0,w=o.correctIndex===d;i.push(nt([`${String.fromCharCode(65+d)}. ${h}`,`${f} responses`,`${v}%`,w?"correct answer":""]))})}),i.join(` -`)}function Gp(t,e){const n=new Blob([e],{type:"text/csv;charset=utf-8;"}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=t,i.click(),URL.revokeObjectURL(r)}const Tb="changeme";function bb(){const t=Sr(),[e,n]=C.useState(!1),[r,i]=C.useState(""),[s,o]=C.useState(""),[l,a]=C.useState([]),[u,h]=C.useState({}),[d,f]=C.useState("polls"),[v,w]=C.useState(new Set),[_,E]=C.useState(new Set),[g,p]=C.useState(null),[m,S]=C.useState(null),[I,P]=C.useState({}),[b,A]=C.useState({});C.useEffect(()=>{(localStorage.getItem("historyAuth")==="true"||localStorage.getItem("role")==="teacher")&&n(!0)},[]),C.useEffect(()=>{if(!e)return;const y=R_(a),x=xr(ne(re,"sessionStudents"),T=>{const O=T.val()||{},K={};Object.values(O).forEach(Ge=>{const L=Ge.date||"unknown";K[L]||(K[L]=new Set),K[L].add(Ge.name)});const tt={};Object.entries(K).forEach(([Ge,L])=>{tt[Ge]=[...L].sort()}),h(tt)});return()=>{y(),x()}},[e]);function q(y){y.preventDefault(),r===Tb?(localStorage.setItem("historyAuth","true"),n(!0)):(o("Incorrect password."),i(""))}function z(y){vr(ne(re,`pollHistory/${y}`)),p(null),w(x=>{const T=new Set(x);return T.delete(y),T})}function pe(y,x){x.forEach(T=>vr(ne(re,`pollHistory/${T.id}`))),S(null),E(T=>{const O=new Set(T);return O.delete(y),O})}function D(y){w(x=>{const T=new Set(x);return T.has(y)?T.delete(y):T.add(y),T})}function Y(y){E(x=>{const T=new Set(x);return T.has(y)?T.delete(y):T.add(y),T})}function X(y,x){P(T=>({...T,[y]:x}))}function et(y){A(x=>({...x,[y]:!0})),setTimeout(()=>A(x=>({...x,[y]:!1})),2e3)}function Ee(y){const x=Ib(y),T=new Date(y.startedAt).toLocaleDateString().replace(/\//g,"-");Gp(`poll_${T}_${y.id}.csv`,x)}function Be(y,x){const T=kb(y,x),O=new Date(x[0].startedAt).toLocaleDateString().replace(/\//g,"-"),K=y.replace(/[^a-z0-9]/gi,"_").toLowerCase();Gp(`session_${K}_${O}.csv`,T)}function R(y){const x={},T=[];return y.forEach(O=>{if(O.setId){const K=O.sessionKey||`${O.setId}_${new Date(O.startedAt).toLocaleDateString()}`;x[K]||(x[K]={key:K,setId:O.setId,setName:O.setName,date:new Date(O.startedAt).toLocaleDateString(),startedAt:O.startedAt,polls:[]}),x[K].polls.push(O)}else T.push(O)}),Object.values(x).forEach(O=>{O.polls.sort((K,tt)=>(K.setPosition??0)-(tt.setPosition??0))}),[...Object.values(x).map(O=>({type:"set",...O})),...T.map(O=>({type:"poll",...O}))].sort((O,K)=>(K.startedAt||0)-(O.startedAt||0))}if(!e)return c.jsx("div",{style:F.center,children:c.jsxs("div",{style:F.loginCard,className:"fade-up",children:[c.jsxs("div",{style:F.loginLogo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsx("h2",{style:{fontSize:"1.4rem",marginBottom:"0.25rem"},children:"Poll History"}),c.jsx("p",{style:{color:"var(--muted)",marginBottom:"1.5rem",fontSize:"0.9rem"},children:"Enter the teacher password to view history and attendance."}),c.jsxs("form",{onSubmit:q,style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[c.jsx("input",{className:"input",type:"password",placeholder:"Teacher password",value:r,onChange:y=>{i(y.target.value),o("")},autoFocus:!0,style:{textAlign:"center"}}),s&&c.jsx("span",{style:F.err,children:s}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{justifyContent:"center",padding:"0.75rem"},children:"View History β†’"})]}),c.jsx("button",{style:F.backLink,onClick:()=>t("/"),children:"← Back"})]})});const U=R(l);return c.jsxs("div",{style:F.page,children:[c.jsxs("header",{style:F.header,children:[c.jsx("button",{style:F.back,onClick:()=>t("/"),children:"← Back"}),c.jsx("span",{style:F.title,children:"Poll History"}),c.jsxs("div",{style:F.tabs,children:[c.jsx("button",{style:{...F.tab,...d==="polls"?F.tabActive:{}},onClick:()=>f("polls"),children:"Polls"}),c.jsx("button",{style:{...F.tab,...d==="attendance"?F.tabActive:{}},onClick:()=>f("attendance"),children:"Attendance"})]})]}),c.jsxs("main",{style:F.main,children:[d==="polls"&&c.jsxs("div",{className:"fade-up",children:[U.length===0&&c.jsx("div",{style:F.empty,children:"No polls yet. Run your first one in class!"}),U.map(y=>{if(y.type==="set"){const x=_.has(y.key),T=y.polls.reduce((O,K)=>O+Object.keys(K.responses||{}).length,0);return c.jsxs("div",{style:F.setGroup,children:[c.jsxs("div",{style:F.setGroupHeaderRow,children:[c.jsxs("button",{style:F.setGroupHeaderBtn,onClick:()=>Y(y.key),children:[c.jsx("span",{style:F.triangle,children:x?"β–Ό":"β–Ά"}),c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{style:F.setGroupName,children:["πŸ“š ",y.setName]}),c.jsxs("div",{style:F.setGroupMeta,children:[y.date," Β· ",y.polls.length," polls Β· ",T," total responses"]})]})]}),c.jsxs("div",{style:{display:"flex",gap:"0.4rem",alignItems:"center"},children:[c.jsx("button",{style:{...F.exportBtn,...b[y.key]?F.exportBtnSuccess:{}},onClick:()=>{Be(y.setName,y.polls),et(y.key)},children:b[y.key]?"βœ“ Downloading":"⬇ Session CSV"}),m!==y.key?c.jsx("button",{style:F.deleteBtn,onClick:()=>S(y.key),title:"Delete this session",children:"πŸ—‘"}):c.jsxs("div",{style:F.confirmRow,children:[c.jsxs("span",{style:F.confirmText,children:["Delete all ",y.polls.length," polls?"]}),c.jsx("button",{className:"btn btn-primary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem",background:"#dc2626"},onClick:()=>pe(y.key,y.polls),children:"Yes"}),c.jsx("button",{className:"btn btn-secondary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem"},onClick:()=>S(null),children:"Cancel"})]})]})]}),x&&c.jsx("div",{style:F.setGroupPolls,children:y.polls.map(O=>c.jsx(qp,{poll:O,expanded:v.has(O.id),viewMode:I[O.id]||"summary",confirmDelete:g,copyFeedback:b[O.id],onToggle:()=>D(O.id),onDelete:()=>z(O.id),onConfirmDelete:()=>p(O.id),onCancelDelete:()=>p(null),onSetView:K=>X(O.id,K),onDownload:()=>Ee(O),onDownloadFeedback:()=>et(O.id),positionLabel:`${(O.setPosition??0)+1}.`},O.id))})]},y.key)}return c.jsx(qp,{poll:y,expanded:v.has(y.id),viewMode:I[y.id]||"summary",confirmDelete:g,copyFeedback:b[y.id],onToggle:()=>D(y.id),onDelete:()=>z(y.id),onConfirmDelete:()=>p(y.id),onCancelDelete:()=>p(null),onSetView:x=>X(y.id,x),onDownload:()=>Ee(y),onDownloadFeedback:()=>et(y.id)},y.id)})]}),d==="attendance"&&c.jsxs("div",{className:"fade-up",children:[Object.keys(u).length===0&&c.jsx("div",{style:F.empty,children:"No attendance records yet."}),Object.entries(u).sort(([y],[x])=>x.localeCompare(y)).map(([y,x])=>c.jsxs("div",{style:F.pollCard,children:[c.jsx("div",{style:F.pollHeaderRow,children:c.jsxs("div",{style:{padding:"0.25rem 0"},children:[c.jsx("div",{style:F.pollQ,children:y}),c.jsxs("div",{style:F.pollMeta,children:[x.length," student",x.length!==1?"s":""]})]})}),c.jsx("div",{style:{padding:"0 1rem 1rem",display:"flex",flexWrap:"wrap",gap:"0.4rem"},children:x.map(T=>c.jsx("span",{style:F.chip,children:T},T))})]},y))]})]})]})}function qp({poll:t,expanded:e,viewMode:n,confirmDelete:r,copyFeedback:i,onToggle:s,onDelete:o,onConfirmDelete:l,onCancelDelete:a,onSetView:u,onDownload:h,onDownloadFeedback:d,positionLabel:f}){const v=t.responses||{},w=Object.keys(v).length,_=r===t.id,E=t.correctIndex!=null,g={};return t.options.forEach((p,m)=>{g[m]=[]}),Object.entries(v).forEach(([p,m])=>{g[m]!==void 0?g[m].push(p):g[m]=[p]}),c.jsxs("div",{style:F.pollCard,children:[c.jsxs("div",{style:F.pollHeaderRow,children:[c.jsxs("button",{style:F.pollHeaderBtn,onClick:s,children:[c.jsx("span",{style:F.triangle,children:e?"β–Ό":"β–Ά"}),c.jsxs("div",{children:[c.jsxs("div",{style:F.pollQ,children:[f&&c.jsxs("span",{style:F.posLabel,children:[f," "]}),t.question]}),c.jsxs("div",{style:F.pollMeta,children:[new Date(t.startedAt).toLocaleString()," Β· ",w," response",w!==1?"s":""]})]})]}),c.jsxs("div",{style:{display:"flex",gap:"0.4rem",alignItems:"center"},children:[!_&&c.jsx("button",{style:{...F.exportBtn,...i?F.exportBtnSuccess:{}},onClick:()=>{h(),d()},children:i?"βœ“ Downloading":"⬇ CSV"}),_?c.jsxs("div",{style:F.confirmRow,children:[c.jsx("span",{style:F.confirmText,children:"Delete?"}),c.jsx("button",{className:"btn btn-primary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem",background:"#dc2626"},onClick:o,children:"Yes"}),c.jsx("button",{className:"btn btn-secondary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem"},onClick:a,children:"Cancel"})]}):c.jsx("button",{style:F.deleteBtn,onClick:l,title:"Delete",children:"πŸ—‘"})]})]}),e&&c.jsxs("div",{style:F.pollDetails,children:[c.jsxs("div",{style:F.viewTabs,children:[c.jsx("button",{style:{...F.viewTab,...n==="summary"?F.viewTabActive:{}},onClick:()=>u("summary"),children:"Summary"}),c.jsx("button",{style:{...F.viewTab,...n==="students"?F.viewTabActive:{}},onClick:()=>u("students"),children:"By student"})]}),n==="summary"&&c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.6rem"},children:t.options.map((p,m)=>{const S=Object.values(v).filter(b=>b===m).length,I=w>0?Math.round(S/w*100):0,P=E&&t.correctIndex===m;return c.jsxs("div",{style:F.histOpt,children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:4},children:[c.jsxs("span",{style:{fontWeight:P?600:400,color:P?"var(--success)":"inherit"},children:[String.fromCharCode(65+m),". ",p," ",P&&"βœ“"]}),c.jsxs("span",{style:{color:"var(--muted)",fontSize:"0.85rem"},children:[S," (",I,"%)"]})]}),c.jsx("div",{style:F.barBg,children:c.jsx("div",{style:{...F.barFill,width:`${I}%`,background:P?"var(--success)":"var(--accent2)"}})})]},m)})}),n==="students"&&c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[t.options.map((p,m)=>{const S=g[m]||[],I=E&&t.correctIndex===m;return S.length===0?null:c.jsxs("div",{style:F.answerGroup,children:[c.jsxs("div",{style:{...F.answerGroupHeader,...I?F.answerGroupCorrect:{}},children:[c.jsxs("span",{style:{fontWeight:600},children:[String.fromCharCode(65+m),". ",p]}),I&&c.jsx("span",{style:F.correctTag,children:"βœ“ correct"}),c.jsxs("span",{style:F.answerCount,children:[S.length," student",S.length!==1?"s":""]})]}),c.jsx("div",{style:F.studentNames,children:S.sort().map(P=>c.jsx("span",{style:F.chip,children:P},P))})]},m)}),w===0&&c.jsx("div",{style:{color:"var(--muted)",fontSize:"0.9rem"},children:"No responses."})]})]})]})}const F={center:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"var(--paper)"},loginCard:{background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"2.5rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},loginLogo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",marginBottom:"1.5rem",display:"block"},err:{color:"var(--accent)",fontSize:"0.85rem"},backLink:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",marginTop:"1rem",fontSize:"0.85rem",display:"block",textAlign:"center"},page:{minHeight:"100vh",background:"var(--paper)"},header:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",background:"white",display:"flex",alignItems:"center",gap:"1rem",flexWrap:"wrap"},back:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"0.9rem"},title:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.2rem",flex:1},tabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:8,padding:"0.25rem"},tab:{background:"none",border:"none",padding:"0.35rem 0.85rem",borderRadius:6,cursor:"pointer",fontSize:"0.9rem",color:"var(--muted)",transition:"all 0.15s"},tabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},main:{maxWidth:760,margin:"0 auto",padding:"1.5rem 1rem"},empty:{textAlign:"center",color:"var(--muted)",padding:"3rem",fontSize:"0.95rem"},setGroup:{background:"white",borderRadius:12,border:"1.5px solid var(--accent2)",marginBottom:"0.75rem",overflow:"hidden"},setGroupHeaderRow:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.85rem 1rem",borderBottom:"1px solid var(--cream)"},setGroupHeaderBtn:{display:"flex",alignItems:"center",gap:"0.75rem",background:"none",border:"none",cursor:"pointer",textAlign:"left",flex:1},setGroupName:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"0.95rem"},setGroupMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},setGroupPolls:{padding:"0.5rem 0.75rem",display:"flex",flexDirection:"column",gap:"0.4rem"},triangle:{fontSize:"0.7rem",color:"var(--muted)",flexShrink:0},exportBtn:{background:"var(--cream)",border:"1px solid var(--border)",borderRadius:6,padding:"0.3rem 0.65rem",fontSize:"0.78rem",cursor:"pointer",color:"var(--ink)",whiteSpace:"nowrap",transition:"all 0.15s",flexShrink:0},exportBtnSuccess:{background:"#dcfce7",borderColor:"var(--success)",color:"var(--success)"},pollCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",marginBottom:"0.75rem",overflow:"hidden"},pollHeaderRow:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.75rem 1rem"},pollHeaderBtn:{display:"flex",alignItems:"center",gap:"0.6rem",background:"none",border:"none",cursor:"pointer",textAlign:"left",flex:1,padding:"0.25rem 0"},posLabel:{color:"var(--muted)",fontWeight:400},pollQ:{fontFamily:"var(--font-display)",fontWeight:600,fontSize:"0.95rem"},pollMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},deleteBtn:{background:"none",border:"none",cursor:"pointer",fontSize:"1.1rem",padding:"0.25rem 0.4rem",borderRadius:6,opacity:.5},confirmRow:{display:"flex",alignItems:"center",gap:"0.4rem"},confirmText:{fontSize:"0.82rem",color:"var(--muted)",whiteSpace:"nowrap"},pollDetails:{padding:"0.75rem 1rem 1rem",borderTop:"1px solid var(--border)"},viewTabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:6,padding:"0.2rem",marginBottom:"0.75rem",width:"fit-content"},viewTab:{background:"none",border:"none",padding:"0.25rem 0.65rem",borderRadius:4,cursor:"pointer",fontSize:"0.82rem",color:"var(--muted)"},viewTabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 2px rgba(0,0,0,0.08)"},histOpt:{marginBottom:"0.6rem"},barBg:{height:6,borderRadius:3,background:"var(--cream)",overflow:"hidden"},barFill:{height:"100%",borderRadius:3,transition:"width 0.3s"},answerGroup:{borderRadius:8,border:"1px solid var(--border)",overflow:"hidden"},answerGroupHeader:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",background:"var(--cream)",flexWrap:"wrap"},answerGroupCorrect:{background:"#dcfce7"},correctTag:{fontSize:"0.75rem",color:"var(--success)",fontWeight:600,background:"#bbf7d0",borderRadius:4,padding:"0.1rem 0.4rem"},answerCount:{marginLeft:"auto",fontSize:"0.78rem",color:"var(--muted)"},studentNames:{padding:"0.5rem 0.75rem",display:"flex",flexWrap:"wrap",gap:"0.35rem"},chip:{background:"var(--cream)",borderRadius:4,padding:"0.2rem 0.5rem",fontSize:"0.78rem",color:"var(--ink)"}};function Pb(){return c.jsx(dC,{basename:"/classroom-polling",children:c.jsxs(aC,{children:[c.jsx(fn,{path:"/",element:c.jsx(fC,{})}),c.jsx(fn,{path:"/instructor",element:c.jsx(mb,{})}),c.jsx(fn,{path:"/student",element:c.jsx(vb,{})}),c.jsx(fn,{path:"/pollsets/:id",element:c.jsx(Sb,{})}),c.jsx(fn,{path:"/pollsets",element:c.jsx(Cb,{})}),c.jsx(fn,{path:"/history",element:c.jsx(bb,{})}),c.jsx(fn,{path:"*",element:c.jsx(oC,{to:"/"})})]})})}Za.createRoot(document.getElementById("root")).render(c.jsx(im.StrictMode,{children:c.jsx(Pb,{})})); diff --git a/dist/index.html b/dist/index.html index 4c2d7ef..dc625f8 100644 --- a/dist/index.html +++ b/dist/index.html @@ -8,7 +8,7 @@ - + diff --git a/src/pages/PollHistory.jsx b/src/pages/PollHistory.jsx index a73e791..ec4c38a 100644 --- a/src/pages/PollHistory.jsx +++ b/src/pages/PollHistory.jsx @@ -15,7 +15,7 @@ import { db } from '../firebase'; import { ref, onValue, remove } from 'firebase/database'; import { pollToCsv, sessionToCsv, downloadCsv } from '../utils/csvExport'; -const HISTORY_PASSWORD = import.meta.env.VITE_TEACHER_PASSWORD || 'changeme'; +const HISTORY_PASSWORD = import.meta.env.VITE_INSTRUCTOR_PASSWORD || 'changeme'; export default function PollHistory() { const navigate = useNavigate(); @@ -33,7 +33,7 @@ export default function PollHistory() { const [copyFeedback, setCopyFeedback] = useState({}); // key -> true useEffect(() => { - if (localStorage.getItem("historyAuth") === 'true' || localStorage.getItem("role") === 'teacher') setAuth(true); + if (localStorage.getItem("historyAuth") === 'true' || localStorage.getItem("role") === 'instructor') setAuth(true); }, []); useEffect(() => { @@ -153,11 +153,11 @@ export default function PollHistory() {

Poll History

- Enter the teacher password to view history and attendance. + Enter the instructor password to view history and attendance.

- { setPw(e.target.value); setErr(''); }} autoFocus style={{textAlign:'center'}} /> {err && {err}} diff --git a/src/pages/PollSetDetail.jsx b/src/pages/PollSetDetail.jsx index 67b939b..1559f3e 100644 --- a/src/pages/PollSetDetail.jsx +++ b/src/pages/PollSetDetail.jsx @@ -39,7 +39,7 @@ export default function PollSetDetail() { const [nameValue, setNameValue] = useState(''); useEffect(() => { - if (localStorage.getItem('role') !== 'teacher') navigate('/'); + if (localStorage.getItem('role') !== 'instructor') navigate('/'); return watchPollSet(id, s => { if (!s) return; setPollSet(s); @@ -155,7 +155,7 @@ export default function PollSetDetail() { resultPolicy: first.resultPolicy ?? d.resultPolicy ?? 'on_submit', correctPolicy: first.correctPolicy ?? d.correctPolicy ?? 'with_results', }); - navigate('/teacher'); + navigate('/instructor'); } if (!pollSet) return ( diff --git a/src/pages/PollSets.jsx b/src/pages/PollSets.jsx index b17de83..925ec7a 100644 --- a/src/pages/PollSets.jsx +++ b/src/pages/PollSets.jsx @@ -49,7 +49,7 @@ export default function PollSets() { const [parseErr, setParseErr] = useState(''); useEffect(() => { - if (localStorage.getItem('role') !== 'teacher') navigate('/'); + if (localStorage.getItem('role') !== 'instructor') navigate('/'); return watchPollSets(setSets); }, []); @@ -113,7 +113,7 @@ export default function PollSets() { return (
- + Poll Sets {view === 'list' && ( - {!showTeacherLogin ? ( - ) : ( - + πŸ”‘ - Teacher Password + Instructor Password diff --git a/src/pages/StudentPage.jsx b/src/pages/StudentPage.jsx index a6a8e8d..3179b01 100644 --- a/src/pages/StudentPage.jsx +++ b/src/pages/StudentPage.jsx @@ -87,10 +87,10 @@ export default function StudentPage() { const responseCount = activePoll ? Object.keys(activePoll.responses || {}).length : 0; const pollStopped = activePoll?.ended || timeLeft === 0; - // Determine what to show based on teacher policy + manual overrides + // Determine what to show based on instructor policy + manual overrides function shouldShowResults() { if (!activePoll) return false; - if (activePoll.revealResults) return true; // teacher manually revealed + if (activePoll.revealResults) return true; // instructor manually revealed if (activePoll.resultPolicy === 'never') return false; if (activePoll.resultPolicy === 'manual') return false; if (activePoll.resultPolicy === 'on_submit') return submitted || alreadyAnswered; @@ -100,7 +100,7 @@ export default function StudentPage() { function shouldShowCorrect() { if (!activePoll) return false; if (activePoll.correctIndex == null) return false; - if (activePoll.revealCorrect) return true; // teacher manually revealed + if (activePoll.revealCorrect) return true; // instructor manually revealed if (activePoll.correctPolicy === 'never') return false; if (activePoll.correctPolicy === 'manual') return false; if (activePoll.correctPolicy === 'with_results') return shouldShowResults(); @@ -135,7 +135,7 @@ export default function StudentPage() {

Hi, {name}! πŸ‘‹

-

Waiting for the teacher to start a poll…

+

Waiting for the instructor to start a poll…

@@ -186,7 +186,7 @@ export default function StudentPage() { )} {activePoll.ended && (
- ⏰ Time's up β€” waiting for teacher + ⏰ Time's up β€” waiting for instructor
)} @@ -241,7 +241,7 @@ export default function StudentPage() {
)} {pollStopped && (alreadyAnswered || submitted) && ( -
βœ“ Answer submitted β€” waiting for teacher
+
βœ“ Answer submitted β€” waiting for instructor
)}
From 683c11a24877d401c1143a4cb906aaccae0fcf93 Mon Sep 17 00:00:00 2001 From: Jody Date: Sun, 14 Jun 2026 16:46:19 -0600 Subject: [PATCH 4/4] Deploy --- dist/assets/index-CLC7Q4lX.js | 2747 +++++++++++++++++++++++++++++++++ 1 file changed, 2747 insertions(+) create mode 100644 dist/assets/index-CLC7Q4lX.js diff --git a/dist/assets/index-CLC7Q4lX.js b/dist/assets/index-CLC7Q4lX.js new file mode 100644 index 0000000..85584bc --- /dev/null +++ b/dist/assets/index-CLC7Q4lX.js @@ -0,0 +1,2747 @@ +function B_(t,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();function W_(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Kp={exports:{}},Nl={},Qp={exports:{}},G={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var As=Symbol.for("react.element"),$_=Symbol.for("react.portal"),V_=Symbol.for("react.fragment"),H_=Symbol.for("react.strict_mode"),G_=Symbol.for("react.profiler"),q_=Symbol.for("react.provider"),K_=Symbol.for("react.context"),Q_=Symbol.for("react.forward_ref"),Y_=Symbol.for("react.suspense"),J_=Symbol.for("react.memo"),X_=Symbol.for("react.lazy"),hh=Symbol.iterator;function Z_(t){return t===null||typeof t!="object"?null:(t=hh&&t[hh]||t["@@iterator"],typeof t=="function"?t:null)}var Yp={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Jp=Object.assign,Xp={};function fi(t,e,n){this.props=t,this.context=e,this.refs=Xp,this.updater=n||Yp}fi.prototype.isReactComponent={};fi.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};fi.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Zp(){}Zp.prototype=fi.prototype;function Sc(t,e,n){this.props=t,this.context=e,this.refs=Xp,this.updater=n||Yp}var Cc=Sc.prototype=new Zp;Cc.constructor=Sc;Jp(Cc,fi.prototype);Cc.isPureReactComponent=!0;var fh=Array.isArray,em=Object.prototype.hasOwnProperty,Ec={current:null},tm={key:!0,ref:!0,__self:!0,__source:!0};function nm(t,e,n){var r,i={},s=null,o=null;if(e!=null)for(r in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(s=""+e.key),e)em.call(e,r)&&!tm.hasOwnProperty(r)&&(i[r]=e[r]);var l=arguments.length-2;if(l===1)i.children=n;else if(1>>1,T=R[x];if(0>>1;xi(tt,y))Gei(L,tt)?(R[x]=L,R[Ge]=y,x=Ge):(R[x]=tt,R[K]=y,x=K);else if(Gei(L,y))R[x]=L,R[Ge]=y,x=Ge;else break e}}return U}function i(R,U){var y=R.sortIndex-U.sortIndex;return y!==0?y:R.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var a=[],u=[],h=1,d=null,f=3,v=!1,w=!1,_=!1,E=typeof setTimeout=="function"?setTimeout:null,g=typeof clearTimeout=="function"?clearTimeout:null,p=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function m(R){for(var U=n(u);U!==null;){if(U.callback===null)r(u);else if(U.startTime<=R)r(u),U.sortIndex=U.expirationTime,e(a,U);else break;U=n(u)}}function S(R){if(_=!1,m(R),!w)if(n(a)!==null)w=!0,Ee(I);else{var U=n(u);U!==null&&Be(S,U.startTime-R)}}function I(R,U){w=!1,_&&(_=!1,g(A),A=-1),v=!0;var y=f;try{for(m(U),d=n(a);d!==null&&(!(d.expirationTime>U)||R&&!pe());){var x=d.callback;if(typeof x=="function"){d.callback=null,f=d.priorityLevel;var T=x(d.expirationTime<=U);U=t.unstable_now(),typeof T=="function"?d.callback=T:d===n(a)&&r(a),m(U)}else r(a);d=n(a)}if(d!==null)var O=!0;else{var K=n(u);K!==null&&Be(S,K.startTime-U),O=!1}return O}finally{d=null,f=y,v=!1}}var P=!1,b=null,A=-1,q=5,z=-1;function pe(){return!(t.unstable_now()-zR||125x?(R.sortIndex=y,e(u,R),n(a)===null&&R===n(u)&&(_?(g(A),A=-1):_=!0,Be(S,y-x))):(R.sortIndex=T,e(a,R),w||v||(w=!0,Ee(I))),R},t.unstable_shouldYield=pe,t.unstable_wrapCallback=function(R){var U=f;return function(){var y=f;f=U;try{return R.apply(this,arguments)}finally{f=y}}}})(am);lm.exports=am;var d0=lm.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var h0=C,ht=d0;function k(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),eu=Object.prototype.hasOwnProperty,f0=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,mh={},gh={};function p0(t){return eu.call(gh,t)?!0:eu.call(mh,t)?!1:f0.test(t)?gh[t]=!0:(mh[t]=!0,!1)}function m0(t,e,n,r){if(n!==null&&n.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function g0(t,e,n,r){if(e===null||typeof e>"u"||m0(t,e,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function Ze(t,e,n,r,i,s,o){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=t,this.type=e,this.sanitizeURL=s,this.removeEmptyString=o}var Ue={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){Ue[t]=new Ze(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];Ue[e]=new Ze(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){Ue[t]=new Ze(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){Ue[t]=new Ze(t,2,!1,t,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(t){Ue[t]=new Ze(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){Ue[t]=new Ze(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){Ue[t]=new Ze(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){Ue[t]=new Ze(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){Ue[t]=new Ze(t,5,!1,t.toLowerCase(),null,!1,!1)});var Ic=/[\-:]([a-z])/g;function kc(t){return t[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(t){var e=t.replace(Ic,kc);Ue[e]=new Ze(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(Ic,kc);Ue[e]=new Ze(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(Ic,kc);Ue[e]=new Ze(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){Ue[t]=new Ze(t,1,!1,t.toLowerCase(),null,!1,!1)});Ue.xlinkHref=new Ze("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){Ue[t]=new Ze(t,1,!1,t.toLowerCase(),null,!0,!0)});function Tc(t,e,n,r){var i=Ue.hasOwnProperty(e)?Ue[e]:null;(i!==null?i.type!==0:r||!(2l||i[o]!==s[l]){var a=` +`+i[o].replace(" at new "," at ");return t.displayName&&a.includes("")&&(a=a.replace("",t.displayName)),a}while(1<=o&&0<=l);break}}}finally{pa=!1,Error.prepareStackTrace=n}return(t=t?t.displayName||t.name:"")?Mi(t):""}function v0(t){switch(t.tag){case 5:return Mi(t.type);case 16:return Mi("Lazy");case 13:return Mi("Suspense");case 19:return Mi("SuspenseList");case 0:case 2:case 15:return t=ma(t.type,!1),t;case 11:return t=ma(t.type.render,!1),t;case 1:return t=ma(t.type,!0),t;default:return""}}function iu(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case Pr:return"Fragment";case br:return"Portal";case tu:return"Profiler";case bc:return"StrictMode";case nu:return"Suspense";case ru:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case dm:return(t.displayName||"Context")+".Consumer";case cm:return(t._context.displayName||"Context")+".Provider";case Pc:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Nc:return e=t.displayName||null,e!==null?e:iu(t.type)||"Memo";case pn:e=t._payload,t=t._init;try{return iu(t(e))}catch{}}return null}function y0(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return iu(e);case 8:return e===bc?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function zn(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function fm(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function _0(t){var e=fm(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),r=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return i.call(this)},set:function(o){r=""+o,s.call(this,o)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function Xs(t){t._valueTracker||(t._valueTracker=_0(t))}function pm(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=fm(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function Mo(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function su(t,e){var n=e.checked;return ve({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??t._wrapperState.initialChecked})}function yh(t,e){var n=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;n=zn(e.value!=null?e.value:n),t._wrapperState={initialChecked:r,initialValue:n,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function mm(t,e){e=e.checked,e!=null&&Tc(t,"checked",e,!1)}function ou(t,e){mm(t,e);var n=zn(e.value),r=e.type;if(n!=null)r==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+n):t.value!==""+n&&(t.value=""+n);else if(r==="submit"||r==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?lu(t,e.type,n):e.hasOwnProperty("defaultValue")&&lu(t,e.type,zn(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function _h(t,e,n){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var r=e.type;if(!(r!=="submit"&&r!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,n||e===t.value||(t.value=e),t.defaultValue=e}n=t.name,n!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,n!==""&&(t.name=n)}function lu(t,e,n){(e!=="number"||Mo(t.ownerDocument)!==t)&&(n==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+n&&(t.defaultValue=""+n))}var ji=Array.isArray;function Wr(t,e,n,r){if(t=t.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=Zs.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function ns(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var zi={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},w0=["Webkit","ms","Moz","O"];Object.keys(zi).forEach(function(t){w0.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),zi[e]=zi[t]})});function _m(t,e,n){return e==null||typeof e=="boolean"||e===""?"":n||typeof e!="number"||e===0||zi.hasOwnProperty(t)&&zi[t]?(""+e).trim():e+"px"}function wm(t,e){t=t.style;for(var n in e)if(e.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=_m(n,e[n],r);n==="float"&&(n="cssFloat"),r?t.setProperty(n,i):t[n]=i}}var S0=ve({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function cu(t,e){if(e){if(S0[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(k(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(k(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(k(61))}if(e.style!=null&&typeof e.style!="object")throw Error(k(62))}}function du(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var hu=null;function Rc(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var fu=null,$r=null,Vr=null;function Ch(t){if(t=Ls(t)){if(typeof fu!="function")throw Error(k(280));var e=t.stateNode;e&&(e=Ll(e),fu(t.stateNode,t.type,e))}}function Sm(t){$r?Vr?Vr.push(t):Vr=[t]:$r=t}function Cm(){if($r){var t=$r,e=Vr;if(Vr=$r=null,Ch(t),e)for(t=0;t>>=0,t===0?32:31-(A0(t)/O0|0)|0}var eo=64,to=4194304;function Fi(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function zo(t,e){var n=t.pendingLanes;if(n===0)return 0;var r=0,i=t.suspendedLanes,s=t.pingedLanes,o=n&268435455;if(o!==0){var l=o&~i;l!==0?r=Fi(l):(s&=o,s!==0&&(r=Fi(s)))}else o=n&~i,o!==0?r=Fi(o):s!==0&&(r=Fi(s));if(r===0)return 0;if(e!==0&&e!==r&&!(e&i)&&(i=r&-r,s=e&-e,i>=s||i===16&&(s&4194240)!==0))return e;if(r&4&&(r|=n&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=r;0n;n++)e.push(t);return e}function Os(t,e,n){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-Nt(e),t[e]=n}function j0(t,e){var n=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var r=t.eventTimes;for(t=t.expirationTimes;0=Wi),Rh=" ",Ah=!1;function Wm(t,e){switch(t){case"keyup":return dw.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function $m(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Nr=!1;function fw(t,e){switch(t){case"compositionend":return $m(e);case"keypress":return e.which!==32?null:(Ah=!0,Rh);case"textInput":return t=e.data,t===Rh&&Ah?null:t;default:return null}}function pw(t,e){if(Nr)return t==="compositionend"||!Uc&&Wm(t,e)?(t=zm(),wo=Mc=Cn=null,Nr=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:n,offset:e-t};t=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Mh(n)}}function qm(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?qm(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Km(){for(var t=window,e=Mo();e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=Mo(t.document)}return e}function zc(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function Ew(t){var e=Km(),n=t.focusedElem,r=t.selectionRange;if(e!==n&&n&&n.ownerDocument&&qm(n.ownerDocument.documentElement,n)){if(r!==null&&zc(n)){if(e=r.start,t=r.end,t===void 0&&(t=e),"selectionStart"in n)n.selectionStart=e,n.selectionEnd=Math.min(t,n.value.length);else if(t=(e=n.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=r.end===void 0?s:Math.min(r.end,i),!t.extend&&s>r&&(i=r,r=s,s=i),i=jh(n,s);var o=jh(n,r);i&&o&&(t.rangeCount!==1||t.anchorNode!==i.node||t.anchorOffset!==i.offset||t.focusNode!==o.node||t.focusOffset!==o.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),t.removeAllRanges(),s>r?(t.addRange(e),t.extend(o.node,o.offset)):(e.setEnd(o.node,o.offset),t.addRange(e)))}}for(e=[],t=n;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Rr=null,_u=null,Vi=null,wu=!1;function Fh(t,e,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;wu||Rr==null||Rr!==Mo(r)||(r=Rr,"selectionStart"in r&&zc(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Vi&&as(Vi,r)||(Vi=r,r=$o(_u,"onSelect"),0Dr||(t.current=ku[Dr],ku[Dr]=null,Dr--)}function ce(t,e){Dr++,ku[Dr]=t.current,t.current=e}var Bn={},He=qn(Bn),ot=qn(!1),ar=Bn;function ei(t,e){var n=t.type.contextTypes;if(!n)return Bn;var r=t.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in n)i[s]=e[s];return r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=i),i}function lt(t){return t=t.childContextTypes,t!=null}function Ho(){he(ot),he(He)}function Hh(t,e,n){if(He.current!==Bn)throw Error(k(168));ce(He,e),ce(ot,n)}function rg(t,e,n){var r=t.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in e))throw Error(k(108,y0(t)||"Unknown",i));return ve({},n,r)}function Go(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||Bn,ar=He.current,ce(He,t),ce(ot,ot.current),!0}function Gh(t,e,n){var r=t.stateNode;if(!r)throw Error(k(169));n?(t=rg(t,e,ar),r.__reactInternalMemoizedMergedChildContext=t,he(ot),he(He),ce(He,t)):he(ot),ce(ot,n)}var $t=null,Ml=!1,Pa=!1;function ig(t){$t===null?$t=[t]:$t.push(t)}function Lw(t){Ml=!0,ig(t)}function Kn(){if(!Pa&&$t!==null){Pa=!0;var t=0,e=ie;try{var n=$t;for(ie=1;t>=o,i-=o,Vt=1<<32-Nt(e)+i|n<A?(q=b,b=null):q=b.sibling;var z=f(g,b,m[A],S);if(z===null){b===null&&(b=q);break}t&&b&&z.alternate===null&&e(g,b),p=s(z,p,A),P===null?I=z:P.sibling=z,P=z,b=q}if(A===m.length)return n(g,b),fe&&Jn(g,A),I;if(b===null){for(;AA?(q=b,b=null):q=b.sibling;var pe=f(g,b,z.value,S);if(pe===null){b===null&&(b=q);break}t&&b&&pe.alternate===null&&e(g,b),p=s(pe,p,A),P===null?I=pe:P.sibling=pe,P=pe,b=q}if(z.done)return n(g,b),fe&&Jn(g,A),I;if(b===null){for(;!z.done;A++,z=m.next())z=d(g,z.value,S),z!==null&&(p=s(z,p,A),P===null?I=z:P.sibling=z,P=z);return fe&&Jn(g,A),I}for(b=r(g,b);!z.done;A++,z=m.next())z=v(b,g,A,z.value,S),z!==null&&(t&&z.alternate!==null&&b.delete(z.key===null?A:z.key),p=s(z,p,A),P===null?I=z:P.sibling=z,P=z);return t&&b.forEach(function(D){return e(g,D)}),fe&&Jn(g,A),I}function E(g,p,m,S){if(typeof m=="object"&&m!==null&&m.type===Pr&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case Js:e:{for(var I=m.key,P=p;P!==null;){if(P.key===I){if(I=m.type,I===Pr){if(P.tag===7){n(g,P.sibling),p=i(P,m.props.children),p.return=g,g=p;break e}}else if(P.elementType===I||typeof I=="object"&&I!==null&&I.$$typeof===pn&&Qh(I)===P.type){n(g,P.sibling),p=i(P,m.props),p.ref=Pi(g,P,m),p.return=g,g=p;break e}n(g,P);break}else e(g,P);P=P.sibling}m.type===Pr?(p=or(m.props.children,g.mode,S,m.key),p.return=g,g=p):(S=bo(m.type,m.key,m.props,null,g.mode,S),S.ref=Pi(g,p,m),S.return=g,g=S)}return o(g);case br:e:{for(P=m.key;p!==null;){if(p.key===P)if(p.tag===4&&p.stateNode.containerInfo===m.containerInfo&&p.stateNode.implementation===m.implementation){n(g,p.sibling),p=i(p,m.children||[]),p.return=g,g=p;break e}else{n(g,p);break}else e(g,p);p=p.sibling}p=ja(m,g.mode,S),p.return=g,g=p}return o(g);case pn:return P=m._init,E(g,p,P(m._payload),S)}if(ji(m))return w(g,p,m,S);if(xi(m))return _(g,p,m,S);ao(g,m)}return typeof m=="string"&&m!==""||typeof m=="number"?(m=""+m,p!==null&&p.tag===6?(n(g,p.sibling),p=i(p,m),p.return=g,g=p):(n(g,p),p=Ma(m,g.mode,S),p.return=g,g=p),o(g)):n(g,p)}return E}var ni=ag(!0),ug=ag(!1),Qo=qn(null),Yo=null,jr=null,Vc=null;function Hc(){Vc=jr=Yo=null}function Gc(t){var e=Qo.current;he(Qo),t._currentValue=e}function Pu(t,e,n){for(;t!==null;){var r=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),t===n)break;t=t.return}}function Gr(t,e){Yo=t,Vc=jr=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(it=!0),t.firstContext=null)}function wt(t){var e=t._currentValue;if(Vc!==t)if(t={context:t,memoizedValue:e,next:null},jr===null){if(Yo===null)throw Error(k(308));jr=t,Yo.dependencies={lanes:0,firstContext:t}}else jr=jr.next=t;return e}var nr=null;function qc(t){nr===null?nr=[t]:nr.push(t)}function cg(t,e,n,r){var i=e.interleaved;return i===null?(n.next=n,qc(e)):(n.next=i.next,i.next=n),e.interleaved=n,tn(t,r)}function tn(t,e){t.lanes|=e;var n=t.alternate;for(n!==null&&(n.lanes|=e),n=t,t=t.return;t!==null;)t.childLanes|=e,n=t.alternate,n!==null&&(n.childLanes|=e),n=t,t=t.return;return n.tag===3?n.stateNode:null}var mn=!1;function Kc(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function dg(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function Jt(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function Nn(t,e,n){var r=t.updateQueue;if(r===null)return null;if(r=r.shared,J&2){var i=r.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),r.pending=e,tn(t,n)}return i=r.interleaved,i===null?(e.next=e,qc(r)):(e.next=i.next,i.next=e),r.interleaved=e,tn(t,n)}function Co(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194240)!==0)){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,Oc(t,n)}}function Yh(t,e){var n=t.updateQueue,r=t.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?i=s=o:s=s.next=o,n=n.next}while(n!==null);s===null?i=s=e:s=s.next=e}else i=s=e;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}function Jo(t,e,n,r){var i=t.updateQueue;mn=!1;var s=i.firstBaseUpdate,o=i.lastBaseUpdate,l=i.shared.pending;if(l!==null){i.shared.pending=null;var a=l,u=a.next;a.next=null,o===null?s=u:o.next=u,o=a;var h=t.alternate;h!==null&&(h=h.updateQueue,l=h.lastBaseUpdate,l!==o&&(l===null?h.firstBaseUpdate=u:l.next=u,h.lastBaseUpdate=a))}if(s!==null){var d=i.baseState;o=0,h=u=a=null,l=s;do{var f=l.lane,v=l.eventTime;if((r&f)===f){h!==null&&(h=h.next={eventTime:v,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var w=t,_=l;switch(f=e,v=n,_.tag){case 1:if(w=_.payload,typeof w=="function"){d=w.call(v,d,f);break e}d=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=_.payload,f=typeof w=="function"?w.call(v,d,f):w,f==null)break e;d=ve({},d,f);break e;case 2:mn=!0}}l.callback!==null&&l.lane!==0&&(t.flags|=64,f=i.effects,f===null?i.effects=[l]:f.push(l))}else v={eventTime:v,lane:f,tag:l.tag,payload:l.payload,callback:l.callback,next:null},h===null?(u=h=v,a=d):h=h.next=v,o|=f;if(l=l.next,l===null){if(l=i.shared.pending,l===null)break;f=l,l=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(!0);if(h===null&&(a=d),i.baseState=a,i.firstBaseUpdate=u,i.lastBaseUpdate=h,e=i.shared.interleaved,e!==null){i=e;do o|=i.lane,i=i.next;while(i!==e)}else s===null&&(i.shared.lanes=0);dr|=o,t.lanes=o,t.memoizedState=d}}function Jh(t,e,n){if(t=e.effects,e.effects=null,t!==null)for(e=0;en?n:4,t(!0);var r=Ra.transition;Ra.transition={};try{t(!1),e()}finally{ie=n,Ra.transition=r}}function bg(){return St().memoizedState}function Uw(t,e,n){var r=An(t);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Pg(t))Ng(e,n);else if(n=cg(t,e,n,r),n!==null){var i=Qe();Rt(n,t,r,i),Rg(n,e,r)}}function zw(t,e,n){var r=An(t),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Pg(t))Ng(e,i);else{var s=t.alternate;if(t.lanes===0&&(s===null||s.lanes===0)&&(s=e.lastRenderedReducer,s!==null))try{var o=e.lastRenderedState,l=s(o,n);if(i.hasEagerState=!0,i.eagerState=l,Ot(l,o)){var a=e.interleaved;a===null?(i.next=i,qc(e)):(i.next=a.next,a.next=i),e.interleaved=i;return}}catch{}finally{}n=cg(t,e,i,r),n!==null&&(i=Qe(),Rt(n,t,r,i),Rg(n,e,r))}}function Pg(t){var e=t.alternate;return t===ge||e!==null&&e===ge}function Ng(t,e){Hi=Zo=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function Rg(t,e,n){if(n&4194240){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,Oc(t,n)}}var el={readContext:wt,useCallback:We,useContext:We,useEffect:We,useImperativeHandle:We,useInsertionEffect:We,useLayoutEffect:We,useMemo:We,useReducer:We,useRef:We,useState:We,useDebugValue:We,useDeferredValue:We,useTransition:We,useMutableSource:We,useSyncExternalStore:We,useId:We,unstable_isNewReconciler:!1},Bw={readContext:wt,useCallback:function(t,e){return Lt().memoizedState=[t,e===void 0?null:e],t},useContext:wt,useEffect:Zh,useImperativeHandle:function(t,e,n){return n=n!=null?n.concat([t]):null,xo(4194308,4,Eg.bind(null,e,t),n)},useLayoutEffect:function(t,e){return xo(4194308,4,t,e)},useInsertionEffect:function(t,e){return xo(4,2,t,e)},useMemo:function(t,e){var n=Lt();return e=e===void 0?null:e,t=t(),n.memoizedState=[t,e],t},useReducer:function(t,e,n){var r=Lt();return e=n!==void 0?n(e):e,r.memoizedState=r.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},r.queue=t,t=t.dispatch=Uw.bind(null,ge,t),[r.memoizedState,t]},useRef:function(t){var e=Lt();return t={current:t},e.memoizedState=t},useState:Xh,useDebugValue:nd,useDeferredValue:function(t){return Lt().memoizedState=t},useTransition:function(){var t=Xh(!1),e=t[0];return t=Fw.bind(null,t[1]),Lt().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,n){var r=ge,i=Lt();if(fe){if(n===void 0)throw Error(k(407));n=n()}else{if(n=e(),Le===null)throw Error(k(349));cr&30||mg(r,e,n)}i.memoizedState=n;var s={value:n,getSnapshot:e};return i.queue=s,Zh(vg.bind(null,r,s,t),[t]),r.flags|=2048,gs(9,gg.bind(null,r,s,n,e),void 0,null),n},useId:function(){var t=Lt(),e=Le.identifierPrefix;if(fe){var n=Ht,r=Vt;n=(r&~(1<<32-Nt(r)-1)).toString(32)+n,e=":"+e+"R"+n,n=ps++,0<\/script>",t=t.removeChild(t.firstChild)):typeof r.is=="string"?t=o.createElement(n,{is:r.is}):(t=o.createElement(n),n==="select"&&(o=t,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):t=o.createElementNS(t,n),t[Mt]=e,t[ds]=r,Bg(t,e,!1,!1),e.stateNode=t;e:{switch(o=du(n,r),n){case"dialog":de("cancel",t),de("close",t),i=r;break;case"iframe":case"object":case"embed":de("load",t),i=r;break;case"video":case"audio":for(i=0;isi&&(e.flags|=128,r=!0,Ni(s,!1),e.lanes=4194304)}else{if(!r)if(t=Xo(o),t!==null){if(e.flags|=128,r=!0,n=t.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),Ni(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!fe)return $e(e),null}else 2*Ce()-s.renderingStartTime>si&&n!==1073741824&&(e.flags|=128,r=!0,Ni(s,!1),e.lanes=4194304);s.isBackwards?(o.sibling=e.child,e.child=o):(n=s.last,n!==null?n.sibling=o:e.child=o,s.last=o)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=Ce(),e.sibling=null,n=me.current,ce(me,r?n&1|2:n&1),e):($e(e),null);case 22:case 23:return ad(),r=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==r&&(e.flags|=8192),r&&e.mode&1?ut&1073741824&&($e(e),e.subtreeFlags&6&&(e.flags|=8192)):$e(e),null;case 24:return null;case 25:return null}throw Error(k(156,e.tag))}function Qw(t,e){switch(Wc(e),e.tag){case 1:return lt(e.type)&&Ho(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return ri(),he(ot),he(He),Jc(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return Yc(e),null;case 13:if(he(me),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(k(340));ti()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return he(me),null;case 4:return ri(),null;case 10:return Gc(e.type._context),null;case 22:case 23:return ad(),null;case 24:return null;default:return null}}var co=!1,Ve=!1,Yw=typeof WeakSet=="function"?WeakSet:Set,M=null;function Fr(t,e){var n=t.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ye(t,e,r)}else n.current=null}function Fu(t,e,n){try{n()}catch(r){ye(t,e,r)}}var df=!1;function Jw(t,e){if(Su=Bo,t=Km(),zc(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var o=0,l=-1,a=-1,u=0,h=0,d=t,f=null;t:for(;;){for(var v;d!==n||i!==0&&d.nodeType!==3||(l=o+i),d!==s||r!==0&&d.nodeType!==3||(a=o+r),d.nodeType===3&&(o+=d.nodeValue.length),(v=d.firstChild)!==null;)f=d,d=v;for(;;){if(d===t)break t;if(f===n&&++u===i&&(l=o),f===s&&++h===r&&(a=o),(v=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=v}n=l===-1||a===-1?null:{start:l,end:a}}else n=null}n=n||{start:0,end:0}}else n=null;for(Cu={focusedElem:t,selectionRange:n},Bo=!1,M=e;M!==null;)if(e=M,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,M=t;else for(;M!==null;){e=M;try{var w=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var _=w.memoizedProps,E=w.memoizedState,g=e.stateNode,p=g.getSnapshotBeforeUpdate(e.elementType===e.type?_:It(e.type,_),E);g.__reactInternalSnapshotBeforeUpdate=p}break;case 3:var m=e.stateNode.containerInfo;m.nodeType===1?m.textContent="":m.nodeType===9&&m.documentElement&&m.removeChild(m.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(k(163))}}catch(S){ye(e,e.return,S)}if(t=e.sibling,t!==null){t.return=e.return,M=t;break}M=e.return}return w=df,df=!1,w}function Gi(t,e,n){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&t)===t){var s=i.destroy;i.destroy=void 0,s!==void 0&&Fu(e,n,s)}i=i.next}while(i!==r)}}function Ul(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var n=e=e.next;do{if((n.tag&t)===t){var r=n.create;n.destroy=r()}n=n.next}while(n!==e)}}function Uu(t){var e=t.ref;if(e!==null){var n=t.stateNode;switch(t.tag){case 5:t=n;break;default:t=n}typeof e=="function"?e(t):e.current=t}}function Vg(t){var e=t.alternate;e!==null&&(t.alternate=null,Vg(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[Mt],delete e[ds],delete e[Iu],delete e[Ow],delete e[Dw])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function Hg(t){return t.tag===5||t.tag===3||t.tag===4}function hf(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Hg(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function zu(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.nodeType===8?n.parentNode.insertBefore(t,e):n.insertBefore(t,e):(n.nodeType===8?(e=n.parentNode,e.insertBefore(t,n)):(e=n,e.appendChild(t)),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=Vo));else if(r!==4&&(t=t.child,t!==null))for(zu(t,e,n),t=t.sibling;t!==null;)zu(t,e,n),t=t.sibling}function Bu(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(r!==4&&(t=t.child,t!==null))for(Bu(t,e,n),t=t.sibling;t!==null;)Bu(t,e,n),t=t.sibling}var Me=null,kt=!1;function dn(t,e,n){for(n=n.child;n!==null;)Gg(t,e,n),n=n.sibling}function Gg(t,e,n){if(jt&&typeof jt.onCommitFiberUnmount=="function")try{jt.onCommitFiberUnmount(Rl,n)}catch{}switch(n.tag){case 5:Ve||Fr(n,e);case 6:var r=Me,i=kt;Me=null,dn(t,e,n),Me=r,kt=i,Me!==null&&(kt?(t=Me,n=n.stateNode,t.nodeType===8?t.parentNode.removeChild(n):t.removeChild(n)):Me.removeChild(n.stateNode));break;case 18:Me!==null&&(kt?(t=Me,n=n.stateNode,t.nodeType===8?ba(t.parentNode,n):t.nodeType===1&&ba(t,n),os(t)):ba(Me,n.stateNode));break;case 4:r=Me,i=kt,Me=n.stateNode.containerInfo,kt=!0,dn(t,e,n),Me=r,kt=i;break;case 0:case 11:case 14:case 15:if(!Ve&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var s=i,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&Fu(n,e,o),i=i.next}while(i!==r)}dn(t,e,n);break;case 1:if(!Ve&&(Fr(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){ye(n,e,l)}dn(t,e,n);break;case 21:dn(t,e,n);break;case 22:n.mode&1?(Ve=(r=Ve)||n.memoizedState!==null,dn(t,e,n),Ve=r):dn(t,e,n);break;default:dn(t,e,n)}}function ff(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var n=t.stateNode;n===null&&(n=t.stateNode=new Yw),e.forEach(function(r){var i=oS.bind(null,t,r);n.has(r)||(n.add(r),r.then(i,i))})}}function xt(t,e){var n=e.deletions;if(n!==null)for(var r=0;ri&&(i=o),r&=~s}if(r=i,r=Ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Zw(r/1960))-r,10t?16:t,En===null)var r=!1;else{if(t=En,En=null,rl=0,J&6)throw Error(k(331));var i=J;for(J|=4,M=t.current;M!==null;){var s=M,o=s.child;if(M.flags&16){var l=s.deletions;if(l!==null){for(var a=0;aCe()-od?sr(t,0):sd|=n),at(t,e)}function ev(t,e){e===0&&(t.mode&1?(e=to,to<<=1,!(to&130023424)&&(to=4194304)):e=1);var n=Qe();t=tn(t,e),t!==null&&(Os(t,e,n),at(t,n))}function sS(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),ev(t,n)}function oS(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,i=t.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=t.stateNode;break;default:throw Error(k(314))}r!==null&&r.delete(e),ev(t,n)}var tv;tv=function(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps||ot.current)it=!0;else{if(!(t.lanes&n)&&!(e.flags&128))return it=!1,qw(t,e,n);it=!!(t.flags&131072)}else it=!1,fe&&e.flags&1048576&&sg(e,Ko,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;Io(t,e),t=e.pendingProps;var i=ei(e,He.current);Gr(e,n),i=Zc(null,e,r,t,i,n);var s=ed();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,lt(r)?(s=!0,Go(e)):s=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Kc(e),i.updater=Fl,e.stateNode=i,i._reactInternals=e,Ru(e,r,t,n),e=Du(null,e,r,!0,s,n)):(e.tag=0,fe&&s&&Bc(e),qe(null,e,i,n),e=e.child),e;case 16:r=e.elementType;e:{switch(Io(t,e),t=e.pendingProps,i=r._init,r=i(r._payload),e.type=r,i=e.tag=aS(r),t=It(r,t),i){case 0:e=Ou(null,e,r,t,n);break e;case 1:e=af(null,e,r,t,n);break e;case 11:e=of(null,e,r,t,n);break e;case 14:e=lf(null,e,r,It(r.type,t),n);break e}throw Error(k(306,r,""))}return e;case 0:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:It(r,i),Ou(t,e,r,i,n);case 1:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:It(r,i),af(t,e,r,i,n);case 3:e:{if(Fg(e),t===null)throw Error(k(387));r=e.pendingProps,s=e.memoizedState,i=s.element,dg(t,e),Jo(e,r,null,n);var o=e.memoizedState;if(r=o.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},e.updateQueue.baseState=s,e.memoizedState=s,e.flags&256){i=ii(Error(k(423)),e),e=uf(t,e,r,n,i);break e}else if(r!==i){i=ii(Error(k(424)),e),e=uf(t,e,r,n,i);break e}else for(ct=Pn(e.stateNode.containerInfo.firstChild),dt=e,fe=!0,Tt=null,n=ug(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ti(),r===i){e=nn(t,e,n);break e}qe(t,e,r,n)}e=e.child}return e;case 5:return hg(e),t===null&&bu(e),r=e.type,i=e.pendingProps,s=t!==null?t.memoizedProps:null,o=i.children,Eu(r,i)?o=null:s!==null&&Eu(r,s)&&(e.flags|=32),jg(t,e),qe(t,e,o,n),e.child;case 6:return t===null&&bu(e),null;case 13:return Ug(t,e,n);case 4:return Qc(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=ni(e,null,r,n):qe(t,e,r,n),e.child;case 11:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:It(r,i),of(t,e,r,i,n);case 7:return qe(t,e,e.pendingProps,n),e.child;case 8:return qe(t,e,e.pendingProps.children,n),e.child;case 12:return qe(t,e,e.pendingProps.children,n),e.child;case 10:e:{if(r=e.type._context,i=e.pendingProps,s=e.memoizedProps,o=i.value,ce(Qo,r._currentValue),r._currentValue=o,s!==null)if(Ot(s.value,o)){if(s.children===i.children&&!ot.current){e=nn(t,e,n);break e}}else for(s=e.child,s!==null&&(s.return=e);s!==null;){var l=s.dependencies;if(l!==null){o=s.child;for(var a=l.firstContext;a!==null;){if(a.context===r){if(s.tag===1){a=Jt(-1,n&-n),a.tag=2;var u=s.updateQueue;if(u!==null){u=u.shared;var h=u.pending;h===null?a.next=a:(a.next=h.next,h.next=a),u.pending=a}}s.lanes|=n,a=s.alternate,a!==null&&(a.lanes|=n),Pu(s.return,n,e),l.lanes|=n;break}a=a.next}}else if(s.tag===10)o=s.type===e.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(k(341));o.lanes|=n,l=o.alternate,l!==null&&(l.lanes|=n),Pu(o,n,e),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===e){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}qe(t,e,i.children,n),e=e.child}return e;case 9:return i=e.type,r=e.pendingProps.children,Gr(e,n),i=wt(i),r=r(i),e.flags|=1,qe(t,e,r,n),e.child;case 14:return r=e.type,i=It(r,e.pendingProps),i=It(r.type,i),lf(t,e,r,i,n);case 15:return Lg(t,e,e.type,e.pendingProps,n);case 17:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:It(r,i),Io(t,e),e.tag=1,lt(r)?(t=!0,Go(e)):t=!1,Gr(e,n),Ag(e,r,i),Ru(e,r,i,n),Du(null,e,r,!0,t,n);case 19:return zg(t,e,n);case 22:return Mg(t,e,n)}throw Error(k(156,e.tag))};function nv(t,e){return Pm(t,e)}function lS(t,e,n,r){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function vt(t,e,n,r){return new lS(t,e,n,r)}function cd(t){return t=t.prototype,!(!t||!t.isReactComponent)}function aS(t){if(typeof t=="function")return cd(t)?1:0;if(t!=null){if(t=t.$$typeof,t===Pc)return 11;if(t===Nc)return 14}return 2}function On(t,e){var n=t.alternate;return n===null?(n=vt(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&14680064,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n}function bo(t,e,n,r,i,s){var o=2;if(r=t,typeof t=="function")cd(t)&&(o=1);else if(typeof t=="string")o=5;else e:switch(t){case Pr:return or(n.children,i,s,e);case bc:o=8,i|=8;break;case tu:return t=vt(12,n,e,i|2),t.elementType=tu,t.lanes=s,t;case nu:return t=vt(13,n,e,i),t.elementType=nu,t.lanes=s,t;case ru:return t=vt(19,n,e,i),t.elementType=ru,t.lanes=s,t;case hm:return Bl(n,i,s,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case cm:o=10;break e;case dm:o=9;break e;case Pc:o=11;break e;case Nc:o=14;break e;case pn:o=16,r=null;break e}throw Error(k(130,t==null?t:typeof t,""))}return e=vt(o,n,e,i),e.elementType=t,e.type=r,e.lanes=s,e}function or(t,e,n,r){return t=vt(7,t,r,e),t.lanes=n,t}function Bl(t,e,n,r){return t=vt(22,t,r,e),t.elementType=hm,t.lanes=n,t.stateNode={isHidden:!1},t}function Ma(t,e,n){return t=vt(6,t,null,e),t.lanes=n,t}function ja(t,e,n){return e=vt(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function uS(t,e,n,r,i){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=va(0),this.expirationTimes=va(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=va(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function dd(t,e,n,r,i,s,o,l,a){return t=new uS(t,e,n,l,a),e===1?(e=1,s===!0&&(e|=8)):e=0,s=vt(3,null,null,e),t.current=s,s.stateNode=t,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Kc(s),t}function cS(t,e,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(ov)}catch(t){console.error(t)}}ov(),om.exports=ft;var mS=om.exports,Sf=mS;Za.createRoot=Sf.createRoot,Za.hydrateRoot=Sf.hydrateRoot;/** + * @remix-run/router v1.23.3 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function ys(){return ys=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function md(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function vS(){return Math.random().toString(36).substr(2,8)}function Ef(t,e){return{usr:t.state,key:t.key,idx:e}}function Gu(t,e,n,r){return n===void 0&&(n=null),ys({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?gi(e):e,{state:n,key:e&&e.key||r||vS()})}function lv(t){let{pathname:e="/",search:n="",hash:r=""}=t;return n&&n!=="?"&&(e+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(e+=r.charAt(0)==="#"?r:"#"+r),e}function gi(t){let e={};if(t){let n=t.indexOf("#");n>=0&&(e.hash=t.substr(n),t=t.substr(0,n));let r=t.indexOf("?");r>=0&&(e.search=t.substr(r),t=t.substr(0,r)),t&&(e.pathname=t)}return e}function yS(t,e,n,r){r===void 0&&(r={});let{window:i=document.defaultView,v5Compat:s=!1}=r,o=i.history,l=xn.Pop,a=null,u=h();u==null&&(u=0,o.replaceState(ys({},o.state,{idx:u}),""));function h(){return(o.state||{idx:null}).idx}function d(){l=xn.Pop;let E=h(),g=E==null?null:E-u;u=E,a&&a({action:l,location:_.location,delta:g})}function f(E,g){l=xn.Push;let p=Gu(_.location,E,g);u=h()+1;let m=Ef(p,u),S=_.createHref(p);try{o.pushState(m,"",S)}catch(I){if(I instanceof DOMException&&I.name==="DataCloneError")throw I;i.location.assign(S)}s&&a&&a({action:l,location:_.location,delta:1})}function v(E,g){l=xn.Replace;let p=Gu(_.location,E,g);u=h();let m=Ef(p,u),S=_.createHref(p);o.replaceState(m,"",S),s&&a&&a({action:l,location:_.location,delta:0})}function w(E){let g=i.location.origin!=="null"?i.location.origin:i.location.href,p=typeof E=="string"?E:lv(E);return p=p.replace(/ $/,"%20"),ke(g,"No window.location.(origin|href) available to create URL for href: "+p),new URL(p,g)}let _={get action(){return l},get location(){return t(i,o)},listen(E){if(a)throw new Error("A history only accepts one active listener");return i.addEventListener(Cf,d),a=E,()=>{i.removeEventListener(Cf,d),a=null}},createHref(E){return e(i,E)},createURL:w,encodeLocation(E){let g=w(E);return{pathname:g.pathname,search:g.search,hash:g.hash}},push:f,replace:v,go(E){return o.go(E)}};return _}var xf;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(xf||(xf={}));function _S(t,e,n){return n===void 0&&(n="/"),wS(t,e,n)}function wS(t,e,n,r){let i=typeof e=="string"?gi(e):e,s=cv(i.pathname||"/",n);if(s==null)return null;let o=av(t);SS(o);let l=null,a=OS(s);for(let u=0;l==null&&u{let a={relativePath:l===void 0?s.path||"":l,caseSensitive:s.caseSensitive===!0,childrenIndex:o,route:s};a.relativePath.startsWith("/")&&(ke(a.relativePath.startsWith(r),'Absolute route path "'+a.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),a.relativePath=a.relativePath.slice(r.length));let u=lr([r,a.relativePath]),h=n.concat(a);s.children&&s.children.length>0&&(ke(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+u+'".')),av(s.children,e,h,u)),!(s.path==null&&!s.index)&&e.push({path:u,score:bS(u,s.index),routesMeta:h})};return t.forEach((s,o)=>{var l;if(s.path===""||!((l=s.path)!=null&&l.includes("?")))i(s,o);else for(let a of uv(s.path))i(s,o,a)}),e}function uv(t){let e=t.split("/");if(e.length===0)return[];let[n,...r]=e,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return i?[s,""]:[s];let o=uv(r.join("/")),l=[];return l.push(...o.map(a=>a===""?s:[s,a].join("/"))),i&&l.push(...o),l.map(a=>t.startsWith("/")&&a===""?"/":a)}function SS(t){t.sort((e,n)=>e.score!==n.score?n.score-e.score:PS(e.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const CS=/^:[\w-]+$/,ES=3,xS=2,IS=1,kS=10,TS=-2,If=t=>t==="*";function bS(t,e){let n=t.split("/"),r=n.length;return n.some(If)&&(r+=TS),e&&(r+=xS),n.filter(i=>!If(i)).reduce((i,s)=>i+(CS.test(s)?ES:s===""?IS:kS),r)}function PS(t,e){return t.length===e.length&&t.slice(0,-1).every((r,i)=>r===e[i])?t[t.length-1]-e[e.length-1]:0}function NS(t,e,n){let{routesMeta:r}=t,i={},s="/",o=[];for(let l=0;l{let{paramName:f,isOptional:v}=h;if(f==="*"){let _=l[d]||"";o=s.slice(0,s.length-_.length).replace(/(.)\/+$/,"$1")}const w=l[d];return v&&!w?u[f]=void 0:u[f]=(w||"").replace(/%2F/g,"/"),u},{}),pathname:s,pathnameBase:o,pattern:t}}function AS(t,e,n){e===void 0&&(e=!1),n===void 0&&(n=!0),md(t==="*"||!t.endsWith("*")||t.endsWith("/*"),'Route path "'+t+'" will be treated as if it were '+('"'+t.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+t.replace(/\*$/,"/*")+'".'));let r=[],i="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,l,a)=>(r.push({paramName:l,isOptional:a!=null}),a?"/?([^\\/]+)?":"/([^\\/]+)"));return t.endsWith("*")?(r.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),r]}function OS(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return md(!1,'The URL path "'+t+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),t}}function cv(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let n=e.endsWith("/")?e.length-1:e.length,r=t.charAt(n);return r&&r!=="/"?null:t.slice(n)||"/"}const DS=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,LS=t=>DS.test(t);function MS(t,e){e===void 0&&(e="/");let{pathname:n,search:r="",hash:i=""}=typeof t=="string"?gi(t):t,s;if(n)if(LS(n))s=n;else{if(n.includes("//")){let o=n;n=fv(n),md(!1,"Pathnames cannot have embedded double slashes - normalizing "+(o+" -> "+n))}n.startsWith("/")?s=kf(n.substring(1),"/"):s=kf(n,e)}else s=e;return{pathname:s,search:US(r),hash:zS(i)}}function kf(t,e){let n=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(i=>{i===".."?n.length>1&&n.pop():i!=="."&&n.push(i)}),n.length>1?n.join("/"):"/"}function Fa(t,e,n,r){return"Cannot include a '"+t+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function jS(t){return t.filter((e,n)=>n===0||e.route.path&&e.route.path.length>0)}function dv(t,e){let n=jS(t);return e?n.map((r,i)=>i===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function hv(t,e,n,r){r===void 0&&(r=!1);let i;typeof t=="string"?i=gi(t):(i=ys({},t),ke(!i.pathname||!i.pathname.includes("?"),Fa("?","pathname","search",i)),ke(!i.pathname||!i.pathname.includes("#"),Fa("#","pathname","hash",i)),ke(!i.search||!i.search.includes("#"),Fa("#","search","hash",i)));let s=t===""||i.pathname==="",o=s?"/":i.pathname,l;if(o==null)l=n;else{let d=e.length-1;if(!r&&o.startsWith("..")){let f=o.split("/");for(;f[0]==="..";)f.shift(),d-=1;i.pathname=f.join("/")}l=d>=0?e[d]:"/"}let a=MS(i,l),u=o&&o!=="/"&&o.endsWith("/"),h=(s||o===".")&&n.endsWith("/");return!a.pathname.endsWith("/")&&(u||h)&&(a.pathname+="/"),a}const fv=t=>t.replace(/\/\/+/g,"/"),lr=t=>fv(t.join("/")),FS=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),US=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,zS=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function BS(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const pv=["post","put","patch","delete"];new Set(pv);const WS=["get",...pv];new Set(WS);/** + * React Router v6.30.4 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function _s(){return _s=Object.assign?Object.assign.bind():function(t){for(var e=1;e{l.current=!0}),C.useCallback(function(u,h){if(h===void 0&&(h={}),!l.current)return;if(typeof u=="number"){r.go(u);return}let d=hv(u,JSON.parse(o),s,h.relative==="path");t==null&&e!=="/"&&(d.pathname=d.pathname==="/"?e:lr([e,d.pathname])),(h.replace?r.replace:r.push)(d,h.state,h)},[e,r,o,s,t])}function HS(){let{matches:t}=C.useContext(Qn),e=t[t.length-1];return e?e.params:{}}function GS(t,e){return qS(t,e)}function qS(t,e,n,r){Fs()||ke(!1);let{navigator:i}=C.useContext(js),{matches:s}=C.useContext(Qn),o=s[s.length-1],l=o?o.params:{};o&&o.pathname;let a=o?o.pathnameBase:"/";o&&o.route;let u=vd(),h;if(e){var d;let E=typeof e=="string"?gi(e):e;a==="/"||(d=E.pathname)!=null&&d.startsWith(a)||ke(!1),h=E}else h=u;let f=h.pathname||"/",v=f;if(a!=="/"){let E=a.replace(/^\//,"").split("/");v="/"+f.replace(/^\//,"").split("/").slice(E.length).join("/")}let w=_S(t,{pathname:v}),_=XS(w&&w.map(E=>Object.assign({},E,{params:Object.assign({},l,E.params),pathname:lr([a,i.encodeLocation?i.encodeLocation(E.pathname).pathname:E.pathname]),pathnameBase:E.pathnameBase==="/"?a:lr([a,i.encodeLocation?i.encodeLocation(E.pathnameBase).pathname:E.pathnameBase])})),s,n,r);return e&&_?C.createElement(Gl.Provider,{value:{location:_s({pathname:"/",search:"",hash:"",state:null,key:"default"},h),navigationType:xn.Pop}},_):_}function KS(){let t=nC(),e=BS(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return C.createElement(C.Fragment,null,C.createElement("h2",null,"Unexpected Application Error!"),C.createElement("h3",{style:{fontStyle:"italic"}},e),n?C.createElement("pre",{style:i},n):null,null)}const QS=C.createElement(KS,null);class YS extends C.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,n){return n.location!==e.location||n.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:n.error,location:n.location,revalidation:e.revalidation||n.revalidation}}componentDidCatch(e,n){console.error("React Router caught the following error during render",e,n)}render(){return this.state.error!==void 0?C.createElement(Qn.Provider,{value:this.props.routeContext},C.createElement(mv.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function JS(t){let{routeContext:e,match:n,children:r}=t,i=C.useContext(gd);return i&&i.static&&i.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=n.route.id),C.createElement(Qn.Provider,{value:e},r)}function XS(t,e,n,r){var i;if(e===void 0&&(e=[]),n===void 0&&(n=null),r===void 0&&(r=null),t==null){var s;if(!n)return null;if(n.errors)t=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&e.length===0&&!n.initialized&&n.matches.length>0)t=n.matches;else return null}let o=t,l=(i=n)==null?void 0:i.errors;if(l!=null){let h=o.findIndex(d=>d.route.id&&(l==null?void 0:l[d.route.id])!==void 0);h>=0||ke(!1),o=o.slice(0,Math.min(o.length,h+1))}let a=!1,u=-1;if(n&&r&&r.v7_partialHydration)for(let h=0;h=0?o=o.slice(0,u+1):o=[o[0]];break}}}return o.reduceRight((h,d,f)=>{let v,w=!1,_=null,E=null;n&&(v=l&&d.route.id?l[d.route.id]:void 0,_=d.route.errorElement||QS,a&&(u<0&&f===0?(iC("route-fallback"),w=!0,E=null):u===f&&(w=!0,E=d.route.hydrateFallbackElement||null)));let g=e.concat(o.slice(0,f+1)),p=()=>{let m;return v?m=_:w?m=E:d.route.Component?m=C.createElement(d.route.Component,null):d.route.element?m=d.route.element:m=h,C.createElement(JS,{match:d,routeContext:{outlet:h,matches:g,isDataRoute:n!=null},children:m})};return n&&(d.route.ErrorBoundary||d.route.errorElement||f===0)?C.createElement(YS,{location:n.location,revalidation:n.revalidation,component:_,error:v,children:p(),routeContext:{outlet:null,matches:g,isDataRoute:!0}}):p()},null)}var vv=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(vv||{}),yv=function(t){return t.UseBlocker="useBlocker",t.UseLoaderData="useLoaderData",t.UseActionData="useActionData",t.UseRouteError="useRouteError",t.UseNavigation="useNavigation",t.UseRouteLoaderData="useRouteLoaderData",t.UseMatches="useMatches",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t.UseRouteId="useRouteId",t}(yv||{});function ZS(t){let e=C.useContext(gd);return e||ke(!1),e}function eC(t){let e=C.useContext($S);return e||ke(!1),e}function tC(t){let e=C.useContext(Qn);return e||ke(!1),e}function _v(t){let e=tC(),n=e.matches[e.matches.length-1];return n.route.id||ke(!1),n.route.id}function nC(){var t;let e=C.useContext(mv),n=eC(),r=_v();return e!==void 0?e:(t=n.errors)==null?void 0:t[r]}function rC(){let{router:t}=ZS(vv.UseNavigateStable),e=_v(yv.UseNavigateStable),n=C.useRef(!1);return gv(()=>{n.current=!0}),C.useCallback(function(i,s){s===void 0&&(s={}),n.current&&(typeof i=="number"?t.navigate(i):t.navigate(i,_s({fromRouteId:e},s)))},[t,e])}const Tf={};function iC(t,e,n){Tf[t]||(Tf[t]=!0)}function sC(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function oC(t){let{to:e,replace:n,state:r,relative:i}=t;Fs()||ke(!1);let{future:s,static:o}=C.useContext(js),{matches:l}=C.useContext(Qn),{pathname:a}=vd(),u=Sr(),h=hv(e,dv(l,s.v7_relativeSplatPath),a,i==="path"),d=JSON.stringify(h);return C.useEffect(()=>u(JSON.parse(d),{replace:n,state:r,relative:i}),[u,d,i,n,r]),null}function fn(t){ke(!1)}function lC(t){let{basename:e="/",children:n=null,location:r,navigationType:i=xn.Pop,navigator:s,static:o=!1,future:l}=t;Fs()&&ke(!1);let a=e.replace(/^\/*/,"/"),u=C.useMemo(()=>({basename:a,navigator:s,static:o,future:_s({v7_relativeSplatPath:!1},l)}),[a,l,s,o]);typeof r=="string"&&(r=gi(r));let{pathname:h="/",search:d="",hash:f="",state:v=null,key:w="default"}=r,_=C.useMemo(()=>{let E=cv(h,a);return E==null?null:{location:{pathname:E,search:d,hash:f,state:v,key:w},navigationType:i}},[a,h,d,f,v,w,i]);return _==null?null:C.createElement(js.Provider,{value:u},C.createElement(Gl.Provider,{children:n,value:_}))}function aC(t){let{children:e,location:n}=t;return GS(qu(e),n)}new Promise(()=>{});function qu(t,e){e===void 0&&(e=[]);let n=[];return C.Children.forEach(t,(r,i)=>{if(!C.isValidElement(r))return;let s=[...e,i];if(r.type===C.Fragment){n.push.apply(n,qu(r.props.children,s));return}r.type!==fn&&ke(!1),!r.props.index||!r.props.children||ke(!1);let o={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(o.children=qu(r.props.children,s)),n.push(o)}),n}/** + * React Router DOM v6.30.4 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */const uC="6";try{window.__reactRouterVersion=uC}catch{}const cC="startTransition",bf=i0[cC];function dC(t){let{basename:e,children:n,future:r,window:i}=t,s=C.useRef();s.current==null&&(s.current=gS({window:i,v5Compat:!0}));let o=s.current,[l,a]=C.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},h=C.useCallback(d=>{u&&bf?bf(()=>a(d)):a(d)},[a,u]);return C.useLayoutEffect(()=>o.listen(h),[o,h]),C.useEffect(()=>sC(r),[r]),C.createElement(lC,{basename:e,children:n,location:l.location,navigationType:l.action,navigator:o,future:r})}var Pf;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(Pf||(Pf={}));var Nf;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(Nf||(Nf={}));const hC="prof123";function fC(){const t=Sr(),[e,n]=C.useState(!1),[r,i]=C.useState(""),[s,o]=C.useState("");function l(a){a.preventDefault(),r===hC?(localStorage.setItem("role","instructor"),t("/instructor")):(o("Incorrect password."),i(""))}return c.jsxs("div",{style:Se.page,children:[c.jsxs("div",{style:Se.header,children:[c.jsx("div",{style:Se.logoMark,children:"●"}),c.jsx("span",{style:Se.logoText,children:"ClassPoll"})]}),c.jsxs("div",{style:Se.hero,className:"fade-up",children:[c.jsxs("h1",{style:Se.title,children:["Live Classroom",c.jsx("br",{}),"Polling"]}),c.jsx("p",{style:Se.sub,children:"Real-time polls, instant results, zero setup for students."})]}),c.jsxs("div",{style:Se.cards,className:"fade-up",children:[c.jsxs("button",{style:Se.roleCard,onClick:()=>t("/student"),children:[c.jsx("span",{style:Se.roleIcon,children:"πŸŽ“"}),c.jsx("span",{style:Se.roleLabel,children:"I'm a Student"}),c.jsx("span",{style:Se.roleHint,children:"Join and answer polls"})]}),e?c.jsxs("form",{style:{...Se.roleCard,gap:"0.75rem"},onSubmit:l,children:[c.jsx("span",{style:Se.roleIcon,children:"πŸ”‘"}),c.jsx("span",{style:Se.roleLabel,children:"Instructor Password"}),c.jsx("input",{className:"input",type:"password",placeholder:"Enter password",value:r,onChange:a=>{i(a.target.value),o("")},autoFocus:!0,style:{textAlign:"center"}}),s&&c.jsx("span",{style:Se.err,children:s}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{width:"100%",justifyContent:"center"},children:"Enter"}),c.jsx("button",{type:"button",className:"btn btn-secondary",style:{width:"100%",justifyContent:"center",fontSize:"0.85rem"},onClick:()=>{n(!1),o(""),i("")},children:"Cancel"})]}):c.jsxs("button",{style:Se.roleCard,onClick:()=>n(!0),children:[c.jsx("span",{style:Se.roleIcon,children:"πŸ“‹"}),c.jsx("span",{style:Se.roleLabel,children:"I'm the Instructor"}),c.jsx("span",{style:Se.roleHint,children:"Create and manage polls"})]})]}),c.jsx("a",{href:"/classroom-polling/history",style:Se.historyLink,children:"View Poll History β†’"})]})}const Se={page:{minHeight:"100vh",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"2rem 1rem",gap:"2rem",background:"var(--paper)"},header:{position:"fixed",top:0,left:0,right:0,padding:"1rem 2rem",display:"flex",alignItems:"center",gap:"0.5rem",borderBottom:"1px solid var(--border)",background:"var(--paper)"},logoMark:{color:"var(--accent)",fontSize:"1.2rem"},logoText:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem"},hero:{textAlign:"center"},title:{fontSize:"clamp(2.2rem, 6vw, 3.5rem)",lineHeight:1.1,marginBottom:"0.75rem"},sub:{color:"var(--muted)",fontSize:"1.05rem",maxWidth:"30ch",margin:"0 auto"},cards:{display:"flex",gap:"1.25rem",flexWrap:"wrap",justifyContent:"center"},roleCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:"0.5rem",padding:"2rem 2.5rem",borderRadius:"16px",border:"2px solid var(--border)",cursor:"pointer",transition:"all 0.2s",background:"white",minWidth:"200px",boxShadow:"var(--shadow)"},roleIcon:{fontSize:"2.5rem"},roleLabel:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.15rem"},roleHint:{fontSize:"0.82rem",color:"var(--muted)"},err:{color:"var(--accent)",fontSize:"0.85rem"},historyLink:{color:"var(--muted)",fontSize:"0.85rem",textDecoration:"underline",cursor:"pointer"}},pC="modulepreload",mC=function(t){return"/classroom-polling/"+t},Rf={},gC=function(e,n,r){let i=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.allSettled(n.map(a=>{if(a=mC(a),a in Rf)return;Rf[a]=!0;const u=a.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${a}"]${h}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":pC,u||(d.as="script"),d.crossOrigin="",d.href=a,l&&d.setAttribute("nonce",l),document.head.appendChild(d),u)return new Promise((f,v)=>{d.addEventListener("load",f),d.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${a}`)))})}))}function s(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&s(l.reason);return e().catch(s)})};var Af={};/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const wv={NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const N=function(t,e){if(!t)throw vi(e)},vi=function(t){return new Error("Firebase Database ("+wv.SDK_VERSION+") INTERNAL ASSERT FAILED: "+t)};/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Sv=function(t){const e=[];let n=0;for(let r=0;r>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e},vC=function(t){const e=[];let n=0,r=0;for(;n191&&i<224){const s=t[n++];e[r++]=String.fromCharCode((i&31)<<6|s&63)}else if(i>239&&i<365){const s=t[n++],o=t[n++],l=t[n++],a=((i&7)<<18|(s&63)<<12|(o&63)<<6|l&63)-65536;e[r++]=String.fromCharCode(55296+(a>>10)),e[r++]=String.fromCharCode(56320+(a&1023))}else{const s=t[n++],o=t[n++];e[r++]=String.fromCharCode((i&15)<<12|(s&63)<<6|o&63)}}return e.join("")},yd={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:typeof atob=="function",encodeByteArray(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let i=0;i>2,d=(s&3)<<4|l>>4;let f=(l&15)<<2|u>>6,v=u&63;a||(v=64,o||(f=64)),r.push(n[h],n[d],n[f],n[v])}return r.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(Sv(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):vC(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();const n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let i=0;i>4;if(r.push(f),u!==64){const v=l<<4&240|u>>2;if(r.push(v),d!==64){const w=u<<6&192|d;r.push(w)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}};class yC extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const Cv=function(t){const e=Sv(t);return yd.encodeByteArray(e,!0)},ol=function(t){return Cv(t).replace(/\./g,"")},ll=function(t){try{return yd.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function _C(t){return Ev(void 0,t)}function Ev(t,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:const n=e;return new Date(n.getTime());case Object:t===void 0&&(t={});break;case Array:t=[];break;default:return e}for(const n in e)!e.hasOwnProperty(n)||!wC(n)||(t[n]=Ev(t[n],e[n]));return t}function wC(t){return t!=="__proto__"}/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function SC(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const CC=()=>SC().__FIREBASE_DEFAULTS__,EC=()=>{if(typeof process>"u"||typeof Af>"u")return;const t=Af.__FIREBASE_DEFAULTS__;if(t)return JSON.parse(t)},xC=()=>{if(typeof document>"u")return;let t;try{t=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const e=t&&ll(t[1]);return e&&JSON.parse(e)},_d=()=>{try{return CC()||EC()||xC()}catch(t){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${t}`);return}},xv=t=>{var e,n;return(n=(e=_d())===null||e===void 0?void 0:e.emulatorHosts)===null||n===void 0?void 0:n[t]},IC=t=>{const e=xv(t);if(!e)return;const n=e.lastIndexOf(":");if(n<=0||n+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);const r=parseInt(e.substring(n+1),10);return e[0]==="["?[e.substring(1,n-1),r]:[e.substring(0,n),r]},Iv=()=>{var t;return(t=_d())===null||t===void 0?void 0:t.config},kv=t=>{var e;return(e=_d())===null||e===void 0?void 0:e[`_${t}`]};/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Us{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,n)=>{this.resolve=e,this.reject=n})}wrapCallback(e){return(n,r)=>{n?this.reject(n):this.resolve(r),typeof e=="function"&&(this.promise.catch(()=>{}),e.length===1?e(n):e(n,r))}}}/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function kC(t,e){if(t.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n={alg:"none",type:"JWT"},r=e||"demo-project",i=t.iat||0,s=t.sub||t.user_id;if(!s)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const o=Object.assign({iss:`https://securetoken.google.com/${r}`,aud:r,iat:i,exp:i+3600,auth_time:i,sub:s,user_id:s,firebase:{sign_in_provider:"custom",identities:{}}},t);return[ol(JSON.stringify(n)),ol(JSON.stringify(o)),""].join(".")}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function Je(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function wd(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(Je())}function TC(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function bC(){const t=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof t=="object"&&t.id!==void 0}function Tv(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function PC(){const t=Je();return t.indexOf("MSIE ")>=0||t.indexOf("Trident/")>=0}function NC(){return wv.NODE_ADMIN===!0}function RC(){try{return typeof indexedDB=="object"}catch{return!1}}function AC(){return new Promise((t,e)=>{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),t(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var s;e(((s=i.error)===null||s===void 0?void 0:s.message)||"")}}catch(n){e(n)}})}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const OC="FirebaseError";class Yn extends Error{constructor(e,n,r){super(n),this.code=e,this.customData=r,this.name=OC,Object.setPrototypeOf(this,Yn.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,zs.prototype.create)}}class zs{constructor(e,n,r){this.service=e,this.serviceName=n,this.errors=r}create(e,...n){const r=n[0]||{},i=`${this.service}/${e}`,s=this.errors[e],o=s?DC(s,r):"Error",l=`${this.serviceName}: ${o} (${i}).`;return new Yn(i,l,r)}}function DC(t,e){return t.replace(LC,(n,r)=>{const i=e[r];return i!=null?String(i):`<${r}?>`})}const LC=/\{\$([^}]+)}/g;/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function ws(t){return JSON.parse(t)}function Ne(t){return JSON.stringify(t)}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const bv=function(t){let e={},n={},r={},i="";try{const s=t.split(".");e=ws(ll(s[0])||""),n=ws(ll(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch{}return{header:e,claims:n,data:r,signature:i}},MC=function(t){const e=bv(t),n=e.claims;return!!n&&typeof n=="object"&&n.hasOwnProperty("iat")},jC=function(t){const e=bv(t).claims;return typeof e=="object"&&e.admin===!0};/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function Bt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function oi(t,e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]}function Ku(t){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function al(t,e,n){const r={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[i]=e.call(n,t[i],i,t));return r}function ul(t,e){if(t===e)return!0;const n=Object.keys(t),r=Object.keys(e);for(const i of n){if(!r.includes(i))return!1;const s=t[i],o=e[i];if(Of(s)&&Of(o)){if(!ul(s,o))return!1}else if(s!==o)return!1}for(const i of r)if(!n.includes(i))return!1;return!0}function Of(t){return t!==null&&typeof t=="object"}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function yi(t){const e=[];for(const[n,r]of Object.entries(t))Array.isArray(r)?r.forEach(i=>{e.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}):e.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return e.length?"&"+e.join("&"):""}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class FC{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=512/8,this.pad_[0]=128;for(let e=1;e>>31)&4294967295}let i=this.chain_[0],s=this.chain_[1],o=this.chain_[2],l=this.chain_[3],a=this.chain_[4],u,h;for(let d=0;d<80;d++){d<40?d<20?(u=l^s&(o^l),h=1518500249):(u=s^o^l,h=1859775393):d<60?(u=s&o|l&(s|o),h=2400959708):(u=s^o^l,h=3395469782);const f=(i<<5|i>>>27)+u+a+h+r[d]&4294967295;a=l,l=o,o=(s<<30|s>>>2)&4294967295,s=i,i=f}this.chain_[0]=this.chain_[0]+i&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+l&4294967295,this.chain_[4]=this.chain_[4]+a&4294967295}update(e,n){if(e==null)return;n===void 0&&(n=e.length);const r=n-this.blockSize;let i=0;const s=this.buf_;let o=this.inbuf_;for(;i=56;i--)this.buf_[i]=n&255,n/=256;this.compress_(this.buf_);let r=0;for(let i=0;i<5;i++)for(let s=24;s>=0;s-=8)e[r]=this.chain_[i]>>s&255,++r;return e}}function UC(t,e){const n=new zC(t,e);return n.subscribe.bind(n)}class zC{constructor(e,n){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=n,this.task.then(()=>{e(this)}).catch(r=>{this.error(r)})}next(e){this.forEachObserver(n=>{n.next(e)})}error(e){this.forEachObserver(n=>{n.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,n,r){let i;if(e===void 0&&n===void 0&&r===void 0)throw new Error("Missing Observer.");BC(e,["next","error","complete"])?i=e:i={next:e,error:n,complete:r},i.next===void 0&&(i.next=Ua),i.error===void 0&&(i.error=Ua),i.complete===void 0&&(i.complete=Ua);const s=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch{}}),this.observers.push(i),s}unsubscribeOne(e){this.observers===void 0||this.observers[e]===void 0||(delete this.observers[e],this.observerCount-=1,this.observerCount===0&&this.onNoObservers!==void 0&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let n=0;n{if(this.observers!==void 0&&this.observers[e]!==void 0)try{n(this.observers[e])}catch(r){typeof console<"u"&&console.error&&console.error(r)}})}close(e){this.finalized||(this.finalized=!0,e!==void 0&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function BC(t,e){if(typeof t!="object"||t===null)return!1;for(const n of e)if(n in t&&typeof t[n]=="function")return!0;return!1}function Ua(){}function ql(t,e){return`${t} failed: ${e} argument `}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const WC=function(t){const e=[];let n=0;for(let r=0;r=55296&&i<=56319){const s=i-55296;r++,N(r>6|192,e[n++]=i&63|128):i<65536?(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e},Kl=function(t){let e=0;for(let n=0;n=55296&&r<=56319?(e+=4,n++):e+=3}return e};/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function Et(t){return t&&t._delegate?t._delegate:t}class fr{constructor(e,n,r){this.name=e,this.instanceFactory=n,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}}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Zn="[DEFAULT]";/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class $C{constructor(e,n){this.name=e,this.container=n,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const n=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(n)){const r=new Us;if(this.instancesDeferred.set(n,r),this.isInitialized(n)||this.shouldAutoInitialize())try{const i=this.getOrInitializeService({instanceIdentifier:n});i&&r.resolve(i)}catch{}}return this.instancesDeferred.get(n).promise}getImmediate(e){var n;const r=this.normalizeInstanceIdentifier(e==null?void 0:e.identifier),i=(n=e==null?void 0:e.optional)!==null&&n!==void 0?n:!1;if(this.isInitialized(r)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:r})}catch(s){if(i)return null;throw s}else{if(i)return null;throw Error(`Service ${this.name} is not available`)}}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(HC(e))try{this.getOrInitializeService({instanceIdentifier:Zn})}catch{}for(const[n,r]of this.instancesDeferred.entries()){const i=this.normalizeInstanceIdentifier(n);try{const s=this.getOrInitializeService({instanceIdentifier:i});r.resolve(s)}catch{}}}}clearInstance(e=Zn){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(n=>"INTERNAL"in n).map(n=>n.INTERNAL.delete()),...e.filter(n=>"_delete"in n).map(n=>n._delete())])}isComponentSet(){return this.component!=null}isInitialized(e=Zn){return this.instances.has(e)}getOptions(e=Zn){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:n={}}=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`);const i=this.getOrInitializeService({instanceIdentifier:r,options:n});for(const[s,o]of this.instancesDeferred.entries()){const l=this.normalizeInstanceIdentifier(s);r===l&&o.resolve(i)}return i}onInit(e,n){var r;const i=this.normalizeInstanceIdentifier(n),s=(r=this.onInitCallbacks.get(i))!==null&&r!==void 0?r:new Set;s.add(e),this.onInitCallbacks.set(i,s);const o=this.instances.get(i);return o&&e(o,i),()=>{s.delete(e)}}invokeOnInitCallbacks(e,n){const r=this.onInitCallbacks.get(n);if(r)for(const i of r)try{i(e,n)}catch{}}getOrInitializeService({instanceIdentifier:e,options:n={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:VC(e),options:n}),this.instances.set(e,r),this.instancesOptions.set(e,n),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r)}catch{}return r||null}normalizeInstanceIdentifier(e=Zn){return this.component?this.component.multipleInstances?e:Zn:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function VC(t){return t===Zn?void 0:t}function HC(t){return t.instantiationMode==="EAGER"}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class GC{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const n=this.getProvider(e.name);if(n.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);n.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 n=new $C(e,this);return this.providers.set(e,n),n}getProviders(){return Array.from(this.providers.values())}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */var oe;(function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"})(oe||(oe={}));const qC={debug:oe.DEBUG,verbose:oe.VERBOSE,info:oe.INFO,warn:oe.WARN,error:oe.ERROR,silent:oe.SILENT},KC=oe.INFO,QC={[oe.DEBUG]:"log",[oe.VERBOSE]:"log",[oe.INFO]:"info",[oe.WARN]:"warn",[oe.ERROR]:"error"},YC=(t,e,...n)=>{if(ee.some(n=>t instanceof n);let Df,Lf;function XC(){return Df||(Df=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ZC(){return Lf||(Lf=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Pv=new WeakMap,Qu=new WeakMap,Nv=new WeakMap,za=new WeakMap,Cd=new WeakMap;function eE(t){const e=new Promise((n,r)=>{const i=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o)},s=()=>{n(Dn(t.result)),i()},o=()=>{r(t.error),i()};t.addEventListener("success",s),t.addEventListener("error",o)});return e.then(n=>{n instanceof IDBCursor&&Pv.set(n,t)}).catch(()=>{}),Cd.set(e,t),e}function tE(t){if(Qu.has(t))return;const e=new Promise((n,r)=>{const i=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",o),t.removeEventListener("abort",o)},s=()=>{n(),i()},o=()=>{r(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",s),t.addEventListener("error",o),t.addEventListener("abort",o)});Qu.set(t,e)}let Yu={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return Qu.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Nv.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Dn(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function nE(t){Yu=t(Yu)}function rE(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){const r=t.call(Ba(this),e,...n);return Nv.set(r,e.sort?e.sort():[e]),Dn(r)}:ZC().includes(t)?function(...e){return t.apply(Ba(this),e),Dn(Pv.get(this))}:function(...e){return Dn(t.apply(Ba(this),e))}}function iE(t){return typeof t=="function"?rE(t):(t instanceof IDBTransaction&&tE(t),JC(t,XC())?new Proxy(t,Yu):t)}function Dn(t){if(t instanceof IDBRequest)return eE(t);if(za.has(t))return za.get(t);const e=iE(t);return e!==t&&(za.set(t,e),Cd.set(e,t)),e}const Ba=t=>Cd.get(t);function sE(t,e,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const o=indexedDB.open(t,e),l=Dn(o);return r&&o.addEventListener("upgradeneeded",a=>{r(Dn(o.result),a.oldVersion,a.newVersion,Dn(o.transaction),a)}),n&&o.addEventListener("blocked",a=>n(a.oldVersion,a.newVersion,a)),l.then(a=>{s&&a.addEventListener("close",()=>s()),i&&a.addEventListener("versionchange",u=>i(u.oldVersion,u.newVersion,u))}).catch(()=>{}),l}const oE=["get","getKey","getAll","getAllKeys","count"],lE=["put","add","delete","clear"],Wa=new Map;function Mf(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(Wa.get(e))return Wa.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,i=lE.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||oE.includes(n)))return;const s=async function(o,...l){const a=this.transaction(o,i?"readwrite":"readonly");let u=a.store;return r&&(u=u.index(l.shift())),(await Promise.all([u[n](...l),i&&a.done]))[0]};return Wa.set(e,s),s}nE(t=>({...t,get:(e,n,r)=>Mf(e,n)||t.get(e,n,r),has:(e,n)=>!!Mf(e,n)||t.has(e,n)}));/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class aE{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(n=>{if(uE(n)){const r=n.getImmediate();return`${r.library}/${r.version}`}else return null}).filter(n=>n).join(" ")}}function uE(t){const e=t.getComponent();return(e==null?void 0:e.type)==="VERSION"}const Ju="@firebase/app",jf="0.10.13";/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const rn=new Sd("@firebase/app"),cE="@firebase/app-compat",dE="@firebase/analytics-compat",hE="@firebase/analytics",fE="@firebase/app-check-compat",pE="@firebase/app-check",mE="@firebase/auth",gE="@firebase/auth-compat",vE="@firebase/database",yE="@firebase/data-connect",_E="@firebase/database-compat",wE="@firebase/functions",SE="@firebase/functions-compat",CE="@firebase/installations",EE="@firebase/installations-compat",xE="@firebase/messaging",IE="@firebase/messaging-compat",kE="@firebase/performance",TE="@firebase/performance-compat",bE="@firebase/remote-config",PE="@firebase/remote-config-compat",NE="@firebase/storage",RE="@firebase/storage-compat",AE="@firebase/firestore",OE="@firebase/vertexai-preview",DE="@firebase/firestore-compat",LE="firebase",ME="10.14.1";/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Xu="[DEFAULT]",jE={[Ju]:"fire-core",[cE]:"fire-core-compat",[hE]:"fire-analytics",[dE]:"fire-analytics-compat",[pE]:"fire-app-check",[fE]:"fire-app-check-compat",[mE]:"fire-auth",[gE]:"fire-auth-compat",[vE]:"fire-rtdb",[yE]:"fire-data-connect",[_E]:"fire-rtdb-compat",[wE]:"fire-fn",[SE]:"fire-fn-compat",[CE]:"fire-iid",[EE]:"fire-iid-compat",[xE]:"fire-fcm",[IE]:"fire-fcm-compat",[kE]:"fire-perf",[TE]:"fire-perf-compat",[bE]:"fire-rc",[PE]:"fire-rc-compat",[NE]:"fire-gcs",[RE]:"fire-gcs-compat",[AE]:"fire-fst",[DE]:"fire-fst-compat",[OE]:"fire-vertex","fire-js":"fire-js",[LE]:"fire-js-all"};/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const cl=new Map,FE=new Map,Zu=new Map;function Ff(t,e){try{t.container.addComponent(e)}catch(n){rn.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n)}}function li(t){const e=t.name;if(Zu.has(e))return rn.debug(`There were multiple attempts to register component ${e}.`),!1;Zu.set(e,t);for(const n of cl.values())Ff(n,t);for(const n of FE.values())Ff(n,t);return!0}function Ed(t,e){const n=t.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),t.container.getProvider(e)}function Gt(t){return t.settings!==void 0}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const UE={"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."},Ln=new zs("app","Firebase",UE);/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class zE{constructor(e,n,r){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},n),this._name=n.name,this._automaticDataCollectionEnabled=n.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new fr("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 Ln.create("app-deleted",{appName:this._name})}}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const _i=ME;function Rv(t,e={}){let n=t;typeof e!="object"&&(e={name:e});const r=Object.assign({name:Xu,automaticDataCollectionEnabled:!1},e),i=r.name;if(typeof i!="string"||!i)throw Ln.create("bad-app-name",{appName:String(i)});if(n||(n=Iv()),!n)throw Ln.create("no-options");const s=cl.get(i);if(s){if(ul(n,s.options)&&ul(r,s.config))return s;throw Ln.create("duplicate-app",{appName:i})}const o=new GC(i);for(const a of Zu.values())o.addComponent(a);const l=new zE(n,r,o);return cl.set(i,l),l}function Av(t=Xu){const e=cl.get(t);if(!e&&t===Xu&&Iv())return Rv();if(!e)throw Ln.create("no-app",{appName:t});return e}function Mn(t,e,n){var r;let i=(r=jE[t])!==null&&r!==void 0?r:t;n&&(i+=`-${n}`);const s=i.match(/\s|\//),o=e.match(/\s|\//);if(s||o){const l=[`Unable to register library "${i}" with version "${e}":`];s&&l.push(`library name "${i}" contains illegal characters (whitespace or "/")`),s&&o&&l.push("and"),o&&l.push(`version name "${e}" contains illegal characters (whitespace or "/")`),rn.warn(l.join(" "));return}li(new fr(`${i}-version`,()=>({library:i,version:e}),"VERSION"))}/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const BE="firebase-heartbeat-database",WE=1,Ss="firebase-heartbeat-store";let $a=null;function Ov(){return $a||($a=sE(BE,WE,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(Ss)}catch(n){console.warn(n)}}}}).catch(t=>{throw Ln.create("idb-open",{originalErrorMessage:t.message})})),$a}async function $E(t){try{const n=(await Ov()).transaction(Ss),r=await n.objectStore(Ss).get(Dv(t));return await n.done,r}catch(e){if(e instanceof Yn)rn.warn(e.message);else{const n=Ln.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});rn.warn(n.message)}}}async function Uf(t,e){try{const r=(await Ov()).transaction(Ss,"readwrite");await r.objectStore(Ss).put(e,Dv(t)),await r.done}catch(n){if(n instanceof Yn)rn.warn(n.message);else{const r=Ln.create("idb-set",{originalErrorMessage:n==null?void 0:n.message});rn.warn(r.message)}}}function Dv(t){return`${t.name}!${t.options.appId}`}/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const VE=1024,HE=30*24*60*60*1e3;class GE{constructor(e){this.container=e,this._heartbeatsCache=null;const n=this.container.getProvider("app").getImmediate();this._storage=new KE(n),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r))}async triggerHeartbeat(){var e,n;try{const i=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),s=zf();return((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,((n=this._heartbeatsCache)===null||n===void 0?void 0:n.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===s||this._heartbeatsCache.heartbeats.some(o=>o.date===s)?void 0:(this._heartbeatsCache.heartbeats.push({date:s,agent:i}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(o=>{const l=new Date(o.date).valueOf();return Date.now()-l<=HE}),this._storage.overwrite(this._heartbeatsCache))}catch(r){rn.warn(r)}}async getHeartbeatsHeader(){var e;try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null||this._heartbeatsCache.heartbeats.length===0)return"";const n=zf(),{heartbeatsToSend:r,unsentEntries:i}=qE(this._heartbeatsCache.heartbeats),s=ol(JSON.stringify({version:2,heartbeats:r}));return this._heartbeatsCache.lastSentHeartbeatDate=n,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),s}catch(n){return rn.warn(n),""}}}function zf(){return new Date().toISOString().substring(0,10)}function qE(t,e=VE){const n=[];let r=t.slice();for(const i of t){const s=n.find(o=>o.agent===i.agent);if(s){if(s.dates.push(i.date),Bf(n)>e){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),Bf(n)>e){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}class KE{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return RC()?AC().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const n=await $E(this.app);return n!=null&&n.heartbeats?n:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){var n;if(await this._canUseIndexedDBPromise){const i=await this.read();return Uf(this.app,{lastSentHeartbeatDate:(n=e.lastSentHeartbeatDate)!==null&&n!==void 0?n:i.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){var n;if(await this._canUseIndexedDBPromise){const i=await this.read();return Uf(this.app,{lastSentHeartbeatDate:(n=e.lastSentHeartbeatDate)!==null&&n!==void 0?n:i.lastSentHeartbeatDate,heartbeats:[...i.heartbeats,...e.heartbeats]})}else return}}function Bf(t){return ol(JSON.stringify({version:2,heartbeats:t})).length}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function QE(t){li(new fr("platform-logger",e=>new aE(e),"PRIVATE")),li(new fr("heartbeat",e=>new GE(e),"PRIVATE")),Mn(Ju,jf,t),Mn(Ju,jf,"esm2017"),Mn("fire-js","")}QE("");var YE="firebase",JE="10.14.1";/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */Mn(YE,JE,"app");var Wf={};const $f="@firebase/database",Vf="1.0.8";/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */let Lv="";function XE(t){Lv=t}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class ZE{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,n){n==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),Ne(n))}get(e){const n=this.domStorage_.getItem(this.prefixedName_(e));return n==null?null:ws(n)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class ex{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,n){n==null?delete this.cache_[e]:this.cache_[e]=n}get(e){return Bt(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Mv=function(t){try{if(typeof window<"u"&&typeof window[t]<"u"){const e=window[t];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new ZE(e)}}catch{}return new ex},ir=Mv("localStorage"),tx=Mv("sessionStorage");/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Kr=new Sd("@firebase/database"),nx=function(){let t=1;return function(){return t++}}(),jv=function(t){const e=WC(t),n=new FC;n.update(e);const r=n.digest();return yd.encodeByteArray(r)},Bs=function(...t){let e="";for(let n=0;n{document.readyState==="complete"&&n()}),window.attachEvent("onload",n))}},ai="[MIN_NAME]",pr="[MAX_NAME]",Cr=function(t,e){if(t===e)return 0;if(t===ai||e===pr)return-1;if(e===ai||t===pr)return 1;{const n=Gf(t),r=Gf(e);return n!==null?r!==null?n-r===0?t.length-e.length:n-r:-1:r!==null?1:tn?r.push(t.substring(i,n)):r.push(t.substring(i,i+e));return r};function ze(t,e){for(const n in t)t.hasOwnProperty(n)&&e(n,t[n])}const Uv=function(t){N(!xd(t),"Invalid JSON number");const e=11,n=52,r=(1<=Math.pow(2,1-r)?(l=Math.min(Math.floor(Math.log(t)/Math.LN2),r),s=l+r,o=Math.round(t*Math.pow(2,n-l)-Math.pow(2,n))):(s=0,o=Math.round(t/Math.pow(2,1-r-n))));const u=[];for(a=n;a;a-=1)u.push(o%2?1:0),o=Math.floor(o/2);for(a=e;a;a-=1)u.push(s%2?1:0),s=Math.floor(s/2);u.push(i?1:0),u.reverse();const h=u.join("");let d="";for(a=0;a<64;a+=8){let f=parseInt(h.substr(a,8),2).toString(16);f.length===1&&(f="0"+f),d=d+f}return d.toLowerCase()},lx=function(){return!!(typeof window=="object"&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},ax=function(){return typeof Windows=="object"&&typeof Windows.UI=="object"};function ux(t,e){let n="Unknown Error";t==="too_big"?n="The data requested exceeds the maximum size that can be accessed with a single request.":t==="permission_denied"?n="Client doesn't have permission to access the desired data.":t==="unavailable"&&(n="The service is unavailable");const r=new Error(t+" at "+e._path.toString()+": "+n);return r.code=t.toUpperCase(),r}const cx=new RegExp("^-?(0*)\\d{1,10}$"),dx=-2147483648,hx=2147483647,Gf=function(t){if(cx.test(t)){const e=Number(t);if(e>=dx&&e<=hx)return e}return null},wi=function(t){try{t()}catch(e){setTimeout(()=>{const n=e.stack||"";throw Ye("Exception was thrown by user callback.",n),e},Math.floor(0))}},fx=function(){return(typeof window=="object"&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},Yi=function(t,e){const n=setTimeout(t,e);return typeof n=="number"&&typeof Deno<"u"&&Deno.unrefTimer?Deno.unrefTimer(n):typeof n=="object"&&n.unref&&n.unref(),n};/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class px{constructor(e,n){this.appName_=e,this.appCheckProvider=n,this.appCheck=n==null?void 0:n.getImmediate({optional:!0}),this.appCheck||n==null||n.get().then(r=>this.appCheck=r)}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise((n,r)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(n,r):n(null)},0)})}addTokenChangeListener(e){var n;(n=this.appCheckProvider)===null||n===void 0||n.get().then(r=>r.addTokenListener(e))}notifyForInvalidToken(){Ye(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class mx{constructor(e,n,r){this.appName_=e,this.firebaseOptions_=n,this.authProvider_=r,this.auth_=null,this.auth_=r.getImmediate({optional:!0}),this.auth_||r.onInit(i=>this.auth_=i)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(n=>n&&n.code==="auth/token-not-initialized"?(je("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(n)):new Promise((n,r)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(n,r):n(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(n=>n.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(n=>n.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/.',Ye(e)}}class Po{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Po.OWNER="owner";/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const kd="5",zv="v",Bv="s",Wv="r",$v="f",Vv=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Hv="ls",Gv="p",tc="ac",qv="websocket",Kv="long_polling";/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Qv{constructor(e,n,r,i,s=!1,o="",l=!1,a=!1){this.secure=n,this.namespace=r,this.webSocketOnly=i,this.nodeAdmin=s,this.persistenceKey=o,this.includeNamespaceInQueryParams=l,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ir.get("host:"+e)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)==="s-"}isCustomHost(){return this._domain!=="firebaseio.com"&&this._domain!=="firebaseio-demo.com"}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&ir.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://",n=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${n}`}}function gx(t){return t.host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams}function Yv(t,e,n){N(typeof e=="string","typeof type must == string"),N(typeof n=="object","typeof params must == object");let r;if(e===qv)r=(t.secure?"wss://":"ws://")+t.internalHost+"/.ws?";else if(e===Kv)r=(t.secure?"https://":"http://")+t.internalHost+"/.lp?";else throw new Error("Unknown connection type: "+e);gx(t)&&(n.ns=t.namespace);const i=[];return ze(n,(s,o)=>{i.push(s+"="+o)}),r+i.join("&")}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class vx{constructor(){this.counters_={}}incrementCounter(e,n=1){Bt(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=n}get(){return _C(this.counters_)}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Va={},Ha={};function Td(t){const e=t.toString();return Va[e]||(Va[e]=new vx),Va[e]}function yx(t,e){const n=t.toString();return Ha[n]||(Ha[n]=e()),Ha[n]}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class _x{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,n){this.closeAfterResponse=e,this.onClose=n,this.closeAfterResponse{this.onMessage_(r[i])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const qf="start",wx="close",Sx="pLPCommand",Cx="pRTLPCB",Jv="id",Xv="pw",Zv="ser",Ex="cb",xx="seg",Ix="ts",kx="d",Tx="dframe",ey=1870,ty=30,bx=ey-ty,Px=25e3,Nx=3e4;class zr{constructor(e,n,r,i,s,o,l){this.connId=e,this.repoInfo=n,this.applicationId=r,this.appCheckToken=i,this.authToken=s,this.transportSessionId=o,this.lastSessionId=l,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Ws(e),this.stats_=Td(n),this.urlFn=a=>(this.appCheckToken&&(a[tc]=this.appCheckToken),Yv(n,Kv,a))}open(e,n){this.curSegmentNum=0,this.onDisconnect_=n,this.myPacketOrderer=new _x(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(Nx)),sx(()=>{if(this.isClosed_)return;this.scriptTagHolder=new bd((...s)=>{const[o,l,a,u,h]=s;if(this.incrementIncomingBytes_(s),!!this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,o===qf)this.id=l,this.password=a;else if(o===wx)l?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(l,()=>{this.onClosed_()})):this.onClosed_();else throw new Error("Unrecognized command received: "+o)},(...s)=>{const[o,l]=s;this.incrementIncomingBytes_(s),this.myPacketOrderer.handleResponse(o,l)},()=>{this.onClosed_()},this.urlFn);const r={};r[qf]="t",r[Zv]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(r[Ex]=this.scriptTagHolder.uniqueCallbackIdentifier),r[zv]=kd,this.transportSessionId&&(r[Bv]=this.transportSessionId),this.lastSessionId&&(r[Hv]=this.lastSessionId),this.applicationId&&(r[Gv]=this.applicationId),this.appCheckToken&&(r[tc]=this.appCheckToken),typeof location<"u"&&location.hostname&&Vv.test(location.hostname)&&(r[Wv]=$v);const i=this.urlFn(r);this.log_("Connecting via long-poll to "+i),this.scriptTagHolder.addTag(i,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){zr.forceAllow_=!0}static forceDisallow(){zr.forceDisallow_=!0}static isAvailable(){return zr.forceAllow_?!0:!zr.forceDisallow_&&typeof document<"u"&&document.createElement!=null&&!lx()&&!ax()}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 n=Ne(e);this.bytesSent+=n.length,this.stats_.incrementCounter("bytes_sent",n.length);const r=Cv(n),i=Fv(r,bx);for(let s=0;sdocument.domain="'+document.domain+'";<\/script>');const o=""+s+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(o),this.myIFrame.doc.close()}catch(l){je("frame writing exception"),l.stack&&je(l.stack),je(l)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||je("No IE domain setting required")}catch{const r=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+r+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";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(()=>{this.myIFrame!==null&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,n){for(this.myID=e,this.myPW=n,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[Jv]=this.myID,e[Xv]=this.myPW,e[Zv]=this.currentSerial;let n=this.urlFn(e),r="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+ty+r.length<=ey;){const o=this.pendingSegs.shift();r=r+"&"+xx+i+"="+o.seg+"&"+Ix+i+"="+o.ts+"&"+kx+i+"="+o.d,i++}return n=n+r,this.addLongPollTag_(n,this.currentSerial),!0}else return!1}enqueueSegment(e,n,r){this.pendingSegs.push({seg:e,ts:n,d:r}),this.alive&&this.newRequest_()}addLongPollTag_(e,n){this.outstandingRequests.add(n);const r=()=>{this.outstandingRequests.delete(n),this.newRequest_()},i=setTimeout(r,Math.floor(Px)),s=()=>{clearTimeout(i),r()};this.addTag(e,s)}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const r=this.myIFrame.doc.createElement("script");r.type="text/javascript",r.async=!0,r.src=e,r.onload=r.onreadystatechange=function(){const i=r.readyState;(!i||i==="loaded"||i==="complete")&&(r.onload=r.onreadystatechange=null,r.parentNode&&r.parentNode.removeChild(r),n())},r.onerror=()=>{je("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(r)}catch{}},Math.floor(1))}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Rx=16384,Ax=45e3;let dl=null;typeof MozWebSocket<"u"?dl=MozWebSocket:typeof WebSocket<"u"&&(dl=WebSocket);class bt{constructor(e,n,r,i,s,o,l){this.connId=e,this.applicationId=r,this.appCheckToken=i,this.authToken=s,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Ws(this.connId),this.stats_=Td(n),this.connURL=bt.connectionURL_(n,o,l,i,r),this.nodeAdmin=n.nodeAdmin}static connectionURL_(e,n,r,i,s){const o={};return o[zv]=kd,typeof location<"u"&&location.hostname&&Vv.test(location.hostname)&&(o[Wv]=$v),n&&(o[Bv]=n),r&&(o[Hv]=r),i&&(o[tc]=i),s&&(o[Gv]=s),Yv(e,qv,o)}open(e,n){this.onDisconnect=n,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ir.set("previous_websocket_failure",!0);try{let r;NC(),this.mySock=new dl(this.connURL,[],r)}catch(r){this.log_("Error instantiating WebSocket.");const i=r.message||r.data;i&&this.log_(i),this.onClosed_();return}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=r=>{this.handleIncomingFrame(r)},this.mySock.onerror=r=>{this.log_("WebSocket error. Closing connection.");const i=r.message||r.data;i&&this.log_(i),this.onClosed_()}}start(){}static forceDisallow(){bt.forceDisallow_=!0}static isAvailable(){let e=!1;if(typeof navigator<"u"&&navigator.userAgent){const n=/Android ([0-9]{0,}\.[0-9]{0,})/,r=navigator.userAgent.match(n);r&&r.length>1&&parseFloat(r[1])<4.4&&(e=!0)}return!e&&dl!==null&&!bt.forceDisallow_}static previouslyFailed(){return ir.isInMemoryStorage||ir.get("previous_websocket_failure")===!0}markConnectionHealthy(){ir.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const n=this.frames.join("");this.frames=null;const r=ws(n);this.onMessage(r)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(N(this.frames===null,"We already have a frame buffer"),e.length<=6){const n=Number(e);if(!isNaN(n))return this.handleNewFrameCount_(n),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(this.mySock===null)return;const n=e.data;if(this.bytesReceived+=n.length,this.stats_.incrementCounter("bytes_received",n.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(n);else{const r=this.extractFrameCount_(n);r!==null&&this.appendFrame_(r)}}send(e){this.resetKeepAlive();const n=Ne(e);this.bytesSent+=n.length,this.stats_.incrementCounter("bytes_sent",n.length);const r=Fv(n,Rx);r.length>1&&this.sendString_(String(r.length));for(let i=0;i{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(Ax))}sendString_(e){try{this.mySock.send(e)}catch(n){this.log_("Exception thrown from WebSocket.send():",n.message||n.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}bt.responsesRequiredToBeHealthy=2;bt.healthyTimeout=3e4;/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Cs{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[zr,bt]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){const n=bt&&bt.isAvailable();let r=n&&!bt.previouslyFailed();if(e.webSocketOnly&&(n||Ye("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),r=!0),r)this.transports_=[bt];else{const i=this.transports_=[];for(const s of Cs.ALL_TRANSPORTS)s&&s.isAvailable()&&i.push(s);Cs.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}}Cs.globalTransportInitialized_=!1;/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Ox=6e4,Dx=5e3,Lx=10*1024,Mx=100*1024,Ga="t",Kf="d",jx="s",Qf="r",Fx="e",Yf="o",Jf="a",Xf="n",Zf="p",Ux="h";class zx{constructor(e,n,r,i,s,o,l,a,u,h){this.id=e,this.repoInfo_=n,this.applicationId_=r,this.appCheckToken_=i,this.authToken_=s,this.onMessage_=o,this.onReady_=l,this.onDisconnect_=a,this.onKill_=u,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Ws("c:"+this.id+":"),this.transportManager_=new Cs(n),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 n=this.connReceiver_(this.conn_),r=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(n,r)},Math.floor(0));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=Yi(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>Mx?(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>Lx?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(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return n=>{e===this.conn_?this.onConnectionLost_(n):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return n=>{this.state_!==2&&(e===this.rx_?this.onPrimaryMessageReceived_(n):e===this.secondaryConn_?this.onSecondaryMessageReceived_(n):this.log_("message on old connection"))}}sendRequest(e){const n={t:"d",d:e};this.sendData_(n)}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(Ga in e){const n=e[Ga];n===Jf?this.upgradeIfSecondaryHealthy_():n===Qf?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):n===Yf&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const n=Ai("t",e),r=Ai("d",e);if(n==="c")this.onSecondaryControl_(r);else if(n==="d")this.pendingDataMessages.push(r);else throw new Error("Unknown protocol layer: "+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:Zf,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:Jf,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:Xf,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const n=Ai("t",e),r=Ai("d",e);n==="c"?this.onControl_(r):n==="d"&&this.onDataMessage_(r)}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 n=Ai(Ga,e);if(Kf in e){const r=e[Kf];if(n===Ux){const i=Object.assign({},r);this.repoInfo_.isUsingEmulator&&(i.h=this.repoInfo_.host),this.onHandshake_(i)}else if(n===Xf){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let i=0;i{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(Ox))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,this.state_===1?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,n){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(n,this.sessionId),this.onReady_=null),this.primaryResponsesRequired_===0?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Yi(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(Dx))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:Zf,d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,!e&&this.state_===0?(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(ir.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)):this.state_===1&&this.log_("Realtime connection lost."),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(this.state_!==1)throw"Connection is not connected";this.tx_.send(e)}close(){this.state_!==2&&(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)}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class ny{put(e,n,r,i){}merge(e,n,r,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,n,r){}onDisconnectMerge(e,n,r){}onDisconnectCancel(e,n){}reportStats(e){}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class ry{constructor(e){this.allowedEvents_=e,this.listeners_={},N(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...n){if(Array.isArray(this.listeners_[e])){const r=[...this.listeners_[e]];for(let i=0;in===e),"Unknown event: "+e)}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class hl extends ry{constructor(){super(["online"]),this.online_=!0,typeof window<"u"&&typeof window.addEventListener<"u"&&!wd()&&(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))}static getInstance(){return new hl}getInitialEvent(e){return N(e==="online","Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const ep=32,tp=768;class le{constructor(e,n){if(n===void 0){this.pieces_=e.split("/");let r=0;for(let i=0;i0&&(this.pieces_[r]=this.pieces_[i],r++);this.pieces_.length=r,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=n}toString(){let e="";for(let n=this.pieceNum_;n=t.pieces_.length?null:t.pieces_[t.pieceNum_]}function Wn(t){return t.pieces_.length-t.pieceNum_}function ue(t){let e=t.pieceNum_;return e=t.pieces_.length)return null;const e=[];for(let n=t.pieceNum_;n0&&n.push(r[i])}return new le(n,0)}function H(t){return t.pieceNum_>=t.pieces_.length}function Ke(t,e){const n=$(t),r=$(e);if(n===null)return e;if(n===r)return Ke(ue(t),ue(e));throw new Error("INTERNAL ERROR: innerPath ("+e+") is not within outerPath ("+t+")")}function Wx(t,e){const n=Es(t,0),r=Es(e,0);for(let i=0;iWn(e))return!1;for(;n0&&(t.byteLength_+=1),t.parts_.push(e),t.byteLength_+=Kl(e),sy(t)}function Hx(t){const e=t.parts_.pop();t.byteLength_-=Kl(e),t.parts_.length>0&&(t.byteLength_-=1)}function sy(t){if(t.byteLength_>tp)throw new Error(t.errorPrefix_+"has a key path longer than "+tp+" bytes ("+t.byteLength_+").");if(t.parts_.length>ep)throw new Error(t.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+ep+") or object contains a cycle "+er(t))}function er(t){return t.parts_.length===0?"":"in property '"+t.parts_.join(".")+"'"}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Rd extends ry{constructor(){super(["visible"]);let e,n;typeof document<"u"&&typeof document.addEventListener<"u"&&(typeof document.hidden<"u"?(n="visibilitychange",e="hidden"):typeof document.mozHidden<"u"?(n="mozvisibilitychange",e="mozHidden"):typeof document.msHidden<"u"?(n="msvisibilitychange",e="msHidden"):typeof document.webkitHidden<"u"&&(n="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,n&&document.addEventListener(n,()=>{const r=!document[e];r!==this.visible_&&(this.visible_=r,this.trigger("visible",r))},!1)}static getInstance(){return new Rd}getInitialEvent(e){return N(e==="visible","Unknown event type: "+e),[this.visible_]}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Oi=1e3,Gx=60*5*1e3,np=30*1e3,qx=1.3,Kx=3e4,Qx="server_kill",rp=3;class Xt extends ny{constructor(e,n,r,i,s,o,l,a){if(super(),this.repoInfo_=e,this.applicationId_=n,this.onDataUpdate_=r,this.onConnectStatus_=i,this.onServerInfoUpdate_=s,this.authTokenProvider_=o,this.appCheckTokenProvider_=l,this.authOverride_=a,this.id=Xt.nextPersistentConnectionId_++,this.log_=Ws("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_=Oi,this.maxReconnectDelay_=Gx,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)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Rd.getInstance().on("visible",this.onVisible_,this),e.host.indexOf("fblocal")===-1&&hl.getInstance().on("online",this.onOnline_,this)}sendRequest(e,n,r){const i=++this.requestNumber_,s={r:i,a:e,b:n};this.log_(Ne(s)),N(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(s),r&&(this.requestCBHash_[i]=r)}get(e){this.initConnection_();const n=new Us,i={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:o=>{const l=o.d;o.s==="ok"?n.resolve(l):n.reject(l)}};this.outstandingGets_.push(i),this.outstandingGetCount_++;const s=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(s),n.promise}listen(e,n,r,i){this.initConnection_();const s=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+s),this.listens.has(o)||this.listens.set(o,new Map),N(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),N(!this.listens.get(o).has(s),"listen() called twice for same path/queryId.");const l={onComplete:i,hashFn:n,query:e,tag:r};this.listens.get(o).set(s,l),this.connected_&&this.sendListen_(l)}sendGet_(e){const n=this.outstandingGets_[e];this.sendRequest("g",n.request,r=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(r)})}sendListen_(e){const n=e.query,r=n._path.toString(),i=n._queryIdentifier;this.log_("Listen on "+r+" for "+i);const s={p:r},o="q";e.tag&&(s.q=n._queryObject,s.t=e.tag),s.h=e.hashFn(),this.sendRequest(o,s,l=>{const a=l.d,u=l.s;Xt.warnOnListenWarnings_(a,n),(this.listens.get(r)&&this.listens.get(r).get(i))===e&&(this.log_("listen response",l),u!=="ok"&&this.removeListen_(r,i),e.onComplete&&e.onComplete(u,a))})}static warnOnListenWarnings_(e,n){if(e&&typeof e=="object"&&Bt(e,"w")){const r=oi(e,"w");if(Array.isArray(r)&&~r.indexOf("no_index")){const i='".indexOn": "'+n._queryParams.getIndex().toString()+'"',s=n._path.toString();Ye(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${i} at ${s} 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&&e.length===40||jC(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=np)}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_,n=MC(e)?"auth":"gauth",r={cred:e};this.authOverride_===null?r.noauth=!0:typeof this.authOverride_=="object"&&(r.authvar=this.authOverride_),this.sendRequest(n,r,i=>{const s=i.s,o=i.d||"error";this.authToken_===e&&(s==="ok"?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(s,o))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{const n=e.s,r=e.d||"error";n==="ok"?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(n,r)})}unlisten(e,n){const r=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+r+" "+i),N(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(r,i)&&this.connected_&&this.sendUnlisten_(r,i,e._queryObject,n)}sendUnlisten_(e,n,r,i){this.log_("Unlisten on "+e+" for "+n);const s={p:e},o="n";i&&(s.q=r,s.t=i),this.sendRequest(o,s)}onDisconnectPut(e,n,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,n,r):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:n,onComplete:r})}onDisconnectMerge(e,n,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,n,r):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:n,onComplete:r})}onDisconnectCancel(e,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:n})}sendOnDisconnect_(e,n,r,i){const s={p:n,d:r};this.log_("onDisconnect "+e,s),this.sendRequest(e,s,o=>{i&&setTimeout(()=>{i(o.s,o.d)},Math.floor(0))})}put(e,n,r,i){this.putInternal("p",e,n,r,i)}merge(e,n,r,i){this.putInternal("m",e,n,r,i)}putInternal(e,n,r,i,s){this.initConnection_();const o={p:n,d:r};s!==void 0&&(o.h=s),this.outstandingPuts_.push({action:e,request:o,onComplete:i}),this.outstandingPutCount_++;const l=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(l):this.log_("Buffering put: "+n)}sendPut_(e){const n=this.outstandingPuts_[e].action,r=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(n,r,s=>{this.log_(n+" response",s),delete this.outstandingPuts_[e],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),i&&i(s.s,s.d)})}reportStats(e){if(this.connected_){const n={c:e};this.log_("reportStats",n),this.sendRequest("s",n,r=>{if(r.s!=="ok"){const s=r.d;this.log_("reportStats","Error sending stats: "+s)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+Ne(e));const n=e.r,r=this.requestCBHash_[n];r&&(delete this.requestCBHash_[n],r(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,n){this.log_("handleServerMessage",e,n),e==="d"?this.onDataUpdate_(n.p,n.d,!1,n.t):e==="m"?this.onDataUpdate_(n.p,n.d,!0,n.t):e==="c"?this.onListenRevoked_(n.p,n.q):e==="ac"?this.onAuthRevoked_(n.s,n.d):e==="apc"?this.onAppCheckRevoked_(n.s,n.d):e==="sd"?this.onSecurityDebugPacket_(n):ec("Unrecognized action received from server: "+Ne(e)+` +Are you using the latest client?`)}onReady_(e,n){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(e),this.lastSessionId=n,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){N(!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_=Oi,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=Oi,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_()){this.visible_?this.lastConnectionEstablishedTime_&&(new Date().getTime()-this.lastConnectionEstablishedTime_>Kx&&(this.reconnectDelay_=Oi),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());const e=new Date().getTime()-this.lastConnectionAttemptTime_;let n=Math.max(0,this.reconnectDelay_-e);n=Math.random()*n,this.log_("Trying to reconnect in "+n+"ms"),this.scheduleConnect_(n),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*qx)}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),n=this.onReady_.bind(this),r=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+Xt.nextConnectionId_++,s=this.lastSessionId;let o=!1,l=null;const a=function(){l?l.close():(o=!0,r())},u=function(d){N(l,"sendRequest call when we're not connected not allowed."),l.sendRequest(d)};this.realtime_={close:a,sendRequest:u};const h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[d,f]=await Promise.all([this.authTokenProvider_.getToken(h),this.appCheckTokenProvider_.getToken(h)]);o?je("getToken() completed but was canceled"):(je("getToken() completed. Creating connection."),this.authToken_=d&&d.accessToken,this.appCheckToken_=f&&f.token,l=new zx(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,n,r,v=>{Ye(v+" ("+this.repoInfo_.toString()+")"),this.interrupt(Qx)},s))}catch(d){this.log_("Failed to get token: "+d),o||(this.repoInfo_.nodeAdmin&&Ye(d),a())}}}interrupt(e){je("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){je("Resuming connection for reason: "+e),delete this.interruptReasons_[e],Ku(this.interruptReasons_)&&(this.reconnectDelay_=Oi,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const n=e-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:n})}cancelSentTransactions_(){for(let e=0;eId(s)).join("$"):r="default";const i=this.removeListen_(e,r);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,n){const r=new le(e).toString();let i;if(this.listens.has(r)){const s=this.listens.get(r);i=s.get(n),s.delete(n),s.size===0&&this.listens.delete(r)}else i=void 0;return i}onAuthRevoked_(e,n){je("Auth token revoked: "+e+"/"+n),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(e==="invalid_token"||e==="permission_denied")&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=rp&&(this.reconnectDelay_=np,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,n){je("App check token revoked: "+e+"/"+n),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(e==="invalid_token"||e==="permission_denied")&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=rp&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace(` +`,` +FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const n of e.values())this.sendListen_(n);for(let e=0;e0}peek(){if(this.nodeStack_.length===0)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 De{constructor(e,n,r,i,s){this.key=e,this.value=n,this.color=r??De.RED,this.left=i??st.EMPTY_NODE,this.right=s??st.EMPTY_NODE}copy(e,n,r,i,s){return new De(e??this.key,n??this.value,r??this.color,i??this.left,s??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,n,r){let i=this;const s=r(e,i.key);return s<0?i=i.copy(null,null,null,i.left.insert(e,n,r),null):s===0?i=i.copy(null,n,null,null,null):i=i.copy(null,null,null,null,i.right.insert(e,n,r)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return st.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,n){let r,i;if(r=this,n(e,r.key)<0)!r.left.isEmpty()&&!r.left.isRed_()&&!r.left.left.isRed_()&&(r=r.moveRedLeft_()),r=r.copy(null,null,null,r.left.remove(e,n),null);else{if(r.left.isRed_()&&(r=r.rotateRight_()),!r.right.isEmpty()&&!r.right.isRed_()&&!r.right.left.isRed_()&&(r=r.moveRedRight_()),n(e,r.key)===0){if(r.right.isEmpty())return st.EMPTY_NODE;i=r.right.min_(),r=r.copy(i.key,i.value,null,null,r.right.removeMin_())}r=r.copy(null,null,null,null,r.right.remove(e,n))}return r.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,De.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,De.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),n=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,n)}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)}}De.RED=!0;De.BLACK=!1;class Yx{copy(e,n,r,i,s){return this}insert(e,n,r){return new De(e,n,null)}remove(e,n){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}}class st{constructor(e,n=st.EMPTY_NODE){this.comparator_=e,this.root_=n}insert(e,n){return new st(this.comparator_,this.root_.insert(e,n,this.comparator_).copy(null,null,De.BLACK,null,null))}remove(e){return new st(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,De.BLACK,null,null))}get(e){let n,r=this.root_;for(;!r.isEmpty();){if(n=this.comparator_(e,r.key),n===0)return r.value;n<0?r=r.left:n>0&&(r=r.right)}return null}getPredecessorKey(e){let n,r=this.root_,i=null;for(;!r.isEmpty();)if(n=this.comparator_(e,r.key),n===0){if(r.left.isEmpty())return i?i.key:null;for(r=r.left;!r.right.isEmpty();)r=r.right;return r.key}else n<0?r=r.left:n>0&&(i=r,r=r.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 mo(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,n){return new mo(this.root_,e,this.comparator_,!1,n)}getReverseIteratorFrom(e,n){return new mo(this.root_,e,this.comparator_,!0,n)}getReverseIterator(e){return new mo(this.root_,null,this.comparator_,!0,e)}}st.EMPTY_NODE=new Yx;/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function Jx(t,e){return Cr(t.name,e.name)}function Ad(t,e){return Cr(t,e)}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */let nc;function Xx(t){nc=t}const ly=function(t){return typeof t=="number"?"number:"+Uv(t):"string:"+t},ay=function(t){if(t.isLeafNode()){const e=t.val();N(typeof e=="string"||typeof e=="number"||typeof e=="object"&&Bt(e,".sv"),"Priority must be a string or number.")}else N(t===nc||t.isEmpty(),"priority of unexpected type.");N(t===nc||t.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */let ip;class Ae{constructor(e,n=Ae.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=n,this.lazyHash_=null,N(this.value_!==void 0&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value."),ay(this.priorityNode_)}static set __childrenNodeConstructor(e){ip=e}static get __childrenNodeConstructor(){return ip}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Ae(this.value_,e)}getImmediateChild(e){return e===".priority"?this.priorityNode_:Ae.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return H(e)?this:$(e)===".priority"?this.priorityNode_:Ae.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,n){return null}updateImmediateChild(e,n){return e===".priority"?this.updatePriority(n):n.isEmpty()&&e!==".priority"?this:Ae.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,n).updatePriority(this.priorityNode_)}updateChild(e,n){const r=$(e);return r===null?n:n.isEmpty()&&r!==".priority"?this:(N(r!==".priority"||Wn(e)===1,".priority must be the last token in a path"),this.updateImmediateChild(r,Ae.__childrenNodeConstructor.EMPTY_NODE.updateChild(ue(e),n)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,n){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+ly(this.priorityNode_.val())+":");const n=typeof this.value_;e+=n+":",n==="number"?e+=Uv(this.value_):e+=this.value_,this.lazyHash_=jv(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Ae.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Ae.__childrenNodeConstructor?-1:(N(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const n=typeof e.value_,r=typeof this.value_,i=Ae.VALUE_TYPE_ORDER.indexOf(n),s=Ae.VALUE_TYPE_ORDER.indexOf(r);return N(i>=0,"Unknown leaf type: "+n),N(s>=0,"Unknown leaf type: "+r),i===s?r==="object"?0:this.value_parseInt(Math.log(s)/nI,10),r=s=>parseInt(Array(s+1).join("1"),2);this.count=n(e+1),this.current_=this.count-1;const i=r(this.count);this.bits_=e+1&i}nextBitIsOne(){const e=!(this.bits_&1<{const o=oi(this.indexSet_,s);if(N(o,"Missing index implementation for "+s),i===Tr)if(o.isDefinedOn(e.node)){const l=[],a=n.getIterator(V.Wrap);let u=a.getNext();for(;u;)u.name!==e.name&&l.push(u),u=a.getNext();return l.push(e),fl(l,o.getCompare())}else return Tr;else{const l=n.get(e.name);let a=i;return l&&(a=a.remove(new V(e.name,l))),a.insert(e,e.node)}});return new qt(r,this.indexSet_)}removeFromIndexes(e,n){const r=al(this.indexes_,i=>{if(i===Tr)return i;{const s=n.get(e.name);return s?i.remove(new V(e.name,s)):i}});return new qt(r,this.indexSet_)}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */let Di;class B{constructor(e,n,r){this.children_=e,this.priorityNode_=n,this.indexMap_=r,this.lazyHash_=null,this.priorityNode_&&ay(this.priorityNode_),this.children_.isEmpty()&&N(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return Di||(Di=new B(new st(Ad),null,qt.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Di}updatePriority(e){return this.children_.isEmpty()?this:new B(this.children_,e,this.indexMap_)}getImmediateChild(e){if(e===".priority")return this.getPriority();{const n=this.children_.get(e);return n===null?Di:n}}getChild(e){const n=$(e);return n===null?this:this.getImmediateChild(n).getChild(ue(e))}hasChild(e){return this.children_.get(e)!==null}updateImmediateChild(e,n){if(N(n,"We should always be passing snapshot nodes"),e===".priority")return this.updatePriority(n);{const r=new V(e,n);let i,s;n.isEmpty()?(i=this.children_.remove(e),s=this.indexMap_.removeFromIndexes(r,this.children_)):(i=this.children_.insert(e,n),s=this.indexMap_.addToIndexes(r,this.children_));const o=i.isEmpty()?Di:this.priorityNode_;return new B(i,o,s)}}updateChild(e,n){const r=$(e);if(r===null)return n;{N($(e)!==".priority"||Wn(e)===1,".priority must be the last token in a path");const i=this.getImmediateChild(r).updateChild(ue(e),n);return this.updateImmediateChild(r,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const n={};let r=0,i=0,s=!0;if(this.forEachChild(we,(o,l)=>{n[o]=l.val(e),r++,s&&B.INTEGER_REGEXP_.test(o)?i=Math.max(i,Number(o)):s=!1}),!e&&s&&i<2*r){const o=[];for(const l in n)o[l]=n[l];return o}else return e&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n}hash(){if(this.lazyHash_===null){let e="";this.getPriority().isEmpty()||(e+="priority:"+ly(this.getPriority().val())+":"),this.forEachChild(we,(n,r)=>{const i=r.hash();i!==""&&(e+=":"+n+":"+i)}),this.lazyHash_=e===""?"":jv(e)}return this.lazyHash_}getPredecessorChildName(e,n,r){const i=this.resolveIndex_(r);if(i){const s=i.getPredecessorKey(new V(e,n));return s?s.name:null}else return this.children_.getPredecessorKey(e)}getFirstChildName(e){const n=this.resolveIndex_(e);if(n){const r=n.minKey();return r&&r.name}else return this.children_.minKey()}getFirstChild(e){const n=this.getFirstChildName(e);return n?new V(n,this.children_.get(n)):null}getLastChildName(e){const n=this.resolveIndex_(e);if(n){const r=n.maxKey();return r&&r.name}else return this.children_.maxKey()}getLastChild(e){const n=this.getLastChildName(e);return n?new V(n,this.children_.get(n)):null}forEachChild(e,n){const r=this.resolveIndex_(e);return r?r.inorderTraversal(i=>n(i.name,i.node)):this.children_.inorderTraversal(n)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,n){const r=this.resolveIndex_(n);if(r)return r.getIteratorFrom(e,i=>i);{const i=this.children_.getIteratorFrom(e.name,V.Wrap);let s=i.peek();for(;s!=null&&n.compare(s,e)<0;)i.getNext(),s=i.peek();return i}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,n){const r=this.resolveIndex_(n);if(r)return r.getReverseIteratorFrom(e,i=>i);{const i=this.children_.getReverseIteratorFrom(e.name,V.Wrap);let s=i.peek();for(;s!=null&&n.compare(s,e)>0;)i.getNext(),s=i.peek();return i}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===$s?-1:0}withIndex(e){if(e===Qr||this.indexMap_.hasIndex(e))return this;{const n=this.indexMap_.addIndex(e,this.children_);return new B(this.children_,this.priorityNode_,n)}}isIndexed(e){return e===Qr||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority()))if(this.children_.count()===n.children_.count()){const r=this.getIterator(we),i=n.getIterator(we);let s=r.getNext(),o=i.getNext();for(;s&&o;){if(s.name!==o.name||!s.node.equals(o.node))return!1;s=r.getNext(),o=i.getNext()}return s===null&&o===null}else return!1;else return!1}}resolveIndex_(e){return e===Qr?null:this.indexMap_.get(e.toString())}}B.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class iI extends B{constructor(){super(new st(Ad),B.EMPTY_NODE,qt.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return B.EMPTY_NODE}isEmpty(){return!1}}const $s=new iI;Object.defineProperties(V,{MIN:{value:new V(ai,B.EMPTY_NODE)},MAX:{value:new V(pr,$s)}});oy.__EMPTY_NODE=B.EMPTY_NODE;Ae.__childrenNodeConstructor=B;Xx($s);eI($s);/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const sI=!0;function Pe(t,e=null){if(t===null)return B.EMPTY_NODE;if(typeof t=="object"&&".priority"in t&&(e=t[".priority"]),N(e===null||typeof e=="string"||typeof e=="number"||typeof e=="object"&&".sv"in e,"Invalid priority type found: "+typeof e),typeof t=="object"&&".value"in t&&t[".value"]!==null&&(t=t[".value"]),typeof t!="object"||".sv"in t){const n=t;return new Ae(n,Pe(e))}if(!(t instanceof Array)&&sI){const n=[];let r=!1;if(ze(t,(o,l)=>{if(o.substring(0,1)!=="."){const a=Pe(l);a.isEmpty()||(r=r||!a.getPriority().isEmpty(),n.push(new V(o,a)))}}),n.length===0)return B.EMPTY_NODE;const s=fl(n,Jx,o=>o.name,Ad);if(r){const o=fl(n,we.getCompare());return new B(s,Pe(e),new qt({".priority":o},{".priority":we}))}else return new B(s,Pe(e),qt.Default)}else{let n=B.EMPTY_NODE;return ze(t,(r,i)=>{if(Bt(t,r)&&r.substring(0,1)!=="."){const s=Pe(i);(s.isLeafNode()||!s.isEmpty())&&(n=n.updateImmediateChild(r,s))}}),n.updatePriority(Pe(e))}}Zx(Pe);/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class oI extends Ql{constructor(e){super(),this.indexPath_=e,N(!H(e)&&$(e)!==".priority","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,n){const r=this.extractChild(e.node),i=this.extractChild(n.node),s=r.compareTo(i);return s===0?Cr(e.name,n.name):s}makePost(e,n){const r=Pe(e),i=B.EMPTY_NODE.updateChild(this.indexPath_,r);return new V(n,i)}maxPost(){const e=B.EMPTY_NODE.updateChild(this.indexPath_,$s);return new V(pr,e)}toString(){return Es(this.indexPath_,0).join("/")}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class lI extends Ql{compare(e,n){const r=e.node.compareTo(n.node);return r===0?Cr(e.name,n.name):r}isDefinedOn(e){return!0}indexedValueChanged(e,n){return!e.equals(n)}minPost(){return V.MIN}maxPost(){return V.MAX}makePost(e,n){const r=Pe(e);return new V(n,r)}toString(){return".value"}}const aI=new lI;/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function dy(t){return{type:"value",snapshotNode:t}}function ui(t,e){return{type:"child_added",snapshotNode:e,childName:t}}function xs(t,e){return{type:"child_removed",snapshotNode:e,childName:t}}function Is(t,e,n){return{type:"child_changed",snapshotNode:e,childName:t,oldSnap:n}}function uI(t,e){return{type:"child_moved",snapshotNode:e,childName:t}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Od{constructor(e){this.index_=e}updateChild(e,n,r,i,s,o){N(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const l=e.getImmediateChild(n);return l.getChild(i).equals(r.getChild(i))&&l.isEmpty()===r.isEmpty()||(o!=null&&(r.isEmpty()?e.hasChild(n)?o.trackChildChange(xs(n,l)):N(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):l.isEmpty()?o.trackChildChange(ui(n,r)):o.trackChildChange(Is(n,r,l))),e.isLeafNode()&&r.isEmpty())?e:e.updateImmediateChild(n,r).withIndex(this.index_)}updateFullNode(e,n,r){return r!=null&&(e.isLeafNode()||e.forEachChild(we,(i,s)=>{n.hasChild(i)||r.trackChildChange(xs(i,s))}),n.isLeafNode()||n.forEachChild(we,(i,s)=>{if(e.hasChild(i)){const o=e.getImmediateChild(i);o.equals(s)||r.trackChildChange(Is(i,s,o))}else r.trackChildChange(ui(i,s))})),n.withIndex(this.index_)}updatePriority(e,n){return e.isEmpty()?B.EMPTY_NODE:e.updatePriority(n)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class ks{constructor(e){this.indexedFilter_=new Od(e.getIndex()),this.index_=e.getIndex(),this.startPost_=ks.getStartPost_(e),this.endPost_=ks.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const n=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,r=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return n&&r}updateChild(e,n,r,i,s,o){return this.matches(new V(n,r))||(r=B.EMPTY_NODE),this.indexedFilter_.updateChild(e,n,r,i,s,o)}updateFullNode(e,n,r){n.isLeafNode()&&(n=B.EMPTY_NODE);let i=n.withIndex(this.index_);i=i.updatePriority(B.EMPTY_NODE);const s=this;return n.forEachChild(we,(o,l)=>{s.matches(new V(o,l))||(i=i.updateImmediateChild(o,B.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,r)}updatePriority(e,n){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const n=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),n)}else return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const n=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),n)}else return e.getIndex().maxPost()}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class cI{constructor(e){this.withinDirectionalStart=n=>this.reverse_?this.withinEndPost(n):this.withinStartPost(n),this.withinDirectionalEnd=n=>this.reverse_?this.withinStartPost(n):this.withinEndPost(n),this.withinStartPost=n=>{const r=this.index_.compare(this.rangedFilter_.getStartPost(),n);return this.startIsInclusive_?r<=0:r<0},this.withinEndPost=n=>{const r=this.index_.compare(n,this.rangedFilter_.getEndPost());return this.endIsInclusive_?r<=0:r<0},this.rangedFilter_=new ks(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,n,r,i,s,o){return this.rangedFilter_.matches(new V(n,r))||(r=B.EMPTY_NODE),e.getImmediateChild(n).equals(r)?e:e.numChildren()d(v,f)}else o=this.index_.getCompare();const l=e;N(l.numChildren()===this.limit_,"");const a=new V(n,r),u=this.reverse_?l.getFirstChild(this.index_):l.getLastChild(this.index_),h=this.rangedFilter_.matches(a);if(l.hasChild(n)){const d=l.getImmediateChild(n);let f=i.getChildAfterChild(this.index_,u,this.reverse_);for(;f!=null&&(f.name===n||l.hasChild(f.name));)f=i.getChildAfterChild(this.index_,f,this.reverse_);const v=f==null?1:o(f,a);if(h&&!r.isEmpty()&&v>=0)return s!=null&&s.trackChildChange(Is(n,r,d)),l.updateImmediateChild(n,r);{s!=null&&s.trackChildChange(xs(n,d));const _=l.updateImmediateChild(n,B.EMPTY_NODE);return f!=null&&this.rangedFilter_.matches(f)?(s!=null&&s.trackChildChange(ui(f.name,f.node)),_.updateImmediateChild(f.name,f.node)):_}}else return r.isEmpty()?e:h&&o(u,a)>=0?(s!=null&&(s.trackChildChange(xs(u.name,u.node)),s.trackChildChange(ui(n,r))),l.updateImmediateChild(n,r).updateImmediateChild(u.name,B.EMPTY_NODE)):e}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Dd{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_=we}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===""?this.startSet_:this.viewFrom_==="l"}getIndexStartValue(){return N(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return N(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:ai}hasEnd(){return this.endSet_}getIndexEndValue(){return N(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return N(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:pr}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){return N(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_===we}copy(){const e=new Dd;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 dI(t){return t.loadsAllData()?new Od(t.getIndex()):t.hasLimit()?new cI(t):new ks(t)}function sp(t){const e={};if(t.isDefault())return e;let n;if(t.index_===we?n="$priority":t.index_===aI?n="$value":t.index_===Qr?n="$key":(N(t.index_ instanceof oI,"Unrecognized index type!"),n=t.index_.toString()),e.orderBy=Ne(n),t.startSet_){const r=t.startAfterSet_?"startAfter":"startAt";e[r]=Ne(t.indexStartValue_),t.startNameSet_&&(e[r]+=","+Ne(t.indexStartName_))}if(t.endSet_){const r=t.endBeforeSet_?"endBefore":"endAt";e[r]=Ne(t.indexEndValue_),t.endNameSet_&&(e[r]+=","+Ne(t.indexEndName_))}return t.limitSet_&&(t.isViewFromLeft()?e.limitToFirst=t.limit_:e.limitToLast=t.limit_),e}function op(t){const e={};if(t.startSet_&&(e.sp=t.indexStartValue_,t.startNameSet_&&(e.sn=t.indexStartName_),e.sin=!t.startAfterSet_),t.endSet_&&(e.ep=t.indexEndValue_,t.endNameSet_&&(e.en=t.indexEndName_),e.ein=!t.endBeforeSet_),t.limitSet_){e.l=t.limit_;let n=t.viewFrom_;n===""&&(t.isViewFromLeft()?n="l":n="r"),e.vf=n}return t.index_!==we&&(e.i=t.index_.toString()),e}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class pl extends ny{constructor(e,n,r,i){super(),this.repoInfo_=e,this.onDataUpdate_=n,this.authTokenProvider_=r,this.appCheckTokenProvider_=i,this.log_=Ws("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,n){return n!==void 0?"tag$"+n:(N(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,n,r,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const o=pl.getListenId_(e,r),l={};this.listens_[o]=l;const a=sp(e._queryParams);this.restRequest_(s+".json",a,(u,h)=>{let d=h;if(u===404&&(d=null,u=null),u===null&&this.onDataUpdate_(s,d,!1,r),oi(this.listens_,o)===l){let f;u?u===401?f="permission_denied":f="rest_error:"+u:f="ok",i(f,null)}})}unlisten(e,n){const r=pl.getListenId_(e,n);delete this.listens_[r]}get(e){const n=sp(e._queryParams),r=e._path.toString(),i=new Us;return this.restRequest_(r+".json",n,(s,o)=>{let l=o;s===404&&(l=null,s=null),s===null?(this.onDataUpdate_(r,l,!1,null),i.resolve(l)):i.reject(new Error(l))}),i.promise}refreshAuthToken(e){}restRequest_(e,n={},r){return n.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,s])=>{i&&i.accessToken&&(n.auth=i.accessToken),s&&s.token&&(n.ac=s.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+yi(n);this.log_("Sending REST request for "+o);const l=new XMLHttpRequest;l.onreadystatechange=()=>{if(r&&l.readyState===4){this.log_("REST Response for "+o+" received. status:",l.status,"response:",l.responseText);let a=null;if(l.status>=200&&l.status<300){try{a=ws(l.responseText)}catch{Ye("Failed to parse JSON response for "+o+": "+l.responseText)}r(null,a)}else l.status!==401&&l.status!==404&&Ye("Got unsuccessful REST response for "+o+" Status: "+l.status),r(l.status);r=null}},l.open("GET",o,!0),l.send()})}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class hI{constructor(){this.rootNode_=B.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,n){this.rootNode_=this.rootNode_.updateChild(e,n)}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function ml(){return{value:null,children:new Map}}function hy(t,e,n){if(H(e))t.value=n,t.children.clear();else if(t.value!==null)t.value=t.value.updateChild(e,n);else{const r=$(e);t.children.has(r)||t.children.set(r,ml());const i=t.children.get(r);e=ue(e),hy(i,e,n)}}function rc(t,e,n){t.value!==null?n(e,t.value):fI(t,(r,i)=>{const s=new le(e.toString()+"/"+r);rc(i,s,n)})}function fI(t,e){t.children.forEach((n,r)=>{e(r,n)})}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class pI{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),n=Object.assign({},e);return this.last_&&ze(this.last_,(r,i)=>{n[r]=n[r]-i}),this.last_=e,n}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const lp=10*1e3,mI=30*1e3,gI=5*60*1e3;class vI{constructor(e,n){this.server_=n,this.statsToReport_={},this.statsListener_=new pI(e);const r=lp+(mI-lp)*Math.random();Yi(this.reportStats_.bind(this),Math.floor(r))}reportStats_(){const e=this.statsListener_.get(),n={};let r=!1;ze(e,(i,s)=>{s>0&&Bt(this.statsToReport_,i)&&(n[i]=s,r=!0)}),r&&this.server_.reportStats(n),Yi(this.reportStats_.bind(this),Math.floor(Math.random()*2*gI))}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */var Pt;(function(t){t[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"})(Pt||(Pt={}));function Ld(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Md(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function jd(t){return{fromUser:!1,fromServer:!0,queryId:t,tagged:!0}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class gl{constructor(e,n,r){this.path=e,this.affectedTree=n,this.revert=r,this.type=Pt.ACK_USER_WRITE,this.source=Ld()}operationForChild(e){if(H(this.path)){if(this.affectedTree.value!=null)return N(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const n=this.affectedTree.subtree(new le(e));return new gl(ee(),n,this.revert)}}else return N($(this.path)===e,"operationForChild called for unrelated child."),new gl(ue(this.path),this.affectedTree,this.revert)}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Ts{constructor(e,n){this.source=e,this.path=n,this.type=Pt.LISTEN_COMPLETE}operationForChild(e){return H(this.path)?new Ts(this.source,ee()):new Ts(this.source,ue(this.path))}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class mr{constructor(e,n,r){this.source=e,this.path=n,this.snap=r,this.type=Pt.OVERWRITE}operationForChild(e){return H(this.path)?new mr(this.source,ee(),this.snap.getImmediateChild(e)):new mr(this.source,ue(this.path),this.snap)}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class ci{constructor(e,n,r){this.source=e,this.path=n,this.children=r,this.type=Pt.MERGE}operationForChild(e){if(H(this.path)){const n=this.children.subtree(new le(e));return n.isEmpty()?null:n.value?new mr(this.source,ee(),n.value):new ci(this.source,ee(),n)}else return N($(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new ci(this.source,ue(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class $n{constructor(e,n,r){this.node_=e,this.fullyInitialized_=n,this.filtered_=r}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(H(e))return this.isFullyInitialized()&&!this.filtered_;const n=$(e);return this.isCompleteForChild(n)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class yI{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function _I(t,e,n,r){const i=[],s=[];return e.forEach(o=>{o.type==="child_changed"&&t.index_.indexedValueChanged(o.oldSnap,o.snapshotNode)&&s.push(uI(o.childName,o.snapshotNode))}),Li(t,i,"child_removed",e,r,n),Li(t,i,"child_added",e,r,n),Li(t,i,"child_moved",s,r,n),Li(t,i,"child_changed",e,r,n),Li(t,i,"value",e,r,n),i}function Li(t,e,n,r,i,s){const o=r.filter(l=>l.type===n);o.sort((l,a)=>SI(t,l,a)),o.forEach(l=>{const a=wI(t,l,s);i.forEach(u=>{u.respondsTo(l.type)&&e.push(u.createEvent(a,t.query_))})})}function wI(t,e,n){return e.type==="value"||e.type==="child_removed"||(e.prevName=n.getPredecessorChildName(e.childName,e.snapshotNode,t.index_)),e}function SI(t,e,n){if(e.childName==null||n.childName==null)throw vi("Should only compare child_ events.");const r=new V(e.childName,e.snapshotNode),i=new V(n.childName,n.snapshotNode);return t.index_.compare(r,i)}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function Yl(t,e){return{eventCache:t,serverCache:e}}function Ji(t,e,n,r){return Yl(new $n(e,n,r),t.serverCache)}function fy(t,e,n,r){return Yl(t.eventCache,new $n(e,n,r))}function vl(t){return t.eventCache.isFullyInitialized()?t.eventCache.getNode():null}function gr(t){return t.serverCache.isFullyInitialized()?t.serverCache.getNode():null}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */let Ka;const CI=()=>(Ka||(Ka=new st(ox)),Ka);class ae{constructor(e,n=CI()){this.value=e,this.children=n}static fromObject(e){let n=new ae(null);return ze(e,(r,i)=>{n=n.set(new le(r),i)}),n}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,n){if(this.value!=null&&n(this.value))return{path:ee(),value:this.value};if(H(e))return null;{const r=$(e),i=this.children.get(r);if(i!==null){const s=i.findRootMostMatchingPathAndValue(ue(e),n);return s!=null?{path:_e(new le(r),s.path),value:s.value}:null}else return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(H(e))return this;{const n=$(e),r=this.children.get(n);return r!==null?r.subtree(ue(e)):new ae(null)}}set(e,n){if(H(e))return new ae(n,this.children);{const r=$(e),s=(this.children.get(r)||new ae(null)).set(ue(e),n),o=this.children.insert(r,s);return new ae(this.value,o)}}remove(e){if(H(e))return this.children.isEmpty()?new ae(null):new ae(null,this.children);{const n=$(e),r=this.children.get(n);if(r){const i=r.remove(ue(e));let s;return i.isEmpty()?s=this.children.remove(n):s=this.children.insert(n,i),this.value===null&&s.isEmpty()?new ae(null):new ae(this.value,s)}else return this}}get(e){if(H(e))return this.value;{const n=$(e),r=this.children.get(n);return r?r.get(ue(e)):null}}setTree(e,n){if(H(e))return n;{const r=$(e),s=(this.children.get(r)||new ae(null)).setTree(ue(e),n);let o;return s.isEmpty()?o=this.children.remove(r):o=this.children.insert(r,s),new ae(this.value,o)}}fold(e){return this.fold_(ee(),e)}fold_(e,n){const r={};return this.children.inorderTraversal((i,s)=>{r[i]=s.fold_(_e(e,i),n)}),n(e,this.value,r)}findOnPath(e,n){return this.findOnPath_(e,ee(),n)}findOnPath_(e,n,r){const i=this.value?r(n,this.value):!1;if(i)return i;if(H(e))return null;{const s=$(e),o=this.children.get(s);return o?o.findOnPath_(ue(e),_e(n,s),r):null}}foreachOnPath(e,n){return this.foreachOnPath_(e,ee(),n)}foreachOnPath_(e,n,r){if(H(e))return this;{this.value&&r(n,this.value);const i=$(e),s=this.children.get(i);return s?s.foreachOnPath_(ue(e),_e(n,i),r):new ae(null)}}foreach(e){this.foreach_(ee(),e)}foreach_(e,n){this.children.inorderTraversal((r,i)=>{i.foreach_(_e(e,r),n)}),this.value&&n(e,this.value)}foreachChild(e){this.children.inorderTraversal((n,r)=>{r.value&&e(n,r.value)})}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class At{constructor(e){this.writeTree_=e}static empty(){return new At(new ae(null))}}function Xi(t,e,n){if(H(e))return new At(new ae(n));{const r=t.writeTree_.findRootMostValueAndPath(e);if(r!=null){const i=r.path;let s=r.value;const o=Ke(i,e);return s=s.updateChild(o,n),new At(t.writeTree_.set(i,s))}else{const i=new ae(n),s=t.writeTree_.setTree(e,i);return new At(s)}}}function ic(t,e,n){let r=t;return ze(n,(i,s)=>{r=Xi(r,_e(e,i),s)}),r}function ap(t,e){if(H(e))return At.empty();{const n=t.writeTree_.setTree(e,new ae(null));return new At(n)}}function sc(t,e){return Er(t,e)!=null}function Er(t,e){const n=t.writeTree_.findRootMostValueAndPath(e);return n!=null?t.writeTree_.get(n.path).getChild(Ke(n.path,e)):null}function up(t){const e=[],n=t.writeTree_.value;return n!=null?n.isLeafNode()||n.forEachChild(we,(r,i)=>{e.push(new V(r,i))}):t.writeTree_.children.inorderTraversal((r,i)=>{i.value!=null&&e.push(new V(r,i.value))}),e}function jn(t,e){if(H(e))return t;{const n=Er(t,e);return n!=null?new At(new ae(n)):new At(t.writeTree_.subtree(e))}}function oc(t){return t.writeTree_.isEmpty()}function di(t,e){return py(ee(),t.writeTree_,e)}function py(t,e,n){if(e.value!=null)return n.updateChild(t,e.value);{let r=null;return e.children.inorderTraversal((i,s)=>{i===".priority"?(N(s.value!==null,"Priority writes must always be leaf nodes"),r=s.value):n=py(_e(t,i),s,n)}),!n.getChild(t).isEmpty()&&r!==null&&(n=n.updateChild(_e(t,".priority"),r)),n}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function Jl(t,e){return yy(e,t)}function EI(t,e,n,r,i){N(r>t.lastWriteId,"Stacking an older write on top of newer ones"),i===void 0&&(i=!0),t.allWrites.push({path:e,snap:n,writeId:r,visible:i}),i&&(t.visibleWrites=Xi(t.visibleWrites,e,n)),t.lastWriteId=r}function xI(t,e,n,r){N(r>t.lastWriteId,"Stacking an older merge on top of newer ones"),t.allWrites.push({path:e,children:n,writeId:r,visible:!0}),t.visibleWrites=ic(t.visibleWrites,e,n),t.lastWriteId=r}function II(t,e){for(let n=0;nl.writeId===e);N(n>=0,"removeWrite called with nonexistent writeId.");const r=t.allWrites[n];t.allWrites.splice(n,1);let i=r.visible,s=!1,o=t.allWrites.length-1;for(;i&&o>=0;){const l=t.allWrites[o];l.visible&&(o>=n&&TI(l,r.path)?i=!1:yt(r.path,l.path)&&(s=!0)),o--}if(i){if(s)return bI(t),!0;if(r.snap)t.visibleWrites=ap(t.visibleWrites,r.path);else{const l=r.children;ze(l,a=>{t.visibleWrites=ap(t.visibleWrites,_e(r.path,a))})}return!0}else return!1}function TI(t,e){if(t.snap)return yt(t.path,e);for(const n in t.children)if(t.children.hasOwnProperty(n)&&yt(_e(t.path,n),e))return!0;return!1}function bI(t){t.visibleWrites=my(t.allWrites,PI,ee()),t.allWrites.length>0?t.lastWriteId=t.allWrites[t.allWrites.length-1].writeId:t.lastWriteId=-1}function PI(t){return t.visible}function my(t,e,n){let r=At.empty();for(let i=0;i{r=r.updateImmediateChild(s,o)}),r;if(n){const s=jn(t.visibleWrites,e);return n.forEachChild(we,(o,l)=>{const a=di(jn(s,new le(o)),l);r=r.updateImmediateChild(o,a)}),up(s).forEach(o=>{r=r.updateImmediateChild(o.name,o.node)}),r}else{const s=jn(t.visibleWrites,e);return up(s).forEach(o=>{r=r.updateImmediateChild(o.name,o.node)}),r}}function RI(t,e,n,r,i){N(r||i,"Either existingEventSnap or existingServerSnap must exist");const s=_e(e,n);if(sc(t.visibleWrites,s))return null;{const o=jn(t.visibleWrites,s);return oc(o)?i.getChild(n):di(o,i.getChild(n))}}function AI(t,e,n,r){const i=_e(e,n),s=Er(t.visibleWrites,i);if(s!=null)return s;if(r.isCompleteForChild(n)){const o=jn(t.visibleWrites,i);return di(o,r.getNode().getImmediateChild(n))}else return null}function OI(t,e){return Er(t.visibleWrites,e)}function DI(t,e,n,r,i,s,o){let l;const a=jn(t.visibleWrites,e),u=Er(a,ee());if(u!=null)l=u;else if(n!=null)l=di(a,n);else return[];if(l=l.withIndex(o),!l.isEmpty()&&!l.isLeafNode()){const h=[],d=o.getCompare(),f=s?l.getReverseIteratorFrom(r,o):l.getIteratorFrom(r,o);let v=f.getNext();for(;v&&h.length0||!t.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(dy(vl(e)))}}function wy(t,e,n,r,i,s){const o=e.eventCache;if(_l(r,n)!=null)return e;{let l,a;if(H(n))if(N(e.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),e.serverCache.isFiltered()){const u=gr(e),h=u instanceof B?u:B.EMPTY_NODE,d=Fd(r,h);l=t.filter.updateFullNode(e.eventCache.getNode(),d,s)}else{const u=yl(r,gr(e));l=t.filter.updateFullNode(e.eventCache.getNode(),u,s)}else{const u=$(n);if(u===".priority"){N(Wn(n)===1,"Can't have a priority with additional path components");const h=o.getNode();a=e.serverCache.getNode();const d=cp(r,n,h,a);d!=null?l=t.filter.updatePriority(h,d):l=o.getNode()}else{const h=ue(n);let d;if(o.isCompleteForChild(u)){a=e.serverCache.getNode();const f=cp(r,n,o.getNode(),a);f!=null?d=o.getNode().getImmediateChild(u).updateChild(h,f):d=o.getNode().getImmediateChild(u)}else d=Ud(r,u,e.serverCache);d!=null?l=t.filter.updateChild(o.getNode(),u,d,h,i,s):l=o.getNode()}}return Ji(e,l,o.isFullyInitialized()||H(n),t.filter.filtersNodes())}}function wl(t,e,n,r,i,s,o,l){const a=e.serverCache;let u;const h=o?t.filter:t.filter.getIndexedFilter();if(H(n))u=h.updateFullNode(a.getNode(),r,null);else if(h.filtersNodes()&&!a.isFiltered()){const v=a.getNode().updateChild(n,r);u=h.updateFullNode(a.getNode(),v,null)}else{const v=$(n);if(!a.isCompleteForPath(n)&&Wn(n)>1)return e;const w=ue(n),E=a.getNode().getImmediateChild(v).updateChild(w,r);v===".priority"?u=h.updatePriority(a.getNode(),E):u=h.updateChild(a.getNode(),v,E,w,_y,null)}const d=fy(e,u,a.isFullyInitialized()||H(n),h.filtersNodes()),f=new zd(i,d,s);return wy(t,d,n,i,f,l)}function lc(t,e,n,r,i,s,o){const l=e.eventCache;let a,u;const h=new zd(i,e,s);if(H(n))u=t.filter.updateFullNode(e.eventCache.getNode(),r,o),a=Ji(e,u,!0,t.filter.filtersNodes());else{const d=$(n);if(d===".priority")u=t.filter.updatePriority(e.eventCache.getNode(),r),a=Ji(e,u,l.isFullyInitialized(),l.isFiltered());else{const f=ue(n),v=l.getNode().getImmediateChild(d);let w;if(H(f))w=r;else{const _=h.getCompleteChild(d);_!=null?Pd(f)===".priority"&&_.getChild(iy(f)).isEmpty()?w=_:w=_.updateChild(f,r):w=B.EMPTY_NODE}if(v.equals(w))a=e;else{const _=t.filter.updateChild(l.getNode(),d,w,f,h,o);a=Ji(e,_,l.isFullyInitialized(),t.filter.filtersNodes())}}}return a}function dp(t,e){return t.eventCache.isCompleteForChild(e)}function $I(t,e,n,r,i,s,o){let l=e;return r.foreach((a,u)=>{const h=_e(n,a);dp(e,$(h))&&(l=lc(t,l,h,u,i,s,o))}),r.foreach((a,u)=>{const h=_e(n,a);dp(e,$(h))||(l=lc(t,l,h,u,i,s,o))}),l}function hp(t,e,n){return n.foreach((r,i)=>{e=e.updateChild(r,i)}),e}function ac(t,e,n,r,i,s,o,l){if(e.serverCache.getNode().isEmpty()&&!e.serverCache.isFullyInitialized())return e;let a=e,u;H(n)?u=r:u=new ae(null).setTree(n,r);const h=e.serverCache.getNode();return u.children.inorderTraversal((d,f)=>{if(h.hasChild(d)){const v=e.serverCache.getNode().getImmediateChild(d),w=hp(t,v,f);a=wl(t,a,new le(d),w,i,s,o,l)}}),u.children.inorderTraversal((d,f)=>{const v=!e.serverCache.isCompleteForChild(d)&&f.value===null;if(!h.hasChild(d)&&!v){const w=e.serverCache.getNode().getImmediateChild(d),_=hp(t,w,f);a=wl(t,a,new le(d),_,i,s,o,l)}}),a}function VI(t,e,n,r,i,s,o){if(_l(i,n)!=null)return e;const l=e.serverCache.isFiltered(),a=e.serverCache;if(r.value!=null){if(H(n)&&a.isFullyInitialized()||a.isCompleteForPath(n))return wl(t,e,n,a.getNode().getChild(n),i,s,l,o);if(H(n)){let u=new ae(null);return a.getNode().forEachChild(Qr,(h,d)=>{u=u.set(new le(h),d)}),ac(t,e,n,u,i,s,l,o)}else return e}else{let u=new ae(null);return r.foreach((h,d)=>{const f=_e(n,h);a.isCompleteForPath(f)&&(u=u.set(h,a.getNode().getChild(f)))}),ac(t,e,n,u,i,s,l,o)}}function HI(t,e,n,r,i){const s=e.serverCache,o=fy(e,s.getNode(),s.isFullyInitialized()||H(n),s.isFiltered());return wy(t,o,n,r,_y,i)}function GI(t,e,n,r,i,s){let o;if(_l(r,n)!=null)return e;{const l=new zd(r,e,i),a=e.eventCache.getNode();let u;if(H(n)||$(n)===".priority"){let h;if(e.serverCache.isFullyInitialized())h=yl(r,gr(e));else{const d=e.serverCache.getNode();N(d instanceof B,"serverChildren would be complete if leaf node"),h=Fd(r,d)}h=h,u=t.filter.updateFullNode(a,h,s)}else{const h=$(n);let d=Ud(r,h,e.serverCache);d==null&&e.serverCache.isCompleteForChild(h)&&(d=a.getImmediateChild(h)),d!=null?u=t.filter.updateChild(a,h,d,ue(n),l,s):e.eventCache.getNode().hasChild(h)?u=t.filter.updateChild(a,h,B.EMPTY_NODE,ue(n),l,s):u=a,u.isEmpty()&&e.serverCache.isFullyInitialized()&&(o=yl(r,gr(e)),o.isLeafNode()&&(u=t.filter.updateFullNode(u,o,s)))}return o=e.serverCache.isFullyInitialized()||_l(r,ee())!=null,Ji(e,u,o,t.filter.filtersNodes())}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class qI{constructor(e,n){this.query_=e,this.eventRegistrations_=[];const r=this.query_._queryParams,i=new Od(r.getIndex()),s=dI(r);this.processor_=UI(s);const o=n.serverCache,l=n.eventCache,a=i.updateFullNode(B.EMPTY_NODE,o.getNode(),null),u=s.updateFullNode(B.EMPTY_NODE,l.getNode(),null),h=new $n(a,o.isFullyInitialized(),i.filtersNodes()),d=new $n(u,l.isFullyInitialized(),s.filtersNodes());this.viewCache_=Yl(d,h),this.eventGenerator_=new yI(this.query_)}get query(){return this.query_}}function KI(t){return t.viewCache_.serverCache.getNode()}function QI(t){return vl(t.viewCache_)}function YI(t,e){const n=gr(t.viewCache_);return n&&(t.query._queryParams.loadsAllData()||!H(e)&&!n.getImmediateChild($(e)).isEmpty())?n.getChild(e):null}function fp(t){return t.eventRegistrations_.length===0}function JI(t,e){t.eventRegistrations_.push(e)}function pp(t,e,n){const r=[];if(n){N(e==null,"A cancel should cancel all event registrations.");const i=t.query._path;t.eventRegistrations_.forEach(s=>{const o=s.createCancelEvent(n,i);o&&r.push(o)})}if(e){let i=[];for(let s=0;s{r.push(ui(s,o))}),n.isFullyInitialized()&&r.push(dy(n.getNode())),Sy(t,r,n.getNode(),e)}function Sy(t,e,n,r){const i=r?[r]:t.eventRegistrations_;return _I(t.eventGenerator_,e,n,i)}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */let Sl;class Cy{constructor(){this.views=new Map}}function ZI(t){N(!Sl,"__referenceConstructor has already been defined"),Sl=t}function ek(){return N(Sl,"Reference.ts has not been loaded"),Sl}function tk(t){return t.views.size===0}function Bd(t,e,n,r){const i=e.source.queryId;if(i!==null){const s=t.views.get(i);return N(s!=null,"SyncTree gave us an op for an invalid query."),mp(s,e,n,r)}else{let s=[];for(const o of t.views.values())s=s.concat(mp(o,e,n,r));return s}}function Ey(t,e,n,r,i){const s=e._queryIdentifier,o=t.views.get(s);if(!o){let l=yl(n,i?r:null),a=!1;l?a=!0:r instanceof B?(l=Fd(n,r),a=!1):(l=B.EMPTY_NODE,a=!1);const u=Yl(new $n(l,a,!1),new $n(r,i,!1));return new qI(e,u)}return o}function nk(t,e,n,r,i,s){const o=Ey(t,e,r,i,s);return t.views.has(e._queryIdentifier)||t.views.set(e._queryIdentifier,o),JI(o,n),XI(o,n)}function rk(t,e,n,r){const i=e._queryIdentifier,s=[];let o=[];const l=Vn(t);if(i==="default")for(const[a,u]of t.views.entries())o=o.concat(pp(u,n,r)),fp(u)&&(t.views.delete(a),u.query._queryParams.loadsAllData()||s.push(u.query));else{const a=t.views.get(i);a&&(o=o.concat(pp(a,n,r)),fp(a)&&(t.views.delete(i),a.query._queryParams.loadsAllData()||s.push(a.query)))}return l&&!Vn(t)&&s.push(new(ek())(e._repo,e._path)),{removed:s,events:o}}function xy(t){const e=[];for(const n of t.views.values())n.query._queryParams.loadsAllData()||e.push(n);return e}function Fn(t,e){let n=null;for(const r of t.views.values())n=n||YI(r,e);return n}function Iy(t,e){if(e._queryParams.loadsAllData())return Xl(t);{const r=e._queryIdentifier;return t.views.get(r)}}function ky(t,e){return Iy(t,e)!=null}function Vn(t){return Xl(t)!=null}function Xl(t){for(const e of t.views.values())if(e.query._queryParams.loadsAllData())return e;return null}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */let Cl;function ik(t){N(!Cl,"__referenceConstructor has already been defined"),Cl=t}function sk(){return N(Cl,"Reference.ts has not been loaded"),Cl}let ok=1;class gp{constructor(e){this.listenProvider_=e,this.syncPointTree_=new ae(null),this.pendingWriteTree_=LI(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Ty(t,e,n,r,i){return EI(t.pendingWriteTree_,e,n,r,i),i?Si(t,new mr(Ld(),e,n)):[]}function lk(t,e,n,r){xI(t.pendingWriteTree_,e,n,r);const i=ae.fromObject(n);return Si(t,new ci(Ld(),e,i))}function In(t,e,n=!1){const r=II(t.pendingWriteTree_,e);if(kI(t.pendingWriteTree_,e)){let s=new ae(null);return r.snap!=null?s=s.set(ee(),!0):ze(r.children,o=>{s=s.set(new le(o),!0)}),Si(t,new gl(r.path,s,n))}else return[]}function Vs(t,e,n){return Si(t,new mr(Md(),e,n))}function ak(t,e,n){const r=ae.fromObject(n);return Si(t,new ci(Md(),e,r))}function uk(t,e){return Si(t,new Ts(Md(),e))}function ck(t,e,n){const r=$d(t,n);if(r){const i=Vd(r),s=i.path,o=i.queryId,l=Ke(s,e),a=new Ts(jd(o),l);return Hd(t,s,a)}else return[]}function El(t,e,n,r,i=!1){const s=e._path,o=t.syncPointTree_.get(s);let l=[];if(o&&(e._queryIdentifier==="default"||ky(o,e))){const a=rk(o,e,n,r);tk(o)&&(t.syncPointTree_=t.syncPointTree_.remove(s));const u=a.removed;if(l=a.events,!i){const h=u.findIndex(f=>f._queryParams.loadsAllData())!==-1,d=t.syncPointTree_.findOnPath(s,(f,v)=>Vn(v));if(h&&!d){const f=t.syncPointTree_.subtree(s);if(!f.isEmpty()){const v=fk(f);for(let w=0;w0&&!r&&(h?t.listenProvider_.stopListening(Zi(e),null):u.forEach(f=>{const v=t.queryToTagMap.get(Zl(f));t.listenProvider_.stopListening(Zi(f),v)}))}pk(t,u)}return l}function by(t,e,n,r){const i=$d(t,r);if(i!=null){const s=Vd(i),o=s.path,l=s.queryId,a=Ke(o,e),u=new mr(jd(l),a,n);return Hd(t,o,u)}else return[]}function dk(t,e,n,r){const i=$d(t,r);if(i){const s=Vd(i),o=s.path,l=s.queryId,a=Ke(o,e),u=ae.fromObject(n),h=new ci(jd(l),a,u);return Hd(t,o,h)}else return[]}function uc(t,e,n,r=!1){const i=e._path;let s=null,o=!1;t.syncPointTree_.foreachOnPath(i,(f,v)=>{const w=Ke(f,i);s=s||Fn(v,w),o=o||Vn(v)});let l=t.syncPointTree_.get(i);l?(o=o||Vn(l),s=s||Fn(l,ee())):(l=new Cy,t.syncPointTree_=t.syncPointTree_.set(i,l));let a;s!=null?a=!0:(a=!1,s=B.EMPTY_NODE,t.syncPointTree_.subtree(i).foreachChild((v,w)=>{const _=Fn(w,ee());_&&(s=s.updateImmediateChild(v,_))}));const u=ky(l,e);if(!u&&!e._queryParams.loadsAllData()){const f=Zl(e);N(!t.queryToTagMap.has(f),"View does not exist, but we have a tag");const v=mk();t.queryToTagMap.set(f,v),t.tagToQueryMap.set(v,f)}const h=Jl(t.pendingWriteTree_,i);let d=nk(l,e,n,h,s,a);if(!u&&!o&&!r){const f=Iy(l,e);d=d.concat(gk(t,e,f))}return d}function Wd(t,e,n){const i=t.pendingWriteTree_,s=t.syncPointTree_.findOnPath(e,(o,l)=>{const a=Ke(o,e),u=Fn(l,a);if(u)return u});return gy(i,e,s,n,!0)}function hk(t,e){const n=e._path;let r=null;t.syncPointTree_.foreachOnPath(n,(u,h)=>{const d=Ke(u,n);r=r||Fn(h,d)});let i=t.syncPointTree_.get(n);i?r=r||Fn(i,ee()):(i=new Cy,t.syncPointTree_=t.syncPointTree_.set(n,i));const s=r!=null,o=s?new $n(r,!0,!1):null,l=Jl(t.pendingWriteTree_,e._path),a=Ey(i,e,l,s?o.getNode():B.EMPTY_NODE,s);return QI(a)}function Si(t,e){return Py(e,t.syncPointTree_,null,Jl(t.pendingWriteTree_,ee()))}function Py(t,e,n,r){if(H(t.path))return Ny(t,e,n,r);{const i=e.get(ee());n==null&&i!=null&&(n=Fn(i,ee()));let s=[];const o=$(t.path),l=t.operationForChild(o),a=e.children.get(o);if(a&&l){const u=n?n.getImmediateChild(o):null,h=vy(r,o);s=s.concat(Py(l,a,u,h))}return i&&(s=s.concat(Bd(i,t,r,n))),s}}function Ny(t,e,n,r){const i=e.get(ee());n==null&&i!=null&&(n=Fn(i,ee()));let s=[];return e.children.inorderTraversal((o,l)=>{const a=n?n.getImmediateChild(o):null,u=vy(r,o),h=t.operationForChild(o);h&&(s=s.concat(Ny(h,l,a,u)))}),i&&(s=s.concat(Bd(i,t,r,n))),s}function Ry(t,e){const n=e.query,r=bs(t,n);return{hashFn:()=>(KI(e)||B.EMPTY_NODE).hash(),onComplete:i=>{if(i==="ok")return r?ck(t,n._path,r):uk(t,n._path);{const s=ux(i,n);return El(t,n,null,s)}}}}function bs(t,e){const n=Zl(e);return t.queryToTagMap.get(n)}function Zl(t){return t._path.toString()+"$"+t._queryIdentifier}function $d(t,e){return t.tagToQueryMap.get(e)}function Vd(t){const e=t.indexOf("$");return N(e!==-1&&e{if(n&&Vn(n))return[Xl(n)];{let i=[];return n&&(i=xy(n)),ze(r,(s,o)=>{i=i.concat(o)}),i}})}function Zi(t){return t._queryParams.loadsAllData()&&!t._queryParams.isDefault()?new(sk())(t._repo,t._path):t}function pk(t,e){for(let n=0;n{if(!H(u)&&h&&Vn(h))return[Xl(h).query];{let f=[];return h&&(f=f.concat(xy(h).map(v=>v.query))),ze(d,(v,w)=>{f=f.concat(w)}),f}});for(let u=0;u{const u=Kd(a,e.getImmediateChild(l),n);u!==a&&(s=s.updateImmediateChild(l,u))}),s}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Qd{constructor(e="",n=null,r={children:{},childCount:0}){this.name=e,this.parent=n,this.node=r}}function Yd(t,e){let n=e instanceof le?e:new le(e),r=t,i=$(n);for(;i!==null;){const s=oi(r.node.children,i)||{children:{},childCount:0};r=new Qd(i,r,s),n=ue(n),i=$(n)}return r}function Ci(t){return t.node.value}function Dy(t,e){t.node.value=e,cc(t)}function Ly(t){return t.node.childCount>0}function wk(t){return Ci(t)===void 0&&!Ly(t)}function ea(t,e){ze(t.node.children,(n,r)=>{e(new Qd(n,t,r))})}function My(t,e,n,r){n&&e(t),ea(t,i=>{My(i,e,!0)})}function Sk(t,e,n){let r=t.parent;for(;r!==null;){if(e(r))return!0;r=r.parent}return!1}function Hs(t){return new le(t.parent===null?t.name:Hs(t.parent)+"/"+t.name)}function cc(t){t.parent!==null&&Ck(t.parent,t.name,t)}function Ck(t,e,n){const r=wk(n),i=Bt(t.node.children,e);r&&i?(delete t.node.children[e],t.node.childCount--,cc(t)):!r&&!i&&(t.node.children[e]=n.node,t.node.childCount++,cc(t))}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Ek=/[\[\].#$\/\u0000-\u001F\u007F]/,xk=/[\[\].#$\u0000-\u001F\u007F]/,Qa=10*1024*1024,Jd=function(t){return typeof t=="string"&&t.length!==0&&!Ek.test(t)},jy=function(t){return typeof t=="string"&&t.length!==0&&!xk.test(t)},Ik=function(t){return t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),jy(t)},kk=function(t){return t===null||typeof t=="string"||typeof t=="number"&&!xd(t)||t&&typeof t=="object"&&Bt(t,".sv")},Tk=function(t,e,n,r){ta(ql(t,"value"),e,n)},ta=function(t,e,n){const r=n instanceof le?new $x(n,t):n;if(e===void 0)throw new Error(t+"contains undefined "+er(r));if(typeof e=="function")throw new Error(t+"contains a function "+er(r)+" with contents = "+e.toString());if(xd(e))throw new Error(t+"contains "+e.toString()+" "+er(r));if(typeof e=="string"&&e.length>Qa/3&&Kl(e)>Qa)throw new Error(t+"contains a string greater than "+Qa+" utf8 bytes "+er(r)+" ('"+e.substring(0,50)+"...')");if(e&&typeof e=="object"){let i=!1,s=!1;if(ze(e,(o,l)=>{if(o===".value")i=!0;else if(o!==".priority"&&o!==".sv"&&(s=!0,!Jd(o)))throw new Error(t+" contains an invalid key ("+o+") "+er(r)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);Vx(r,o),ta(t,l,r),Hx(r)}),i&&s)throw new Error(t+' contains ".value" child '+er(r)+" in addition to actual children.")}},bk=function(t,e){let n,r;for(n=0;n{const a=new le(o);if(ta(i,l,_e(n,a)),Pd(a)===".priority"&&!kk(l))throw new Error(i+"contains an invalid value for '"+a.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(a)}),bk(i,s)},Fy=function(t,e,n,r){if(!jy(n))throw new Error(ql(t,e)+'was an invalid path = "'+n+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},Nk=function(t,e,n,r){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),Fy(t,e,n)},Uy=function(t,e){if($(e)===".info")throw new Error(t+" failed = Can't modify data under /.info/")},Rk=function(t,e){const n=e.path.toString();if(typeof e.repoInfo.host!="string"||e.repoInfo.host.length===0||!Jd(e.repoInfo.namespace)&&e.repoInfo.host.split(":")[0]!=="localhost"||n.length!==0&&!Ik(n))throw new Error(ql(t,"url")+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)};/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Ak{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function na(t,e){let n=null;for(let r=0;rNd(r,e))}function Ct(t,e,n){na(t,n),By(t,r=>yt(r,e)||yt(e,r))}function By(t,e){t.recursionDepth_++;let n=!0;for(let r=0;r{yp(t,r,i,s,o)},t.authTokenProvider_,t.appCheckProvider_),setTimeout(()=>_p(t,!0),0);else{if(typeof n<"u"&&n!==null){if(typeof n!="object")throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{Ne(n)}catch(r){throw new Error("Invalid authOverride provided: "+r)}}t.persistentConnection_=new Xt(t.repoInfo_,e,(r,i,s,o)=>{yp(t,r,i,s,o)},r=>{_p(t,r)},r=>{Uk(t,r)},t.authTokenProvider_,t.appCheckProvider_,n),t.server_=t.persistentConnection_}t.authTokenProvider_.addTokenChangeListener(r=>{t.server_.refreshAuthToken(r)}),t.appCheckProvider_.addTokenChangeListener(r=>{t.server_.refreshAppCheckToken(r.token)}),t.statsReporter_=yx(t.repoInfo_,()=>new vI(t.stats_,t.server_)),t.infoData_=new hI,t.infoSyncTree_=new gp({startListening:(r,i,s,o)=>{let l=[];const a=t.infoData_.getNode(r._path);return a.isEmpty()||(l=Vs(t.infoSyncTree_,r._path,a),setTimeout(()=>{o("ok")},0)),l},stopListening:()=>{}}),Xd(t,"connected",!1),t.serverSyncTree_=new gp({startListening:(r,i,s,o)=>(t.server_.listen(r,s,i,(l,a)=>{const u=o(l,a);Ct(t.eventQueue_,r._path,u)}),[]),stopListening:(r,i)=>{t.server_.unlisten(r,i)}})}function Fk(t){const n=t.infoData_.getNode(new le(".info/serverTimeOffset")).val()||0;return new Date().getTime()+n}function ra(t){return vk({timestamp:Fk(t)})}function yp(t,e,n,r,i){t.dataUpdateCount++;const s=new le(e);n=t.interceptServerDataCallback_?t.interceptServerDataCallback_(e,n):n;let o=[];if(i)if(r){const a=al(n,u=>Pe(u));o=dk(t.serverSyncTree_,s,a,i)}else{const a=Pe(n);o=by(t.serverSyncTree_,s,a,i)}else if(r){const a=al(n,u=>Pe(u));o=ak(t.serverSyncTree_,s,a)}else{const a=Pe(n);o=Vs(t.serverSyncTree_,s,a)}let l=s;o.length>0&&(l=hi(t,s)),Ct(t.eventQueue_,l,o)}function _p(t,e){Xd(t,"connected",e),e===!1&&$k(t)}function Uk(t,e){ze(e,(n,r)=>{Xd(t,n,r)})}function Xd(t,e,n){const r=new le("/.info/"+e),i=Pe(n);t.infoData_.updateSnapshot(r,i);const s=Vs(t.infoSyncTree_,r,i);Ct(t.eventQueue_,r,s)}function Zd(t){return t.nextWriteId_++}function zk(t,e,n){const r=hk(t.serverSyncTree_,e);return r!=null?Promise.resolve(r):t.server_.get(e).then(i=>{const s=Pe(i).withIndex(e._queryParams.getIndex());uc(t.serverSyncTree_,e,n,!0);let o;if(e._queryParams.loadsAllData())o=Vs(t.serverSyncTree_,e._path,s);else{const l=bs(t.serverSyncTree_,e);o=by(t.serverSyncTree_,e._path,s,l)}return Ct(t.eventQueue_,e._path,o),El(t.serverSyncTree_,e,n,null,!0),s},i=>(Gs(t,"get for query "+Ne(e)+" failed: "+i),Promise.reject(new Error(i))))}function Bk(t,e,n,r,i){Gs(t,"set",{path:e.toString(),value:n,priority:r});const s=ra(t),o=Pe(n,r),l=Wd(t.serverSyncTree_,e),a=Oy(o,l,s),u=Zd(t),h=Ty(t.serverSyncTree_,e,a,u,!0);na(t.eventQueue_,h),t.server_.put(e.toString(),o.val(!0),(f,v)=>{const w=f==="ok";w||Ye("set at "+e+" failed: "+f);const _=In(t.serverSyncTree_,u,!w);Ct(t.eventQueue_,e,_),dc(t,i,f,v)});const d=th(t,e);hi(t,d),Ct(t.eventQueue_,d,[])}function Wk(t,e,n,r){Gs(t,"update",{path:e.toString(),value:n});let i=!0;const s=ra(t),o={};if(ze(n,(l,a)=>{i=!1,o[l]=Ay(_e(e,l),Pe(a),t.serverSyncTree_,s)}),i)je("update() called with empty data. Don't do anything."),dc(t,r,"ok",void 0);else{const l=Zd(t),a=lk(t.serverSyncTree_,e,o,l);na(t.eventQueue_,a),t.server_.merge(e.toString(),n,(u,h)=>{const d=u==="ok";d||Ye("update at "+e+" failed: "+u);const f=In(t.serverSyncTree_,l,!d),v=f.length>0?hi(t,e):e;Ct(t.eventQueue_,v,f),dc(t,r,u,h)}),ze(n,u=>{const h=th(t,_e(e,u));hi(t,h)}),Ct(t.eventQueue_,e,[])}}function $k(t){Gs(t,"onDisconnectEvents");const e=ra(t),n=ml();rc(t.onDisconnect_,ee(),(i,s)=>{const o=Ay(i,s,t.serverSyncTree_,e);hy(n,i,o)});let r=[];rc(n,ee(),(i,s)=>{r=r.concat(Vs(t.serverSyncTree_,i,s));const o=th(t,i);hi(t,o)}),t.onDisconnect_=ml(),Ct(t.eventQueue_,ee(),r)}function Vk(t,e,n){let r;$(e._path)===".info"?r=uc(t.infoSyncTree_,e,n):r=uc(t.serverSyncTree_,e,n),zy(t.eventQueue_,e._path,r)}function Hk(t,e,n){let r;$(e._path)===".info"?r=El(t.infoSyncTree_,e,n):r=El(t.serverSyncTree_,e,n),zy(t.eventQueue_,e._path,r)}function Gk(t){t.persistentConnection_&&t.persistentConnection_.interrupt(Dk)}function Gs(t,...e){let n="";t.persistentConnection_&&(n=t.persistentConnection_.id+":"),je(n,...e)}function dc(t,e,n,r){e&&wi(()=>{if(n==="ok")e(null);else{const i=(n||"error").toUpperCase();let s=i;r&&(s+=": "+r);const o=new Error(s);o.code=i,e(o)}})}function Wy(t,e,n){return Wd(t.serverSyncTree_,e,n)||B.EMPTY_NODE}function eh(t,e=t.transactionQueueTree_){if(e||ia(t,e),Ci(e)){const n=Vy(t,e);N(n.length>0,"Sending zero length transaction queue"),n.every(i=>i.status===0)&&qk(t,Hs(e),n)}else Ly(e)&&ea(e,n=>{eh(t,n)})}function qk(t,e,n){const r=n.map(u=>u.currentWriteId),i=Wy(t,e,r);let s=i;const o=i.hash();for(let u=0;u{Gs(t,"transaction put response",{path:a.toString(),status:u});let h=[];if(u==="ok"){const d=[];for(let f=0;fn[f].onComplete(null,!0,n[f].currentOutputSnapshotResolved)),n[f].unwatcher();ia(t,Yd(t.transactionQueueTree_,e)),eh(t,t.transactionQueueTree_),Ct(t.eventQueue_,e,h);for(let f=0;fl.status===0).map(l=>l.currentWriteId);for(let l=0;l=Lk)h=!0,d="maxretry",i=i.concat(In(t.serverSyncTree_,a.currentWriteId,!0));else{const f=Wy(t,a.path,o);a.currentInputSnapshot=f;const v=e[l].update(f.val());if(v!==void 0){ta("transaction failed: Data returned ",v,a.path);let w=Pe(v);typeof v=="object"&&v!=null&&Bt(v,".priority")||(w=w.updatePriority(f.getPriority()));const E=a.currentWriteId,g=ra(t),p=Oy(w,f,g);a.currentOutputSnapshotRaw=w,a.currentOutputSnapshotResolved=p,a.currentWriteId=Zd(t),o.splice(o.indexOf(E),1),i=i.concat(Ty(t.serverSyncTree_,a.path,p,a.currentWriteId,a.applyLocally)),i=i.concat(In(t.serverSyncTree_,E,!0))}else h=!0,d="nodata",i=i.concat(In(t.serverSyncTree_,a.currentWriteId,!0))}Ct(t.eventQueue_,n,i),i=[],h&&(e[l].status=2,function(f){setTimeout(f,Math.floor(0))}(e[l].unwatcher),e[l].onComplete&&(d==="nodata"?r.push(()=>e[l].onComplete(null,!1,e[l].currentInputSnapshot)):r.push(()=>e[l].onComplete(new Error(d),!1,null))))}ia(t,t.transactionQueueTree_);for(let l=0;lr.order-i.order),n}function Hy(t,e,n){const r=Ci(e);if(r)for(let i=0;i{Hy(t,i,n)})}function ia(t,e){const n=Ci(e);if(n){let r=0;for(let i=0;i0?n:void 0)}ea(e,r=>{ia(t,r)})}function th(t,e){const n=Hs($y(t,e)),r=Yd(t.transactionQueueTree_,e);return Sk(r,i=>{Ya(t,i)}),Ya(t,r),My(r,i=>{Ya(t,i)}),n}function Ya(t,e){const n=Ci(e);if(n){const r=[];let i=[],s=-1;for(let o=0;o0){let i=n[r];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch{}e+="/"+i}return e}function Yk(t){const e={};t.charAt(0)==="?"&&(t=t.substring(1));for(const n of t.split("&")){if(n.length===0)continue;const r=n.split("=");r.length===2?e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):Ye(`Invalid query segment '${n}' in query '${t}'`)}return e}const wp=function(t,e){const n=Jk(t),r=n.namespace;n.domain==="firebase.com"&&sn(n.host+" is no longer supported. Please use .firebaseio.com instead"),(!r||r==="undefined")&&n.domain!=="localhost"&&sn("Cannot parse Firebase url. Please use https://.firebaseio.com"),n.secure||ix();const i=n.scheme==="ws"||n.scheme==="wss";return{repoInfo:new Qv(n.host,n.secure,r,i,e,"",r!==n.subdomain),path:new le(n.pathString)}},Jk=function(t){let e="",n="",r="",i="",s="",o=!0,l="https",a=443;if(typeof t=="string"){let u=t.indexOf("//");u>=0&&(l=t.substring(0,u-1),t=t.substring(u+2));let h=t.indexOf("/");h===-1&&(h=t.length);let d=t.indexOf("?");d===-1&&(d=t.length),e=t.substring(0,Math.min(h,d)),h=0?(o=l==="https"||l==="wss",a=parseInt(e.substring(u+1),10)):u=e.length;const v=e.slice(0,u);if(v.toLowerCase()==="localhost")n="localhost";else if(v.split(".").length<=2)n=v;else{const w=e.indexOf(".");r=e.substring(0,w).toLowerCase(),n=e.substring(w+1),s=r}"ns"in f&&(s=f.ns)}return{host:e,port:a,domain:n,subdomain:r,secure:o,scheme:l,pathString:i,namespace:s}};/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Xk{constructor(e,n,r,i){this.eventType=e,this.eventRegistration=n,this.snapshot=r,this.prevName=i}getPath(){const e=this.snapshot.ref;return this.eventType==="value"?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+Ne(this.snapshot.exportVal())}}class Zk{constructor(e,n,r){this.eventRegistration=e,this.error=n,this.path=r}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Gy{constructor(e,n){this.snapshotCallback=e,this.cancelCallback=n}onValue(e,n){this.snapshotCallback.call(null,e,n)}onCancel(e){return N(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||this.snapshotCallback.userCallback!==void 0&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class nh{constructor(e,n,r,i){this._repo=e,this._path=n,this._queryParams=r,this._orderByCalled=i}get key(){return H(this._path)?null:Pd(this._path)}get ref(){return new cn(this._repo,this._path)}get _queryIdentifier(){const e=op(this._queryParams),n=Id(e);return n==="{}"?"default":n}get _queryObject(){return op(this._queryParams)}isEqual(e){if(e=Et(e),!(e instanceof nh))return!1;const n=this._repo===e._repo,r=Nd(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return n&&r&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+Bx(this._path)}}class cn extends nh{constructor(e,n){super(e,n,new Dd,!1)}get parent(){const e=iy(this._path);return e===null?null:new cn(this._repo,e)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}}class Ps{constructor(e,n,r){this._node=e,this.ref=n,this._index=r}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const n=new le(e),r=hc(this.ref,e);return new Ps(this._node.getChild(n),r,we)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(r,i)=>e(new Ps(i,hc(this.ref,r),we)))}hasChild(e){const n=new le(e);return!this._node.getChild(n).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function ne(t,e){return t=Et(t),t._checkNotDeleted("ref"),e!==void 0?hc(t._root,e):t._root}function hc(t,e){return t=Et(t),$(t._path)===null?Nk("child","path",e):Fy("child","path",e),new cn(t._repo,_e(t._path,e))}function vr(t){return Uy("remove",t._path),on(t,null)}function on(t,e){t=Et(t),Uy("set",t._path),Tk("set",e,t._path);const n=new Us;return Bk(t._repo,t._path,e,null,n.wrapCallback(()=>{})),n.promise}function sa(t,e){Pk("update",e,t._path);const n=new Us;return Wk(t._repo,t._path,e,n.wrapCallback(()=>{})),n.promise}function Ns(t){t=Et(t);const e=new Gy(()=>{}),n=new oa(e);return zk(t._repo,t,n).then(r=>new Ps(r,new cn(t._repo,t._path),t._queryParams.getIndex()))}class oa{constructor(e){this.callbackContext=e}respondsTo(e){return e==="value"}createEvent(e,n){const r=n._queryParams.getIndex();return new Xk("value",this,new Ps(e.snapshotNode,new cn(n._repo,n._path),r))}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,n){return this.callbackContext.hasCancelCallback?new Zk(this,e,n):null}matches(e){return e instanceof oa?!e.callbackContext||!this.callbackContext?!0:e.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}}function eT(t,e,n,r,i){const s=new Gy(n,void 0),o=new oa(s);return Vk(t._repo,t,o),()=>Hk(t._repo,t,o)}function xr(t,e,n,r){return eT(t,"value",e)}ZI(cn);ik(cn);/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const tT="FIREBASE_DATABASE_EMULATOR_HOST",fc={};let nT=!1;function rT(t,e,n,r){t.repoInfo_=new Qv(`${e}:${n}`,!1,t.repoInfo_.namespace,t.repoInfo_.webSocketOnly,t.repoInfo_.nodeAdmin,t.repoInfo_.persistenceKey,t.repoInfo_.includeNamespaceInQueryParams,!0),r&&(t.authTokenProvider_=r)}function iT(t,e,n,r,i){let s=r||t.options.databaseURL;s===void 0&&(t.options.projectId||sn("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),je("Using default host for project ",t.options.projectId),s=`${t.options.projectId}-default-rtdb.firebaseio.com`);let o=wp(s,i),l=o.repoInfo,a;typeof process<"u"&&Wf&&(a=Wf[tT]),a?(s=`http://${a}?ns=${l.namespace}`,o=wp(s,i),l=o.repoInfo):o.repoInfo.secure;const u=new mx(t.name,t.options,e);Rk("Invalid Firebase Database URL",o),H(o.path)||sn("Database URL must point to the root of a Firebase Database (not including a child path).");const h=oT(l,t,u,new px(t.name,n));return new lT(h,t)}function sT(t,e){const n=fc[e];(!n||n[t.key]!==t)&&sn(`Database ${e}(${t.repoInfo_}) has already been deleted.`),Gk(t),delete n[t.key]}function oT(t,e,n,r){let i=fc[e.name];i||(i={},fc[e.name]=i);let s=i[t.toURLString()];return s&&sn("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new Mk(t,nT,n,r),i[t.toURLString()]=s,s}class lT{constructor(e,n){this._repoInternal=e,this.app=n,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(jk(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new cn(this._repo,ee())),this._rootInternal}_delete(){return this._rootInternal!==null&&(sT(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&sn("Cannot call "+e+" on a deleted database.")}}function aT(t=Av(),e){const n=Ed(t,"database").getImmediate({identifier:e});if(!n._instanceStarted){const r=IC("database");r&&uT(n,...r)}return n}function uT(t,e,n,r={}){t=Et(t),t._checkNotDeleted("useEmulator"),t._instanceStarted&&sn("Cannot call useEmulator() after instance has already been initialized.");const i=t._repoInternal;let s;if(i.repoInfo_.nodeAdmin)r.mockUserToken&&sn('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 Po(Po.OWNER);else if(r.mockUserToken){const o=typeof r.mockUserToken=="string"?r.mockUserToken:kC(r.mockUserToken,t.app.options.projectId);s=new Po(o)}rT(i,e,n,s)}/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function cT(t){XE(_i),li(new fr("database",(e,{instanceIdentifier:n})=>{const r=e.getProvider("app").getImmediate(),i=e.getProvider("auth-internal"),s=e.getProvider("app-check-internal");return iT(r,i,s,n)},"PUBLIC").setMultipleInstances(!0)),Mn($f,Vf,t),Mn($f,Vf,"esm2017")}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const dT={".sv":"timestamp"};function Sp(){return dT}Xt.prototype.simpleListen=function(t,e){this.sendRequest("q",{p:t},e)};Xt.prototype.echo=function(t,e){this.sendRequest("echo",{d:t},e)};cT();function rh(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i"u")return null;const t=navigator;return t.languages&&t.languages[0]||t.language||null}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class qs{constructor(e,n){this.shortDelay=e,this.longDelay=n,an(n>e,"Short delay should be less than long delay!"),this.isMobile=wd()||Tv()}get(){return mT()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function sh(t,e){an(t.emulator,"Emulator should always be set here");const{url:n}=t.emulator;return e?`${n}${e.startsWith("/")?e.slice(1):e}`:n}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Yy{static initialize(e,n,r){this.fetchImpl=e,n&&(this.headersImpl=n),r&&(this.responseImpl=r)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;Kt("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl)return this.headersImpl;if(typeof self<"u"&&"Headers"in self)return self.Headers;if(typeof globalThis<"u"&&globalThis.Headers)return globalThis.Headers;if(typeof Headers<"u")return Headers;Kt("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl)return this.responseImpl;if(typeof self<"u"&&"Response"in self)return self.Response;if(typeof globalThis<"u"&&globalThis.Response)return globalThis.Response;if(typeof Response<"u")return Response;Kt("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const vT={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"};/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const yT=new qs(3e4,6e4);function la(t,e){return t.tenantId&&!e.tenantId?Object.assign(Object.assign({},e),{tenantId:t.tenantId}):e}async function Ei(t,e,n,r,i={}){return Jy(t,i,async()=>{let s={},o={};r&&(e==="GET"?o=r:s={body:JSON.stringify(r)});const l=yi(Object.assign({key:t.config.apiKey},o)).slice(1),a=await t._getAdditionalHeaders();a["Content-Type"]="application/json",t.languageCode&&(a["X-Firebase-Locale"]=t.languageCode);const u=Object.assign({method:e,headers:a},s);return TC()||(u.referrerPolicy="no-referrer"),Yy.fetch()(Zy(t,t.config.apiHost,n,l),u)})}async function Jy(t,e,n){t._canInitEmulator=!1;const r=Object.assign(Object.assign({},vT),e);try{const i=new _T(t),s=await Promise.race([n(),i.promise]);i.clearNetworkTimeout();const o=await s.json();if("needConfirmation"in o)throw go(t,"account-exists-with-different-credential",o);if(s.ok&&!("errorMessage"in o))return o;{const l=s.ok?o.errorMessage:o.error.message,[a,u]=l.split(" : ");if(a==="FEDERATED_USER_ID_ALREADY_LINKED")throw go(t,"credential-already-in-use",o);if(a==="EMAIL_EXISTS")throw go(t,"email-already-in-use",o);if(a==="USER_DISABLED")throw go(t,"user-disabled",o);const h=r[a]||a.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw Qy(t,h,u);ln(t,h)}}catch(i){if(i instanceof Yn)throw i;ln(t,"network-request-failed",{message:String(i)})}}async function Xy(t,e,n,r,i={}){const s=await Ei(t,e,n,r,i);return"mfaPendingCredential"in s&&ln(t,"multi-factor-auth-required",{_serverResponse:s}),s}function Zy(t,e,n,r){const i=`${e}${n}?${r}`;return t.config.emulator?sh(t.config,i):`${t.config.apiScheme}://${i}`}class _T{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((n,r)=>{this.timer=setTimeout(()=>r(Ut(this.auth,"network-request-failed")),yT.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function go(t,e,n){const r={appName:t.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=Ut(t,e,r);return i.customData._tokenResponse=n,i}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function wT(t,e){return Ei(t,"POST","/v1/accounts:delete",e)}async function e_(t,e){return Ei(t,"POST","/v1/accounts:lookup",e)}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function es(t){if(t)try{const e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function ST(t,e=!1){const n=Et(t),r=await n.getIdToken(e),i=oh(r);W(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");const s=typeof i.firebase=="object"?i.firebase:void 0,o=s==null?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:es(Ja(i.auth_time)),issuedAtTime:es(Ja(i.iat)),expirationTime:es(Ja(i.exp)),signInProvider:o||null,signInSecondFactor:(s==null?void 0:s.sign_in_second_factor)||null}}function Ja(t){return Number(t)*1e3}function oh(t){const[e,n,r]=t.split(".");if(e===void 0||n===void 0||r===void 0)return No("JWT malformed, contained fewer than 3 sections"),null;try{const i=ll(n);return i?JSON.parse(i):(No("Failed to decode base64 JWT payload"),null)}catch(i){return No("Caught error parsing JWT payload as JSON",i==null?void 0:i.toString()),null}}function Ep(t){const e=oh(t);return W(e,"internal-error"),W(typeof e.exp<"u","internal-error"),W(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function Rs(t,e,n=!1){if(n)return e;try{return await e}catch(r){throw r instanceof Yn&&CT(r)&&t.auth.currentUser===t&&await t.auth.signOut(),r}}function CT({code:t}){return t==="auth/user-disabled"||t==="auth/user-token-expired"}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class ET{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,this.timerId!==null&&clearTimeout(this.timerId))}getInterval(e){var n;if(e){const r=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),r}else{this.errorBackoff=3e4;const i=((n=this.user.stsTokenManager.expirationTime)!==null&&n!==void 0?n:0)-Date.now()-3e5;return Math.max(0,i)}}schedule(e=!1){if(!this.isRunning)return;const n=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},n)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){(e==null?void 0:e.code)==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class mc{constructor(e,n){this.createdAt=e,this.lastLoginAt=n,this._initializeTime()}_initializeTime(){this.lastSignInTime=es(this.lastLoginAt),this.creationTime=es(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function Il(t){var e;const n=t.auth,r=await t.getIdToken(),i=await Rs(t,e_(n,{idToken:r}));W(i==null?void 0:i.users.length,n,"internal-error");const s=i.users[0];t._notifyReloadListener(s);const o=!((e=s.providerUserInfo)===null||e===void 0)&&e.length?t_(s.providerUserInfo):[],l=IT(t.providerData,o),a=t.isAnonymous,u=!(t.email&&s.passwordHash)&&!(l!=null&&l.length),h=a?u:!1,d={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:l,metadata:new mc(s.createdAt,s.lastLoginAt),isAnonymous:h};Object.assign(t,d)}async function xT(t){const e=Et(t);await Il(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function IT(t,e){return[...t.filter(r=>!e.some(i=>i.providerId===r.providerId)),...e]}function t_(t){return t.map(e=>{var{providerId:n}=e,r=rh(e,["providerId"]);return{providerId:n,uid:r.rawId||"",displayName:r.displayName||null,email:r.email||null,phoneNumber:r.phoneNumber||null,photoURL:r.photoUrl||null}})}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function kT(t,e){const n=await Jy(t,{},async()=>{const r=yi({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:i,apiKey:s}=t.config,o=Zy(t,i,"/v1/token",`key=${s}`),l=await t._getAdditionalHeaders();return l["Content-Type"]="application/x-www-form-urlencoded",Yy.fetch()(o,{method:"POST",headers:l,body:r})});return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function TT(t,e){return Ei(t,"POST","/v2/accounts:revokeToken",la(t,e))}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Yr{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){W(e.idToken,"internal-error"),W(typeof e.idToken<"u","internal-error"),W(typeof e.refreshToken<"u","internal-error");const n="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):Ep(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}updateFromIdToken(e){W(e.length!==0,"internal-error");const n=Ep(e);this.updateTokensAndExpiration(e,null,n)}async getToken(e,n=!1){return!n&&this.accessToken&&!this.isExpired?this.accessToken:(W(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(e,n){const{accessToken:r,refreshToken:i,expiresIn:s}=await kT(e,n);this.updateTokensAndExpiration(r,i,Number(s))}updateTokensAndExpiration(e,n,r){this.refreshToken=n||null,this.accessToken=e||null,this.expirationTime=Date.now()+r*1e3}static fromJSON(e,n){const{refreshToken:r,accessToken:i,expirationTime:s}=n,o=new Yr;return r&&(W(typeof r=="string","internal-error",{appName:e}),o.refreshToken=r),i&&(W(typeof i=="string","internal-error",{appName:e}),o.accessToken=i),s&&(W(typeof s=="number","internal-error",{appName:e}),o.expirationTime=s),o}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 Yr,this.toJSON())}_performRefresh(){return Kt("not implemented")}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function hn(t,e){W(typeof t=="string"||typeof t>"u","internal-error",{appName:e})}class Qt{constructor(e){var{uid:n,auth:r,stsTokenManager:i}=e,s=rh(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new ET(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=n,this.auth=r,this.stsTokenManager=i,this.accessToken=i.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new mc(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const n=await Rs(this,this.stsTokenManager.getToken(this.auth,e));return W(n,this.auth,"internal-error"),this.accessToken!==n&&(this.accessToken=n,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),n}getIdTokenResult(e){return ST(this,e)}reload(){return xT(this)}_assign(e){this!==e&&(W(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(n=>Object.assign({},n)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const n=new Qt(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return n.metadata._copy(this.metadata),n}_onReload(e){W(!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,n=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),n&&await Il(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(Gt(this.auth.app))return Promise.reject(Un(this.auth));const e=await this.getIdToken();return await Rs(this,wT(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({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=>Object.assign({},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,n){var r,i,s,o,l,a,u,h;const d=(r=n.displayName)!==null&&r!==void 0?r:void 0,f=(i=n.email)!==null&&i!==void 0?i:void 0,v=(s=n.phoneNumber)!==null&&s!==void 0?s:void 0,w=(o=n.photoURL)!==null&&o!==void 0?o:void 0,_=(l=n.tenantId)!==null&&l!==void 0?l:void 0,E=(a=n._redirectEventId)!==null&&a!==void 0?a:void 0,g=(u=n.createdAt)!==null&&u!==void 0?u:void 0,p=(h=n.lastLoginAt)!==null&&h!==void 0?h:void 0,{uid:m,emailVerified:S,isAnonymous:I,providerData:P,stsTokenManager:b}=n;W(m&&b,e,"internal-error");const A=Yr.fromJSON(this.name,b);W(typeof m=="string",e,"internal-error"),hn(d,e.name),hn(f,e.name),W(typeof S=="boolean",e,"internal-error"),W(typeof I=="boolean",e,"internal-error"),hn(v,e.name),hn(w,e.name),hn(_,e.name),hn(E,e.name),hn(g,e.name),hn(p,e.name);const q=new Qt({uid:m,auth:e,email:f,emailVerified:S,displayName:d,isAnonymous:I,photoURL:w,phoneNumber:v,tenantId:_,stsTokenManager:A,createdAt:g,lastLoginAt:p});return P&&Array.isArray(P)&&(q.providerData=P.map(z=>Object.assign({},z))),E&&(q._redirectEventId=E),q}static async _fromIdTokenResponse(e,n,r=!1){const i=new Yr;i.updateFromServerResponse(n);const s=new Qt({uid:n.localId,auth:e,stsTokenManager:i,isAnonymous:r});return await Il(s),s}static async _fromGetAccountInfoResponse(e,n,r){const i=n.users[0];W(i.localId!==void 0,"internal-error");const s=i.providerUserInfo!==void 0?t_(i.providerUserInfo):[],o=!(i.email&&i.passwordHash)&&!(s!=null&&s.length),l=new Yr;l.updateFromIdToken(r);const a=new Qt({uid:i.localId,auth:e,stsTokenManager:l,isAnonymous:o}),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:s,metadata:new mc(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!(s!=null&&s.length)};return Object.assign(a,u),a}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const xp=new Map;function Yt(t){an(t instanceof Function,"Expected a class definition");let e=xp.get(t);return e?(an(e instanceof t,"Instance stored in cache mismatched with class"),e):(e=new t,xp.set(t,e),e)}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class n_{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,n){this.storage[e]=n}async _get(e){const n=this.storage[e];return n===void 0?null:n}async _remove(e){delete this.storage[e]}_addListener(e,n){}_removeListener(e,n){}}n_.type="NONE";const Ip=n_;/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function Ro(t,e,n){return`firebase:${t}:${e}:${n}`}class Jr{constructor(e,n,r){this.persistence=e,this.auth=n,this.userKey=r;const{config:i,name:s}=this.auth;this.fullUserKey=Ro(this.userKey,i.apiKey,s),this.fullPersistenceKey=Ro("persistence",i.apiKey,s),this.boundEventHandler=n._onStorageEvent.bind(n),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);return e?Qt._fromJSON(this.auth,e):null}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 n=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,n)return this.setCurrentUser(n)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,n,r="authUser"){if(!n.length)return new Jr(Yt(Ip),e,r);const i=(await Promise.all(n.map(async u=>{if(await u._isAvailable())return u}))).filter(u=>u);let s=i[0]||Yt(Ip);const o=Ro(r,e.config.apiKey,e.name);let l=null;for(const u of n)try{const h=await u._get(o);if(h){const d=Qt._fromJSON(e,h);u!==s&&(l=d),s=u;break}}catch{}const a=i.filter(u=>u._shouldAllowMigration);return!s._shouldAllowMigration||!a.length?new Jr(s,e,r):(s=a[0],l&&await s._set(o,l.toJSON()),await Promise.all(n.map(async u=>{if(u!==s)try{await u._remove(o)}catch{}})),new Jr(s,e,r))}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function kp(t){const e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(o_(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(r_(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(a_(e))return"Blackberry";if(u_(e))return"Webos";if(i_(e))return"Safari";if((e.includes("chrome/")||s_(e))&&!e.includes("edge/"))return"Chrome";if(l_(e))return"Android";{const n=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=t.match(n);if((r==null?void 0:r.length)===2)return r[1]}return"Other"}function r_(t=Je()){return/firefox\//i.test(t)}function i_(t=Je()){const e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function s_(t=Je()){return/crios\//i.test(t)}function o_(t=Je()){return/iemobile/i.test(t)}function l_(t=Je()){return/android/i.test(t)}function a_(t=Je()){return/blackberry/i.test(t)}function u_(t=Je()){return/webos/i.test(t)}function lh(t=Je()){return/iphone|ipad|ipod/i.test(t)||/macintosh/i.test(t)&&/mobile/i.test(t)}function bT(t=Je()){var e;return lh(t)&&!!(!((e=window.navigator)===null||e===void 0)&&e.standalone)}function PT(){return PC()&&document.documentMode===10}function c_(t=Je()){return lh(t)||l_(t)||u_(t)||a_(t)||/windows phone/i.test(t)||o_(t)}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function d_(t,e=[]){let n;switch(t){case"Browser":n=kp(Je());break;case"Worker":n=`${kp(Je())}-${t}`;break;default:n=t}const r=e.length?e.join(","):"FirebaseCore-web";return`${n}/JsCore/${_i}/${r}`}/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class NT{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,n){const r=s=>new Promise((o,l)=>{try{const a=e(s);o(a)}catch(a){l(a)}});r.onAbort=n,this.queue.push(r);const i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const n=[];try{for(const r of this.queue)await r(e),r.onAbort&&n.push(r.onAbort)}catch(r){n.reverse();for(const i of n)try{i()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:r==null?void 0:r.message})}}}/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function RT(t,e={}){return Ei(t,"GET","/v2/passwordPolicy",la(t,e))}/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const AT=6;class OT{constructor(e){var n,r,i,s;const o=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=(n=o.minPasswordLength)!==null&&n!==void 0?n:AT,o.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=o.maxPasswordLength),o.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=o.containsLowercaseCharacter),o.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=o.containsUppercaseCharacter),o.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=o.containsNumericCharacter),o.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=o.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=(i=(r=e.allowedNonAlphanumericCharacters)===null||r===void 0?void 0:r.join(""))!==null&&i!==void 0?i:"",this.forceUpgradeOnSignin=(s=e.forceUpgradeOnSignin)!==null&&s!==void 0?s:!1,this.schemaVersion=e.schemaVersion}validatePassword(e){var n,r,i,s,o,l;const a={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,a),this.validatePasswordCharacterOptions(e,a),a.isValid&&(a.isValid=(n=a.meetsMinPasswordLength)!==null&&n!==void 0?n:!0),a.isValid&&(a.isValid=(r=a.meetsMaxPasswordLength)!==null&&r!==void 0?r:!0),a.isValid&&(a.isValid=(i=a.containsLowercaseLetter)!==null&&i!==void 0?i:!0),a.isValid&&(a.isValid=(s=a.containsUppercaseLetter)!==null&&s!==void 0?s:!0),a.isValid&&(a.isValid=(o=a.containsNumericCharacter)!==null&&o!==void 0?o:!0),a.isValid&&(a.isValid=(l=a.containsNonAlphanumericCharacter)!==null&&l!==void 0?l:!0),a}validatePasswordLengthOptions(e,n){const r=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;r&&(n.meetsMinPasswordLength=e.length>=r),i&&(n.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,n){this.updatePasswordCharacterOptionsStatuses(n,!1,!1,!1,!1);let r;for(let i=0;i="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,n,r,i,s){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=n)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=s))}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class DT{constructor(e,n,r,i){this.app=e,this.heartbeatServiceProvider=n,this.appCheckServiceProvider=r,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Tp(this),this.idTokenSubscription=new Tp(this),this.beforeStateQueue=new NT(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=Ky,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion}_initializeWithPersistence(e,n){return n&&(this._popupRedirectResolver=Yt(n)),this._initializationPromise=this.queue(async()=>{var r,i;if(!this._deleted&&(this.persistenceManager=await Jr.create(this,e),!this._deleted)){if(!((r=this._popupRedirectResolver)===null||r===void 0)&&r._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(n),this.lastNotifiedUid=((i=this.currentUser)===null||i===void 0?void 0:i.uid)||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();if(!(!this.currentUser&&!e)){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{const n=await e_(this,{idToken:e}),r=await Qt._fromGetAccountInfoResponse(this,n,e);await this.directlySetCurrentUser(r)}catch(n){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",n),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){var n;if(Gt(this.app)){const o=this.app.settings.authIdToken;return o?new Promise(l=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(o).then(l,l))}):this.directlySetCurrentUser(null)}const r=await this.assertedPersistence.getCurrentUser();let i=r,s=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const o=(n=this.redirectUser)===null||n===void 0?void 0:n._redirectEventId,l=i==null?void 0:i._redirectEventId,a=await this.tryRedirectSignIn(e);(!o||o===l)&&(a!=null&&a.user)&&(i=a.user,s=!0)}if(!i)return this.directlySetCurrentUser(null);if(!i._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(i)}catch(o){i=r,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(o))}return i?this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}return W(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)}async tryRedirectSignIn(e){let n=null;try{n=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return n}async reloadAndSetCurrentUserOrClear(e){try{await Il(e)}catch(n){if((n==null?void 0:n.code)!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=gT()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(Gt(this.app))return Promise.reject(Un(this));const n=e?Et(e):null;return n&&W(n.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(n&&n._clone(this))}async _updateCurrentUser(e,n=!1){if(!this._deleted)return e&&W(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),n||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return Gt(this.app)?Promise.reject(Un(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return Gt(this.app)?Promise.reject(Un(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(Yt(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const n=this._getPasswordPolicyInternal();return n.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):n.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await RT(this),n=new OT(e);this.tenantId===null?this._projectPasswordPolicy=n:this._tenantPasswordPolicies[this.tenantId]=n}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new zs("auth","Firebase",e())}onAuthStateChanged(e,n,r){return this.registerStateListener(this.authStateSubscription,e,n,r)}beforeAuthStateChanged(e,n){return this.beforeStateQueue.pushCallback(e,n)}onIdTokenChanged(e,n,r){return this.registerStateListener(this.idTokenSubscription,e,n,r)}authStateReady(){return new Promise((e,n)=>{if(this.currentUser)e();else{const r=this.onAuthStateChanged(()=>{r(),e()},n)}})}async revokeAccessToken(e){if(this.currentUser){const n=await this.currentUser.getIdToken(),r={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:n};this.tenantId!=null&&(r.tenantId=this.tenantId),await TT(this,r)}}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:(e=this._currentUser)===null||e===void 0?void 0:e.toJSON()}}async _setRedirectUser(e,n){const r=await this.getOrInitRedirectPersistenceManager(n);return e===null?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const n=e&&Yt(e)||this._popupRedirectResolver;W(n,this,"argument-error"),this.redirectPersistenceManager=await Jr.create(this,[Yt(n._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var n,r;return this._isInitialized&&await this.queue(async()=>{}),((n=this._currentUser)===null||n===void 0?void 0:n._redirectEventId)===e?this._currentUser:((r=this.redirectUser)===null||r===void 0?void 0:r._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,n;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const r=(n=(e=this.currentUser)===null||e===void 0?void 0:e.uid)!==null&&n!==void 0?n:null;this.lastNotifiedUid!==r&&(this.lastNotifiedUid=r,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,n,r,i){if(this._deleted)return()=>{};const s=typeof n=="function"?n:n.next.bind(n);let o=!1;const l=this._isInitialized?Promise.resolve():this._initializationPromise;if(W(l,this,"internal-error"),l.then(()=>{o||s(this.currentUser)}),typeof n=="function"){const a=e.addObserver(n,r,i);return()=>{o=!0,a()}}else{const a=e.addObserver(n);return()=>{o=!0,a()}}}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 W(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=d_(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const n={"X-Client-Version":this.clientVersion};this.app.options.appId&&(n["X-Firebase-gmpid"]=this.app.options.appId);const r=await((e=this.heartbeatServiceProvider.getImmediate({optional:!0}))===null||e===void 0?void 0:e.getHeartbeatsHeader());r&&(n["X-Firebase-Client"]=r);const i=await this._getAppCheckToken();return i&&(n["X-Firebase-AppCheck"]=i),n}async _getAppCheckToken(){var e;const n=await((e=this.appCheckServiceProvider.getImmediate({optional:!0}))===null||e===void 0?void 0:e.getToken());return n!=null&&n.error&&fT(`Error while retrieving App Check token: ${n.error}`),n==null?void 0:n.token}}function aa(t){return Et(t)}class Tp{constructor(e){this.auth=e,this.observer=null,this.addObserver=UC(n=>this.observer=n)}get next(){return W(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */let ah={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function LT(t){ah=t}function MT(t){return ah.loadJS(t)}function jT(){return ah.gapiScript}function FT(t){return`__${t}${Math.floor(Math.random()*1e6)}`}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function UT(t,e){const n=Ed(t,"auth");if(n.isInitialized()){const i=n.getImmediate(),s=n.getOptions();if(ul(s,e??{}))return i;ln(i,"already-initialized")}return n.initialize({options:e})}function zT(t,e){const n=(e==null?void 0:e.persistence)||[],r=(Array.isArray(n)?n:[n]).map(Yt);e!=null&&e.errorMap&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(r,e==null?void 0:e.popupRedirectResolver)}function BT(t,e,n){const r=aa(t);W(r._canInitEmulator,r,"emulator-config-failed"),W(/^https?:\/\//.test(e),r,"invalid-emulator-scheme");const i=!1,s=h_(e),{host:o,port:l}=WT(e),a=l===null?"":`:${l}`;r.config.emulator={url:`${s}//${o}${a}/`},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:o,port:l,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),$T()}function h_(t){const e=t.indexOf(":");return e<0?"":t.substr(0,e+1)}function WT(t){const e=h_(t),n=/(\/\/)?([^?#/]+)/.exec(t.substr(e.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);if(i){const s=i[1];return{host:s,port:bp(r.substr(s.length+1))}}else{const[s,o]=r.split(":");return{host:s,port:bp(o)}}}function bp(t){if(!t)return null;const e=Number(t);return isNaN(e)?null:e}function $T(){function t(){const e=document.createElement("p"),n=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",n.position="fixed",n.width="100%",n.backgroundColor="#ffffff",n.border=".1em solid #000000",n.color="#b50000",n.bottom="0px",n.left="0px",n.margin="0px",n.zIndex="10000",n.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}typeof console<"u"&&typeof console.info=="function"&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?window.addEventListener("DOMContentLoaded",t):t())}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class f_{constructor(e,n){this.providerId=e,this.signInMethod=n}toJSON(){return Kt("not implemented")}_getIdTokenResponse(e){return Kt("not implemented")}_linkToIdToken(e,n){return Kt("not implemented")}_getReauthenticationResolver(e){return Kt("not implemented")}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function Xr(t,e){return Xy(t,"POST","/v1/accounts:signInWithIdp",la(t,e))}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const VT="http://localhost";class yr extends f_{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const n=new yr(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(n.idToken=e.idToken),e.accessToken&&(n.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(n.nonce=e.nonce),e.pendingToken&&(n.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(n.accessToken=e.oauthToken,n.secret=e.oauthTokenSecret):ln("argument-error"),n}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 n=typeof e=="string"?JSON.parse(e):e,{providerId:r,signInMethod:i}=n,s=rh(n,["providerId","signInMethod"]);if(!r||!i)return null;const o=new yr(r,i);return o.idToken=s.idToken||void 0,o.accessToken=s.accessToken||void 0,o.secret=s.secret,o.nonce=s.nonce,o.pendingToken=s.pendingToken||null,o}_getIdTokenResponse(e){const n=this.buildRequest();return Xr(e,n)}_linkToIdToken(e,n){const r=this.buildRequest();return r.idToken=n,Xr(e,r)}_getReauthenticationResolver(e){const n=this.buildRequest();return n.autoCreate=!1,Xr(e,n)}buildRequest(){const e={requestUri:VT,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const n={};this.idToken&&(n.id_token=this.idToken),this.accessToken&&(n.access_token=this.accessToken),this.secret&&(n.oauth_token_secret=this.secret),n.providerId=this.providerId,this.nonce&&!this.pendingToken&&(n.nonce=this.nonce),e.postBody=yi(n)}return e}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class p_{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}}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Ks extends p_{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class yn extends Ks{constructor(){super("facebook.com")}static credential(e){return yr._fromParams({providerId:yn.PROVIDER_ID,signInMethod:yn.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return yn.credentialFromTaggedObject(e)}static credentialFromError(e){return yn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return yn.credential(e.oauthAccessToken)}catch{return null}}}yn.FACEBOOK_SIGN_IN_METHOD="facebook.com";yn.PROVIDER_ID="facebook.com";/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class _n extends Ks{constructor(){super("google.com"),this.addScope("profile")}static credential(e,n){return yr._fromParams({providerId:_n.PROVIDER_ID,signInMethod:_n.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:n})}static credentialFromResult(e){return _n.credentialFromTaggedObject(e)}static credentialFromError(e){return _n.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:n,oauthAccessToken:r}=e;if(!n&&!r)return null;try{return _n.credential(n,r)}catch{return null}}}_n.GOOGLE_SIGN_IN_METHOD="google.com";_n.PROVIDER_ID="google.com";/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class wn extends Ks{constructor(){super("github.com")}static credential(e){return yr._fromParams({providerId:wn.PROVIDER_ID,signInMethod:wn.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return wn.credentialFromTaggedObject(e)}static credentialFromError(e){return wn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return wn.credential(e.oauthAccessToken)}catch{return null}}}wn.GITHUB_SIGN_IN_METHOD="github.com";wn.PROVIDER_ID="github.com";/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Sn extends Ks{constructor(){super("twitter.com")}static credential(e,n){return yr._fromParams({providerId:Sn.PROVIDER_ID,signInMethod:Sn.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:n})}static credentialFromResult(e){return Sn.credentialFromTaggedObject(e)}static credentialFromError(e){return Sn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:n,oauthTokenSecret:r}=e;if(!n||!r)return null;try{return Sn.credential(n,r)}catch{return null}}}Sn.TWITTER_SIGN_IN_METHOD="twitter.com";Sn.PROVIDER_ID="twitter.com";/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function HT(t,e){return Xy(t,"POST","/v1/accounts:signUp",la(t,e))}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class Hn{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,n,r,i=!1){const s=await Qt._fromIdTokenResponse(e,r,i),o=Pp(r);return new Hn({user:s,providerId:o,_tokenResponse:r,operationType:n})}static async _forOperation(e,n,r){await e._updateTokensIfNecessary(r,!0);const i=Pp(r);return new Hn({user:e,providerId:i,_tokenResponse:r,operationType:n})}}function Pp(t){return t.providerId?t.providerId:"phoneNumber"in t?"phone":null}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function GT(t){var e;if(Gt(t.app))return Promise.reject(Un(t));const n=aa(t);if(await n._initializationPromise,!((e=n.currentUser)===null||e===void 0)&&e.isAnonymous)return new Hn({user:n.currentUser,providerId:null,operationType:"signIn"});const r=await HT(n,{returnSecureToken:!0}),i=await Hn._fromIdTokenResponse(n,"signIn",r,!0);return await n._updateCurrentUser(i.user),i}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class kl extends Yn{constructor(e,n,r,i){var s;super(n.code,n.message),this.operationType=r,this.user=i,Object.setPrototypeOf(this,kl.prototype),this.customData={appName:e.name,tenantId:(s=e.tenantId)!==null&&s!==void 0?s:void 0,_serverResponse:n.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,n,r,i){return new kl(e,n,r,i)}}function m_(t,e,n,r){return(e==="reauthenticate"?n._getReauthenticationResolver(t):n._getIdTokenResponse(t)).catch(s=>{throw s.code==="auth/multi-factor-auth-required"?kl._fromErrorAndOperation(t,s,e,r):s})}async function qT(t,e,n=!1){const r=await Rs(t,e._linkToIdToken(t.auth,await t.getIdToken()),n);return Hn._forOperation(t,"link",r)}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function KT(t,e,n=!1){const{auth:r}=t;if(Gt(r.app))return Promise.reject(Un(r));const i="reauthenticate";try{const s=await Rs(t,m_(r,i,e,t),n);W(s.idToken,r,"internal-error");const o=oh(s.idToken);W(o,r,"internal-error");const{sub:l}=o;return W(t.uid===l,r,"user-mismatch"),Hn._forOperation(t,i,s)}catch(s){throw(s==null?void 0:s.code)==="auth/user-not-found"&&ln(r,"user-mismatch"),s}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function QT(t,e,n=!1){if(Gt(t.app))return Promise.reject(Un(t));const r="signIn",i=await m_(t,r,e),s=await Hn._fromIdTokenResponse(t,r,i);return n||await t._updateCurrentUser(s.user),s}function YT(t,e,n,r){return Et(t).onIdTokenChanged(e,n,r)}function JT(t,e,n){return Et(t).beforeAuthStateChanged(e,n)}const Tl="__sak";/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class g_{constructor(e,n){this.storageRetriever=e,this.type=n}_isAvailable(){try{return this.storage?(this.storage.setItem(Tl,"1"),this.storage.removeItem(Tl),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,n){return this.storage.setItem(e,JSON.stringify(n)),Promise.resolve()}_get(e){const n=this.storage.getItem(e);return Promise.resolve(n?JSON.parse(n):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const XT=1e3,ZT=10;class v_ extends g_{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,n)=>this.onStorageEvent(e,n),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=c_(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const n of Object.keys(this.listeners)){const r=this.storage.getItem(n),i=this.localCache[n];r!==i&&e(n,i,r)}}onStorageEvent(e,n=!1){if(!e.key){this.forAllChangedKeys((o,l,a)=>{this.notifyListeners(o,a)});return}const r=e.key;n?this.detachListener():this.stopPolling();const i=()=>{const o=this.storage.getItem(r);!n&&this.localCache[r]===o||this.notifyListeners(r,o)},s=this.storage.getItem(r);PT()&&s!==e.newValue&&e.newValue!==e.oldValue?setTimeout(i,ZT):i()}notifyListeners(e,n){this.localCache[e]=n;const r=this.listeners[e];if(r)for(const i of Array.from(r))i(n&&JSON.parse(n))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,n,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:n,newValue:r}),!0)})},XT)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,n){Object.keys(this.listeners).length===0&&(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(n)}_removeListener(e,n){this.listeners[e]&&(this.listeners[e].delete(n),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&(this.detachListener(),this.stopPolling())}async _set(e,n){await super._set(e,n),this.localCache[e]=JSON.stringify(n)}async _get(e){const n=await super._get(e);return this.localCache[e]=JSON.stringify(n),n}async _remove(e){await super._remove(e),delete this.localCache[e]}}v_.type="LOCAL";const e1=v_;/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class y_ extends g_{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,n){}_removeListener(e,n){}}y_.type="SESSION";const __=y_;/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function t1(t){return Promise.all(t.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(n){return{fulfilled:!1,reason:n}}}))}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class ua{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const n=this.receivers.find(i=>i.isListeningto(e));if(n)return n;const r=new ua(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const n=e,{eventId:r,eventType:i,data:s}=n.data,o=this.handlersMap[i];if(!(o!=null&&o.size))return;n.ports[0].postMessage({status:"ack",eventId:r,eventType:i});const l=Array.from(o).map(async u=>u(n.origin,s)),a=await t1(l);n.ports[0].postMessage({status:"done",eventId:r,eventType:i,response:a})}_subscribe(e,n){Object.keys(this.handlersMap).length===0&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(n)}_unsubscribe(e,n){this.handlersMap[e]&&n&&this.handlersMap[e].delete(n),(!n||this.handlersMap[e].size===0)&&delete this.handlersMap[e],Object.keys(this.handlersMap).length===0&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}ua.receivers=[];/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function uh(t="",e=10){let n="";for(let r=0;r{const u=uh("",20);i.port1.start();const h=setTimeout(()=>{a(new Error("unsupported_event"))},r);o={messageChannel:i,onMessage(d){const f=d;if(f.data.eventId===u)switch(f.data.status){case"ack":clearTimeout(h),s=setTimeout(()=>{a(new Error("timeout"))},3e3);break;case"done":clearTimeout(s),l(f.data.response);break;default:clearTimeout(h),clearTimeout(s),a(new Error("invalid_response"));break}}},this.handlers.add(o),i.port1.addEventListener("message",o.onMessage),this.target.postMessage({eventType:e,eventId:u,data:n},[i.port2])}).finally(()=>{o&&this.removeMessageHandler(o)})}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function zt(){return window}function r1(t){zt().location.href=t}/** + * @license + * Copyright 2020 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function w_(){return typeof zt().WorkerGlobalScope<"u"&&typeof zt().importScripts=="function"}async function i1(){if(!(navigator!=null&&navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}function s1(){var t;return((t=navigator==null?void 0:navigator.serviceWorker)===null||t===void 0?void 0:t.controller)||null}function o1(){return w_()?self:null}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const S_="firebaseLocalStorageDb",l1=1,bl="firebaseLocalStorage",C_="fbase_key";class Qs{constructor(e){this.request=e}toPromise(){return new Promise((e,n)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{n(this.request.error)})})}}function ca(t,e){return t.transaction([bl],e?"readwrite":"readonly").objectStore(bl)}function a1(){const t=indexedDB.deleteDatabase(S_);return new Qs(t).toPromise()}function gc(){const t=indexedDB.open(S_,l1);return new Promise((e,n)=>{t.addEventListener("error",()=>{n(t.error)}),t.addEventListener("upgradeneeded",()=>{const r=t.result;try{r.createObjectStore(bl,{keyPath:C_})}catch(i){n(i)}}),t.addEventListener("success",async()=>{const r=t.result;r.objectStoreNames.contains(bl)?e(r):(r.close(),await a1(),e(await gc()))})})}async function Np(t,e,n){const r=ca(t,!0).put({[C_]:e,value:n});return new Qs(r).toPromise()}async function u1(t,e){const n=ca(t,!1).get(e),r=await new Qs(n).toPromise();return r===void 0?null:r.value}function Rp(t,e){const n=ca(t,!0).delete(e);return new Qs(n).toPromise()}const c1=800,d1=3;class E_{constructor(){this.type="LOCAL",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.db?this.db:(this.db=await gc(),this.db)}async _withRetries(e){let n=0;for(;;)try{const r=await this._openDb();return await e(r)}catch(r){if(n++>d1)throw r;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return w_()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=ua._getInstance(o1()),this.receiver._subscribe("keyChanged",async(e,n)=>({keyProcessed:(await this._poll()).includes(n.key)})),this.receiver._subscribe("ping",async(e,n)=>["keyChanged"])}async initializeSender(){var e,n;if(this.activeServiceWorker=await i1(),!this.activeServiceWorker)return;this.sender=new n1(this.activeServiceWorker);const r=await this.sender._send("ping",{},800);r&&!((e=r[0])===null||e===void 0)&&e.fulfilled&&!((n=r[0])===null||n===void 0)&&n.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(!(!this.sender||!this.activeServiceWorker||s1()!==this.activeServiceWorker))try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await gc();return await Np(e,Tl,"1"),await Rp(e,Tl),!0}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,n){return this._withPendingWrite(async()=>(await this._withRetries(r=>Np(r,e,n)),this.localCache[e]=n,this.notifyServiceWorker(e)))}async _get(e){const n=await this._withRetries(r=>u1(r,e));return this.localCache[e]=n,n}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(n=>Rp(n,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){const e=await this._withRetries(i=>{const s=ca(i,!1).getAll();return new Qs(s).toPromise()});if(!e)return[];if(this.pendingWrites!==0)return[];const n=[],r=new Set;if(e.length!==0)for(const{fbase_key:i,value:s}of e)r.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(s)&&(this.notifyListeners(i,s),n.push(i));for(const i of Object.keys(this.localCache))this.localCache[i]&&!r.has(i)&&(this.notifyListeners(i,null),n.push(i));return n}notifyListeners(e,n){this.localCache[e]=n;const r=this.listeners[e];if(r)for(const i of Array.from(r))i(n)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),c1)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,n){Object.keys(this.listeners).length===0&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(n)}_removeListener(e,n){this.listeners[e]&&(this.listeners[e].delete(n),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&this.stopPolling()}}E_.type="LOCAL";const h1=E_;new qs(3e4,6e4);/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function f1(t,e){return e?Yt(e):(W(t._popupRedirectResolver,t,"argument-error"),t._popupRedirectResolver)}/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class ch extends f_{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Xr(e,this._buildIdpRequest())}_linkToIdToken(e,n){return Xr(e,this._buildIdpRequest(n))}_getReauthenticationResolver(e){return Xr(e,this._buildIdpRequest())}_buildIdpRequest(e){const n={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&&(n.idToken=e),n}}function p1(t){return QT(t.auth,new ch(t),t.bypassAuthState)}function m1(t){const{auth:e,user:n}=t;return W(n,e,"internal-error"),KT(n,new ch(t),t.bypassAuthState)}async function g1(t){const{auth:e,user:n}=t;return W(n,e,"internal-error"),qT(n,new ch(t),t.bypassAuthState)}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class x_{constructor(e,n,r,i,s=!1){this.auth=e,this.resolver=r,this.user=i,this.bypassAuthState=s,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(n)?n:[n]}execute(){return new Promise(async(e,n)=>{this.pendingPromise={resolve:e,reject:n};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(r){this.reject(r)}})}async onAuthEvent(e){const{urlResponse:n,sessionId:r,postBody:i,tenantId:s,error:o,type:l}=e;if(o){this.reject(o);return}const a={auth:this.auth,requestUri:n,sessionId:r,tenantId:s||void 0,postBody:i||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(l)(a))}catch(u){this.reject(u)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return p1;case"linkViaPopup":case"linkViaRedirect":return g1;case"reauthViaPopup":case"reauthViaRedirect":return m1;default:ln(this.auth,"internal-error")}}resolve(e){an(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){an(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()}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const v1=new qs(2e3,1e4);class Br extends x_{constructor(e,n,r,i,s){super(e,n,i,s),this.provider=r,this.authWindow=null,this.pollId=null,Br.currentPopupAction&&Br.currentPopupAction.cancel(),Br.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return W(e,this.auth,"internal-error"),e}async onExecution(){an(this.filter.length===1,"Popup operations only handle one event");const e=uh();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(n=>{this.reject(n)}),this.resolver._isIframeWebStorageSupported(this.auth,n=>{n||this.reject(Ut(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return((e=this.authWindow)===null||e===void 0?void 0:e.associatedEvent)||null}cancel(){this.reject(Ut(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Br.currentPopupAction=null}pollUserCancellation(){const e=()=>{var n,r;if(!((r=(n=this.authWindow)===null||n===void 0?void 0:n.window)===null||r===void 0)&&r.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Ut(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(e,v1.get())};e()}}Br.currentPopupAction=null;/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const y1="pendingRedirect",Ao=new Map;class _1 extends x_{constructor(e,n,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],n,void 0,r),this.eventId=null}async execute(){let e=Ao.get(this.auth._key());if(!e){try{const r=await w1(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(r)}catch(n){e=()=>Promise.reject(n)}Ao.set(this.auth._key(),e)}return this.bypassAuthState||Ao.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if(e.type==="signInViaRedirect")return super.onAuthEvent(e);if(e.type==="unknown"){this.resolve(null);return}if(e.eventId){const n=await this.auth._redirectUserForId(e.eventId);if(n)return this.user=n,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function w1(t,e){const n=E1(e),r=C1(t);if(!await r._isAvailable())return!1;const i=await r._get(n)==="true";return await r._remove(n),i}function S1(t,e){Ao.set(t._key(),e)}function C1(t){return Yt(t._redirectPersistence)}function E1(t){return Ro(y1,t.config.apiKey,t.name)}async function x1(t,e,n=!1){if(Gt(t.app))return Promise.reject(Un(t));const r=aa(t),i=f1(r,e),o=await new _1(r,i,n).execute();return o&&!n&&(delete o.user._redirectEventId,await r._persistUserIfCurrent(o.user),await r._setRedirectUser(null,e)),o}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const I1=10*60*1e3;class k1{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 n=!1;return this.consumers.forEach(r=>{this.isEventForConsumer(e,r)&&(n=!0,this.sendToConsumer(e,r),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!T1(e)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=e,n=!0)),n}sendToConsumer(e,n){var r;if(e.error&&!I_(e)){const i=((r=e.error.code)===null||r===void 0?void 0:r.split("auth/")[1])||"internal-error";n.onError(Ut(this.auth,i))}else n.onAuthEvent(e)}isEventForConsumer(e,n){const r=n.eventId===null||!!e.eventId&&e.eventId===n.eventId;return n.filter.includes(e.type)&&r}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=I1&&this.cachedEventUids.clear(),this.cachedEventUids.has(Ap(e))}saveEventToCache(e){this.cachedEventUids.add(Ap(e)),this.lastProcessedEventTime=Date.now()}}function Ap(t){return[t.type,t.eventId,t.sessionId,t.tenantId].filter(e=>e).join("-")}function I_({type:t,error:e}){return t==="unknown"&&(e==null?void 0:e.code)==="auth/no-auth-event"}function T1(t){switch(t.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return I_(t);default:return!1}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */async function b1(t,e={}){return Ei(t,"GET","/v1/projects",e)}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const P1=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,N1=/^https?/;async function R1(t){if(t.config.emulator)return;const{authorizedDomains:e}=await b1(t);for(const n of e)try{if(A1(n))return}catch{}ln(t,"unauthorized-domain")}function A1(t){const e=pc(),{protocol:n,hostname:r}=new URL(e);if(t.startsWith("chrome-extension://")){const o=new URL(t);return o.hostname===""&&r===""?n==="chrome-extension:"&&t.replace("chrome-extension://","")===e.replace("chrome-extension://",""):n==="chrome-extension:"&&o.hostname===r}if(!N1.test(n))return!1;if(P1.test(t))return r===t;const i=t.replace(/\./g,"\\.");return new RegExp("^(.+\\."+i+"|"+i+")$","i").test(r)}/** + * @license + * Copyright 2020 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const O1=new qs(3e4,6e4);function Op(){const t=zt().___jsl;if(t!=null&&t.H){for(const e of Object.keys(t.H))if(t.H[e].r=t.H[e].r||[],t.H[e].L=t.H[e].L||[],t.H[e].r=[...t.H[e].L],t.CP)for(let n=0;n{var r,i,s;function o(){Op(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Op(),n(Ut(t,"network-request-failed"))},timeout:O1.get()})}if(!((i=(r=zt().gapi)===null||r===void 0?void 0:r.iframes)===null||i===void 0)&&i.Iframe)e(gapi.iframes.getContext());else if(!((s=zt().gapi)===null||s===void 0)&&s.load)o();else{const l=FT("iframefcb");return zt()[l]=()=>{gapi.load?o():n(Ut(t,"network-request-failed"))},MT(`${jT()}?onload=${l}`).catch(a=>n(a))}}).catch(e=>{throw Oo=null,e})}let Oo=null;function L1(t){return Oo=Oo||D1(t),Oo}/** + * @license + * Copyright 2020 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const M1=new qs(5e3,15e3),j1="__/auth/iframe",F1="emulator/auth/iframe",U1={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},z1=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function B1(t){const e=t.config;W(e.authDomain,t,"auth-domain-config-required");const n=e.emulator?sh(e,F1):`https://${t.config.authDomain}/${j1}`,r={apiKey:e.apiKey,appName:t.name,v:_i},i=z1.get(t.config.apiHost);i&&(r.eid=i);const s=t._getFrameworks();return s.length&&(r.fw=s.join(",")),`${n}?${yi(r).slice(1)}`}async function W1(t){const e=await L1(t),n=zt().gapi;return W(n,t,"internal-error"),e.open({where:document.body,url:B1(t),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:U1,dontclear:!0},r=>new Promise(async(i,s)=>{await r.restyle({setHideOnLeave:!1});const o=Ut(t,"network-request-failed"),l=zt().setTimeout(()=>{s(o)},M1.get());function a(){zt().clearTimeout(l),i(r)}r.ping(a).then(a,()=>{s(o)})}))}/** + * @license + * Copyright 2020 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const $1={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"},V1=500,H1=600,G1="_blank",q1="http://localhost";class Dp{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch{}}}function K1(t,e,n,r=V1,i=H1){const s=Math.max((window.screen.availHeight-i)/2,0).toString(),o=Math.max((window.screen.availWidth-r)/2,0).toString();let l="";const a=Object.assign(Object.assign({},$1),{width:r.toString(),height:i.toString(),top:s,left:o}),u=Je().toLowerCase();n&&(l=s_(u)?G1:n),r_(u)&&(e=e||q1,a.scrollbars="yes");const h=Object.entries(a).reduce((f,[v,w])=>`${f}${v}=${w},`,"");if(bT(u)&&l!=="_self")return Q1(e||"",l),new Dp(null);const d=window.open(e||"",l,h);W(d,t,"popup-blocked");try{d.focus()}catch{}return new Dp(d)}function Q1(t,e){const n=document.createElement("a");n.href=t,n.target=e;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Y1="__/auth/handler",J1="emulator/auth/handler",X1=encodeURIComponent("fac");async function Lp(t,e,n,r,i,s){W(t.config.authDomain,t,"auth-domain-config-required"),W(t.config.apiKey,t,"invalid-api-key");const o={apiKey:t.config.apiKey,appName:t.name,authType:n,redirectUrl:r,v:_i,eventId:i};if(e instanceof p_){e.setDefaultLanguage(t.languageCode),o.providerId=e.providerId||"",Ku(e.getCustomParameters())||(o.customParameters=JSON.stringify(e.getCustomParameters()));for(const[h,d]of Object.entries({}))o[h]=d}if(e instanceof Ks){const h=e.getScopes().filter(d=>d!=="");h.length>0&&(o.scopes=h.join(","))}t.tenantId&&(o.tid=t.tenantId);const l=o;for(const h of Object.keys(l))l[h]===void 0&&delete l[h];const a=await t._getAppCheckToken(),u=a?`#${X1}=${encodeURIComponent(a)}`:"";return`${Z1(t)}?${yi(l).slice(1)}${u}`}function Z1({config:t}){return t.emulator?sh(t,J1):`https://${t.authDomain}/${Y1}`}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const Xa="webStorageSupport";class eb{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=__,this._completeRedirectFn=x1,this._overrideRedirectResult=S1}async _openPopup(e,n,r,i){var s;an((s=this.eventManagers[e._key()])===null||s===void 0?void 0:s.manager,"_initialize() not called before _openPopup()");const o=await Lp(e,n,r,pc(),i);return K1(e,o,uh())}async _openRedirect(e,n,r,i){await this._originValidation(e);const s=await Lp(e,n,r,pc(),i);return r1(s),new Promise(()=>{})}_initialize(e){const n=e._key();if(this.eventManagers[n]){const{manager:i,promise:s}=this.eventManagers[n];return i?Promise.resolve(i):(an(s,"If manager is not set, promise should be"),s)}const r=this.initAndGetManager(e);return this.eventManagers[n]={promise:r},r.catch(()=>{delete this.eventManagers[n]}),r}async initAndGetManager(e){const n=await W1(e),r=new k1(e);return n.register("authEvent",i=>(W(i==null?void 0:i.authEvent,e,"invalid-auth-event"),{status:r.onEvent(i.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:r},this.iframes[e._key()]=n,r}_isIframeWebStorageSupported(e,n){this.iframes[e._key()].send(Xa,{type:Xa},i=>{var s;const o=(s=i==null?void 0:i[0])===null||s===void 0?void 0:s[Xa];o!==void 0&&n(!!o),ln(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const n=e._key();return this.originValidationPromises[n]||(this.originValidationPromises[n]=R1(e)),this.originValidationPromises[n]}get _shouldInitProactively(){return c_()||i_()||lh()}}const tb=eb;var Mp="@firebase/auth",jp="1.7.9";/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */class nb{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),((e=this.auth.currentUser)===null||e===void 0?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const n=this.auth.onIdTokenChanged(r=>{e((r==null?void 0:r.stsTokenManager.accessToken)||null)});this.internalListeners.set(e,n),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const n=this.internalListeners.get(e);n&&(this.internalListeners.delete(e),n(),this.updateProactiveRefresh())}assertAuthConfigured(){W(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */function rb(t){switch(t){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function ib(t){li(new fr("auth",(e,{options:n})=>{const r=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),s=e.getProvider("app-check-internal"),{apiKey:o,authDomain:l}=r.options;W(o&&!o.includes(":"),"invalid-api-key",{appName:r.name});const a={apiKey:o,authDomain:l,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:d_(t)},u=new DT(r,i,s,a);return zT(u,n),u},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,n,r)=>{e.getProvider("auth-internal").initialize()})),li(new fr("auth-internal",e=>{const n=aa(e.getProvider("auth").getImmediate());return(r=>new nb(r))(n)},"PRIVATE").setInstantiationMode("EXPLICIT")),Mn(Mp,jp,rb(t)),Mn(Mp,jp,"esm2017")}/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */const sb=5*60,ob=kv("authIdTokenMaxAge")||sb;let Fp=null;const lb=t=>async e=>{const n=e&&await e.getIdTokenResult(),r=n&&(new Date().getTime()-Date.parse(n.issuedAtTime))/1e3;if(r&&r>ob)return;const i=n==null?void 0:n.token;Fp!==i&&(Fp=i,await fetch(t,{method:i?"POST":"DELETE",headers:i?{Authorization:`Bearer ${i}`}:{}}))};function ab(t=Av()){const e=Ed(t,"auth");if(e.isInitialized())return e.getImmediate();const n=UT(t,{popupRedirectResolver:tb,persistence:[h1,e1,__]}),r=kv("authTokenSyncURL");if(r&&typeof isSecureContext=="boolean"&&isSecureContext){const s=new URL(r,location.origin);if(location.origin===s.origin){const o=lb(s.toString());JT(n,o,()=>o(n.currentUser)),YT(n,l=>o(l))}}const i=xv("auth");return i&&BT(n,`http://${i}`),n}function ub(){var t,e;return(e=(t=document.getElementsByTagName("head"))===null||t===void 0?void 0:t[0])!==null&&e!==void 0?e:document}LT({loadJS(t){return new Promise((e,n)=>{const r=document.createElement("script");r.setAttribute("src",t),r.onload=e,r.onerror=i=>{const s=Ut("internal-error");s.customData=i,n(s)},r.type="text/javascript",r.charset="UTF-8",ub().appendChild(r)})},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="});ib("Browser");const cb={apiKey:"AIzaSyBiZSV4Z_3-L0z8RP5yY_2xXlw5fKOy2jc",authDomain:"classroom-polling-dd344.firebaseapp.com",databaseURL:"https://classroom-polling-dd344-default-rtdb.firebaseio.com",projectId:"classroom-polling-dd344",storageBucket:"classroom-polling-dd344.firebasestorage.app",messagingSenderId:"528103899828",appId:"1:528103899828:web:f74274640de611a61d0de1"},k_=Rv(cb),re=aT(k_),db=ab(k_);GT(db).catch(console.error);function T_(t){const e=new Date().toLocaleDateString("en-CA");return on(ne(re,`session/students/${t}`),{joinedAt:Sp(),date:e}),on(ne(re,`sessionStudents/${e}_${t}`),{name:t,date:e,joinedAt:Sp()})}function vc(t){return vr(ne(re,`session/students/${t}`))}function b_(t,e,n){return sa(ne(re,"session/activePoll/responses"),{[t]:n})}function Pl({question:t,options:e,correctIndex:n,duration:r,resultPolicy:i,correctPolicy:s}){const o=`poll_${Date.now()}`;return on(ne(re,"session/activePoll"),{id:o,question:t,options:e,correctIndex:n??null,duration:r,resultPolicy:i,correctPolicy:s,startedAt:Date.now(),responses:{},ended:!1,revealResults:!1,revealCorrect:!1})}async function Do(t,e){const[n,r]=await Promise.all([Ns(ne(re,"session/activePoll")),Ns(ne(re,"session/queue"))]),i=n.val(),s=r.val();if(!i)return;const o={...i,revealResults:t,revealCorrect:e,endedAt:Date.now()};return s&&(o.setId=s.setId,o.setName=s.setName,o.setPosition=s.currentIndex,o.sessionKey=s.sessionKey),await on(ne(re,`pollHistory/${i.id}`),o),vr(ne(re,"session/activePoll"))}function P_(){return sa(ne(re,"session/activePoll"),{ended:!0})}function yc(t,e){return sa(ne(re,"session/activePoll"),{revealResults:t,revealCorrect:e})}function dh(t){const e=ne(re,"session/activePoll");return xr(e,n=>t(n.val()))}function N_(t){const e=ne(re,"session/students");return xr(e,n=>{const r=n.val()||{};t(Object.keys(r).map(i=>({name:i,...r[i]})))})}function R_(t){const e=ne(re,"pollHistory");return xr(e,n=>{const r=n.val()||{},i=Object.values(r).sort((s,o)=>(o.startedAt||0)-(s.startedAt||0));t(i)})}function A_(t){const e=ne(re,"pollSets");return xr(e,n=>{const r=n.val()||{},i=Object.entries(r).map(([s,o])=>({id:s,...o})).sort((s,o)=>(o.createdAt||0)-(s.createdAt||0));t(i)})}async function _c({name:t,defaults:e,polls:n}){const r=`set_${Date.now()}`;return await on(ne(re,`pollSets/${r}`),{id:r,name:t,createdAt:Date.now(),defaults:e,polls:n||[]}),r}function Lo(t,e){return Ns(ne(re,`pollSets/${t}`)).then(n=>{const r=n.val()||{};return on(ne(re,`pollSets/${t}`),{...r,...e})})}function O_(t){return vr(ne(re,`pollSets/${t}`))}function D_(t,e){const n=ne(re,`pollSets/${t}`);return xr(n,r=>e(r.val()))}function L_(t,e,n){const r=`run_${Date.now()}`;return on(ne(re,"session/queue"),{setId:t,setName:e,currentIndex:0,totalPolls:n,sessionKey:r})}function M_(t){return sa(ne(re,"session/queue"),{currentIndex:t})}function wc(){return vr(ne(re,"session/queue"))}function j_(t){const e=ne(re,"session/queue");return xr(e,n=>t(n.val()))}async function F_(t,e){const r=(await Ns(ne(re,"session/activePoll"))).val(),s=(await Ns(ne(re,"session/queue"))).val();if(!r)return;const o={...r,revealResults:t,revealCorrect:e,endedAt:Date.now()};return s&&(o.setId=s.setId,o.setName=s.setName,o.setPosition=s.currentIndex,o.sessionKey=s.sessionKey),await on(ne(re,`pollHistory/${r.id}`),o),vr(ne(re,"session/activePoll"))}const hb=Object.freeze(Object.defineProperty({__proto__:null,advanceQueue:M_,clearQueue:wc,closePoll:F_,createPollSet:_c,deletePollSet:O_,endPoll:Do,expirePoll:P_,joinSession:T_,launchSet:L_,leaveSession:vc,revealPollResults:yc,startPoll:Pl,submitAnswer:b_,updatePollSet:Lo,watchActivePoll:dh,watchPollHistory:R_,watchPollSet:D_,watchPollSets:A_,watchQueue:j_,watchStudents:N_},Symbol.toStringTag,{value:"Module"})),Up=60,fb=[{value:"on_submit",label:"After they submit"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}],pb=[{value:"with_results",label:"With results"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}];function mb(){var Ge;const t=Sr(),[e,n]=C.useState([]),[r,i]=C.useState(null),[s,o]=C.useState(0),[l,a]=C.useState("dashboard"),[u,h]=C.useState(null),[d,f]=C.useState(null),v=C.useRef(null),w=C.useRef(null),_=C.useRef(null),[E,g]=C.useState(""),[p,m]=C.useState(["",""]),[S,I]=C.useState(null),[P,b]=C.useState(Up),[A,q]=C.useState("on_submit"),[z,pe]=C.useState("with_results");C.useEffect(()=>{localStorage.getItem("role")!=="instructor"&&t("/")},[]),C.useEffect(()=>{const L=dh(xe=>{xe&&(_.current=xe),i(xe),xe&&!xe.ended&&o(Math.max(0,Math.round(xe.duration-(Date.now()-xe.startedAt)/1e3)))}),te=N_(n),Te=j_(xe=>{h(xe),xe!=null&&xe.setId?(w.current&&w.current(),gC(async()=>{const{watchPollSet:Ir}=await Promise.resolve().then(()=>hb);return{watchPollSet:Ir}},void 0).then(({watchPollSet:Ir})=>{w.current=Ir(xe.setId,f)})):(f(null),_.current=null,w.current&&(w.current(),w.current=null))});return()=>{L(),te(),Te()}},[]),C.useEffect(()=>(clearInterval(v.current),r&&!r.ended&&(v.current=setInterval(()=>{const L=Math.max(0,Math.round(r.duration-(Date.now()-r.startedAt)/1e3));o(L),L===0&&(clearInterval(v.current),P_())},500)),()=>clearInterval(v.current)),[r==null?void 0:r.id,r==null?void 0:r.ended]);function D(){p.length<6&&m([...p,""])}function Y(L,te){m(p.map((Te,xe)=>xe===L?te:Te))}function X(L){if(p.length<=2)return;const te=p.filter((Te,xe)=>xe!==L);m(te),S===L?I(null):S>L&&I(S-1)}function et(L){L.preventDefault();const te=p.filter(Te=>Te.trim());!E.trim()||te.length<2||(Pl({question:E.trim(),options:te,correctIndex:S,duration:P,resultPolicy:A,correctPolicy:z}),g(""),m(["",""]),I(null),b(Up),q("on_submit"),pe("with_results"),a("dashboard"))}async function Ee(){if(!u||!d)return;const L=u.currentIndex+1;if(r&&await Do(r.revealResults||!1,r.revealCorrect||!1),L>=u.totalPolls){await wc();return}await M_(L);const te=d.defaults||{},Te=(d.polls||[])[L];Te&&await Pl({question:Te.question,options:Te.options,correctIndex:Te.correctIndex??null,duration:Te.duration??te.duration??60,resultPolicy:Te.resultPolicy??te.resultPolicy??"on_submit",correctPolicy:Te.correctPolicy??te.correctPolicy??"with_results"})}async function Be(){r&&await Do(r.revealResults||!1,r.revealCorrect||!1),await wc()}const R=r?Object.keys(r.responses||{}).length:Object.keys(((Ge=_.current)==null?void 0:Ge.responses)||{}).length,U=r==null?void 0:r.ended,y=!!u,x=u&&u.currentIndex>=u.totalPolls-1,T=r||(y?_.current:null),O=!r&&T;function K(L){return L.revealResults?!0:!(L.resultPolicy==="never"||L.resultPolicy==="manual")}function tt(L){return L.revealCorrect?!0:L.correctPolicy==="never"||L.correctPolicy==="manual"?!1:!!(L.correctPolicy==="with_results"&&K(L))}return c.jsxs("div",{style:j.page,children:[c.jsxs("aside",{style:j.sidebar,children:[c.jsxs("div",{style:j.logo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsxs("nav",{style:j.nav,children:[c.jsx("button",{style:{...j.navBtn,...l==="dashboard"?j.navActive:{}},onClick:()=>a("dashboard"),children:"πŸ“Š Dashboard"}),c.jsx("button",{style:{...j.navBtn,...l==="create"?j.navActive:{},...r?j.navDisabled:{}},onClick:()=>!r&&a("create"),disabled:!!r,children:"βž• New Poll"}),c.jsx("button",{style:j.navBtn,onClick:()=>t("/pollsets"),children:"πŸ“š Poll Sets"}),c.jsx("button",{style:j.navBtn,onClick:()=>t("/history"),children:"πŸ• History"})]}),c.jsxs("div",{style:j.sidebarBottom,children:[c.jsxs("div",{style:j.studentCount,children:[c.jsx("span",{style:j.dot}),c.jsx("strong",{children:e.length})," student",e.length!==1?"s":""," online"]}),c.jsx("div",{style:j.studentList,children:e.map(L=>c.jsx("div",{style:j.studentChip,children:L.name},L.name))}),c.jsx("button",{className:"btn btn-secondary",style:{width:"100%",marginTop:"auto",fontSize:"0.8rem"},onClick:()=>{localStorage.removeItem("role"),localStorage.removeItem("historyAuth"),t("/")},children:"Exit"})]})]}),c.jsxs("main",{style:j.main,children:[l==="create"&&c.jsxs("div",{style:j.content,className:"fade-up",children:[c.jsx("h2",{style:j.pageTitle,children:"Create a Poll"}),c.jsxs("form",{onSubmit:et,style:j.form,children:[c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Question"}),c.jsx("textarea",{className:"input",rows:2,placeholder:"e.g. Which process converts sunlight into energy?",value:E,onChange:L=>g(L.target.value),style:{resize:"vertical",width:"100%"},required:!0})]}),c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Answer Options"}),c.jsx("p",{style:j.hint,children:"Click a letter circle to mark the correct answer (optional)"}),c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:p.map((L,te)=>c.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[c.jsx("button",{type:"button",style:{...j.correctBtn,...S===te?j.correctBtnActive:{}},onClick:()=>I(S===te?null:te),children:S===te?"βœ“":String.fromCharCode(65+te)}),c.jsx("input",{className:"input",style:{flex:1},placeholder:`Option ${String.fromCharCode(65+te)}`,value:L,onChange:Te=>Y(te,Te.target.value),required:!0}),c.jsx("button",{type:"button",style:j.removeBtn,onClick:()=>X(te),disabled:p.length<=2,children:"βœ•"})]},te))}),p.length<6&&c.jsx("button",{type:"button",className:"btn btn-ghost",style:{marginTop:"0.5rem",fontSize:"0.85rem"},onClick:D,children:"+ Add option"})]}),c.jsxs("div",{style:j.policySection,children:[c.jsx("label",{className:"label",children:"Show results to students"}),c.jsx("div",{style:j.policyRow,children:fb.map(L=>c.jsx("button",{type:"button",style:{...j.policyBtn,...A===L.value?j.policyBtnActive:{}},onClick:()=>q(L.value),children:c.jsx("span",{style:j.policyLabel,children:L.label})},L.value))})]}),S!=null&&c.jsxs("div",{style:j.policySection,children:[c.jsx("label",{className:"label",children:"Reveal correct answer to students"}),c.jsx("div",{style:j.policyRow,children:pb.map(L=>c.jsx("button",{type:"button",style:{...j.policyBtn,...z===L.value?j.policyBtnActive:{}},onClick:()=>pe(L.value),children:c.jsx("span",{style:j.policyLabel,children:L.label})},L.value))})]}),c.jsxs("div",{style:{display:"flex",gap:"1rem",alignItems:"flex-end"},children:[c.jsxs("div",{style:{flex:1},children:[c.jsx("label",{className:"label",children:"Duration (seconds)"}),c.jsx("input",{className:"input",type:"number",min:10,max:300,value:P,onChange:L=>b(Number(L.target.value))})]}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{padding:"0.65rem 2rem"},children:"Start Poll β†’"})]})]})]}),l==="dashboard"&&c.jsxs("div",{style:j.content,className:"fade-up",children:[y&&c.jsxs("div",{style:j.queueBanner,children:[c.jsx("span",{style:j.queueIcon,children:"πŸ“š"}),c.jsxs("div",{style:{flex:1},children:[c.jsx("div",{style:j.queueName,children:u.setName}),c.jsxs("div",{style:j.queueProgress,children:["Poll ",u.currentIndex+1," of ",u.totalPolls]})]}),c.jsx("div",{style:j.queueDots,children:Array.from({length:u.totalPolls},(L,te)=>c.jsx("div",{style:{...j.queueDot,background:tea("create"),children:"Create one β†’"})," ","or"," ",c.jsx("button",{style:j.link,onClick:()=>t("/pollsets"),children:"launch a set β†’"})]})]}),T&&c.jsxs("div",{style:j.pollCard,children:[c.jsxs("div",{style:j.timerRow,children:[r&&!U?c.jsx(gb,{timeLeft:s,total:r.duration}):c.jsx("div",{style:j.expiredBadge,children:"⏰"}),c.jsxs("div",{style:{flex:1},children:[c.jsx("div",{style:j.pollQuestion,children:T.question}),c.jsxs("div",{style:j.responseMeta,children:[R," / ",e.length," responded",(U||O)&&c.jsx("span",{style:j.expiredTag,children:O?" Β· Poll ended":" Β· Stopped accepting answers"})]})]})]}),c.jsx("div",{style:{marginTop:"1.25rem",display:"flex",flexDirection:"column",gap:"0.6rem"},children:T.options.map((L,te)=>{const Te=Object.values(T.responses||{}).filter(z_=>z_===te).length,xe=Object.keys(T.responses||{}).length,Ir=xe>0?Math.round(Te/xe*100):0,da=T.correctIndex===te;return c.jsxs("div",{style:j.optionRow,children:[c.jsxs("div",{style:{...j.optionLabel,...da?j.correctLabel:{}},children:[String.fromCharCode(65+te),da?"βœ“":""]}),c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"0.25rem"},children:[c.jsx("span",{style:{fontSize:"0.9rem"},children:L}),c.jsxs("span",{style:{fontSize:"0.85rem",color:"var(--muted)"},children:[Te," (",Ir,"%)"]})]}),c.jsx("div",{style:j.barBg,children:c.jsx("div",{style:{...j.barFill,width:`${Ir}%`,background:da?"var(--success)":"var(--accent2)"}})})]})]},te)})}),R>0&&c.jsxs("div",{style:{marginTop:"1rem"},children:[c.jsx("label",{className:"label",children:"Responded"}),c.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.4rem"},children:Object.keys(T.responses).map(L=>c.jsx("span",{style:j.answeredChip,children:L},L))})]}),c.jsxs("div",{style:j.controls,children:[c.jsx("label",{className:"label",style:{marginBottom:"0.75rem"},children:"Student display"}),c.jsxs("div",{style:j.controlGrid,children:[r&&r.resultPolicy==="manual"&&c.jsxs("div",{style:j.controlItem,children:[c.jsx("span",{style:j.controlLabel,children:"Results visible"}),c.jsx(zp,{active:!!r.revealResults,onChange:L=>yc(L,r.revealCorrect)})]}),r&&r.correctPolicy==="manual"&&r.correctIndex!=null&&c.jsxs("div",{style:j.controlItem,children:[c.jsx("span",{style:j.controlLabel,children:"Correct answer visible"}),c.jsx(zp,{active:!!r.revealCorrect,onChange:L=>yc(r.revealResults,L)})]}),c.jsxs("div",{style:j.statusSummary,children:[c.jsx(Bp,{label:"Results",state:T.resultPolicy==="never"?"never":T.resultPolicy==="on_submit"?"auto":T.revealResults?"shown":"hidden"}),T.correctIndex!=null&&c.jsx(Bp,{label:"Answer",state:T.correctPolicy==="never"?"never":tt(T)?"shown":"hidden"})]}),c.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"0.5rem",alignItems:"center"},children:[r&&c.jsx("button",{className:"btn btn-secondary",onClick:()=>y?F_(r.revealResults,r.revealCorrect):Do(r.revealResults,r.revealCorrect),children:y?"End Poll":"Close Poll"}),y&&c.jsx("button",{className:"btn btn-primary",onClick:Ee,children:x?"Finish Set βœ“":`Next Poll β†’ (${u.currentIndex+2} of ${u.totalPolls})`})]})]})]})]})]})]})]})}function zp({active:t,onChange:e}){return c.jsx("button",{onClick:()=>e(!t),style:{position:"relative",width:48,height:26,borderRadius:13,border:"none",background:t?"var(--success)":"var(--border)",cursor:"pointer",transition:"background 0.2s",flexShrink:0},children:c.jsx("span",{style:{position:"absolute",top:3,left:t?22:3,width:20,height:20,borderRadius:"50%",background:"white",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})})}function Bp({label:t,state:e}){const n={shown:{bg:"#dcfce7",color:"#15803d"},hidden:{bg:"#fee2e2",color:"#b91c1c"},auto:{bg:"#dbeafe",color:"#1d4ed8"},never:{bg:"var(--cream)",color:"var(--muted)"}},r={shown:"Shown",hidden:"Hidden",auto:"Auto",never:"Never"},i=n[e]||n.never;return c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem"},children:[c.jsxs("span",{style:{fontSize:"0.78rem",color:"var(--muted)"},children:[t,":"]}),c.jsx("span",{style:{background:i.bg,color:i.color,borderRadius:4,padding:"0.15rem 0.5rem",fontSize:"0.75rem",fontWeight:600},children:r[e]})]})}function gb({timeLeft:t,total:e}){const r=2*Math.PI*28,i=e>0?t/e:0,s=r*(1-i),o=i>.4?"var(--accent2)":i>.15?"#f59e0b":"var(--accent)";return c.jsxs("div",{style:{position:"relative",width:72,height:72,flexShrink:0},children:[c.jsxs("svg",{width:"72",height:"72",style:{transform:"rotate(-90deg)"},children:[c.jsx("circle",{cx:"36",cy:"36",r:28,fill:"none",stroke:"var(--cream)",strokeWidth:"5"}),c.jsx("circle",{cx:"36",cy:"36",r:28,fill:"none",stroke:o,strokeWidth:"5",strokeDasharray:r,strokeDashoffset:s,strokeLinecap:"round",style:{transition:"stroke-dashoffset 0.5s linear, stroke 0.5s"}})]}),c.jsx("span",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.1rem"},children:t})]})}const j={page:{display:"flex",minHeight:"100vh",background:"var(--paper)"},sidebar:{width:220,minHeight:"100vh",background:"var(--ink)",color:"white",display:"flex",flexDirection:"column",padding:"1.5rem 1rem",gap:"0.5rem",position:"sticky",top:0,flexShrink:0},logo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",padding:"0 0.5rem",marginBottom:"1rem"},nav:{display:"flex",flexDirection:"column",gap:"0.25rem"},navBtn:{background:"transparent",color:"rgba(255,255,255,0.7)",border:"none",borderRadius:8,padding:"0.6rem 0.75rem",textAlign:"left",cursor:"pointer",fontSize:"0.9rem",transition:"all 0.15s"},navActive:{background:"rgba(255,255,255,0.12)",color:"white"},navDisabled:{opacity:.4,cursor:"not-allowed"},sidebarBottom:{marginTop:"auto",display:"flex",flexDirection:"column",gap:"0.75rem"},studentCount:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem",color:"rgba(255,255,255,0.6)"},dot:{width:8,height:8,borderRadius:"50%",background:"#4ade80",flexShrink:0,boxShadow:"0 0 6px #4ade80"},studentList:{display:"flex",flexWrap:"wrap",gap:"0.35rem",maxHeight:120,overflowY:"auto"},studentChip:{background:"rgba(255,255,255,0.1)",borderRadius:4,padding:"0.2rem 0.5rem",fontSize:"0.78rem",color:"rgba(255,255,255,0.8)"},main:{flex:1,padding:"2rem",overflowY:"auto"},content:{maxWidth:"100%",margin:"0 auto"},pageTitle:{fontSize:"1.6rem",marginBottom:"1.5rem"},form:{display:"flex",flexDirection:"column",gap:"1.25rem",background:"white",padding:"1.5rem",borderRadius:12,border:"1px solid var(--border)"},hint:{fontSize:"0.82rem",color:"var(--muted)",marginBottom:"0.5rem"},policySection:{display:"flex",flexDirection:"column",gap:"0.5rem"},policyRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},policyBtn:{display:"flex",flexDirection:"column",gap:"0.2rem",padding:"0.6rem 0.85rem",borderRadius:8,border:"1.5px solid var(--border)",background:"var(--paper)",cursor:"pointer",textAlign:"left",transition:"all 0.15s",flex:1,minWidth:120},policyBtnActive:{borderColor:"var(--accent2)",background:"#eff6ff"},policyLabel:{fontSize:"0.88rem",fontWeight:600,color:"var(--ink)"},empty:{textAlign:"center",padding:"4rem 2rem",color:"var(--muted)",display:"flex",flexDirection:"column",alignItems:"center",gap:"0.75rem"},link:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"inherit",textDecoration:"underline"},queueBanner:{display:"flex",alignItems:"center",gap:"0.75rem",background:"#eff6ff",border:"1.5px solid var(--accent2)",borderRadius:12,padding:"0.75rem 1rem",marginBottom:"1.25rem"},queueIcon:{fontSize:"1.4rem"},queueName:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"0.95rem"},queueProgress:{color:"var(--accent2)",fontSize:"0.82rem",marginTop:"0.1rem"},queueDots:{display:"flex",gap:"0.35rem",alignItems:"center"},queueDot:{width:10,height:10,borderRadius:"50%",transition:"background 0.3s"},queueExit:{background:"none",border:"1px solid var(--border)",borderRadius:6,padding:"0.3rem 0.6rem",fontSize:"0.78rem",cursor:"pointer",color:"var(--muted)"},pollCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1.5rem"},timerRow:{display:"flex",alignItems:"center",gap:"1rem"},pollQuestion:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.1rem"},responseMeta:{color:"var(--muted)",fontSize:"0.85rem",marginTop:"0.2rem"},expiredBadge:{width:72,height:72,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.8rem",flexShrink:0},expiredTag:{color:"var(--accent)",fontWeight:500},optionRow:{display:"flex",alignItems:"center",gap:"0.75rem"},optionLabel:{width:28,height:28,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.8rem",fontWeight:700,flexShrink:0},correctLabel:{background:"#dcfce7",color:"var(--success)"},barBg:{height:8,borderRadius:4,background:"var(--cream)",overflow:"hidden"},barFill:{height:"100%",borderRadius:4,transition:"width 0.4s ease"},answeredChip:{background:"#dbeafe",color:"var(--accent2)",borderRadius:4,padding:"0.15rem 0.5rem",fontSize:"0.78rem"},correctBtn:{width:32,height:32,borderRadius:"50%",border:"2px solid var(--border)",background:"var(--cream)",cursor:"pointer",fontWeight:700,fontSize:"0.8rem",flexShrink:0,transition:"all 0.15s"},correctBtnActive:{background:"var(--success)",color:"white",borderColor:"var(--success)"},removeBtn:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",fontSize:"0.9rem",padding:"0.25rem",borderRadius:4},controls:{marginTop:"1.25rem",paddingTop:"1.25rem",borderTop:"1px solid var(--border)"},controlGrid:{display:"flex",gap:"1rem",alignItems:"center",flexWrap:"wrap"},controlItem:{display:"flex",alignItems:"center",gap:"0.6rem"},controlLabel:{fontSize:"0.85rem",color:"var(--muted)"},statusSummary:{display:"flex",gap:"0.75rem",flexWrap:"wrap"}};function vb(){var D;const t=Sr(),[e,n]=C.useState(""),[r,i]=C.useState(!1),[s,o]=C.useState(null),[l,a]=C.useState(null),[u,h]=C.useState(!1),[d,f]=C.useState(0),[v,w]=C.useState(null),_=C.useRef(null),E=C.useRef(null);C.useEffect(()=>dh(X=>{!X&&s&&(w(s),setTimeout(()=>w(null),1e4)),X&&X.id!==E.current&&(a(null),h(!1),E.current=X.id),o(X),X&&!X.ended&&f(Math.max(0,Math.round(X.duration-(Date.now()-X.startedAt)/1e3)))}),[s]),C.useEffect(()=>(clearInterval(_.current),s&&!s.ended&&(_.current=setInterval(()=>{const Y=Math.max(0,Math.round(s.duration-(Date.now()-s.startedAt)/1e3));f(Y),Y===0&&clearInterval(_.current)},500)),()=>clearInterval(_.current)),[s==null?void 0:s.id,s==null?void 0:s.ended]),C.useEffect(()=>{if(!r||!e)return;const Y=()=>vc(e);return window.addEventListener("beforeunload",Y),()=>{Y(),window.removeEventListener("beforeunload",Y)}},[r,e]);function g(Y){Y.preventDefault();const X=e.trim();X&&T_(X).then(()=>i(!0))}function p(Y){u||d===0||s!=null&&s.ended||a(Y)}function m(){l===null||u||!s||(b_(e,s.id,l),h(!0))}const S=s&&((D=s.responses)==null?void 0:D[e])!==void 0,I=S?s.responses[e]:l,P=s?Object.keys(s.responses||{}).length:0,b=(s==null?void 0:s.ended)||d===0;function A(){return s?s.revealResults?!0:s.resultPolicy==="never"||s.resultPolicy==="manual"?!1:s.resultPolicy==="on_submit"?u||S:!1:!1}function q(){return!s||s.correctIndex==null?!1:s.revealCorrect?!0:s.correctPolicy==="never"||s.correctPolicy==="manual"?!1:s.correctPolicy==="with_results"?A():!1}const z=A(),pe=q();return r?!s&&!v?c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.waitCard,className:"fade-up",children:[c.jsx("div",{style:se.pulse}),c.jsxs("h2",{style:{fontFamily:"var(--font-display)",fontSize:"1.5rem"},children:["Hi, ",e,"! πŸ‘‹"]}),c.jsx("p",{style:{color:"var(--muted)"},children:"Waiting for the instructor to start a poll…"}),c.jsx("button",{style:se.backLink,onClick:()=>{vc(e),t("/")},children:"Leave session"})]})}):!s&&v?c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.waitCard,className:"fade-up",children:[c.jsx("span",{style:{fontSize:"2.5rem"},children:"βœ…"}),c.jsx("h2",{style:{fontFamily:"var(--font-display)"},children:"Poll closed!"}),c.jsx("p",{style:{color:"var(--muted)",textAlign:"center"},children:c.jsx("em",{children:v.question})}),v.correctIndex!=null&&v.revealCorrect&&c.jsxs("p",{style:{color:"var(--success)",fontWeight:600},children:["Correct answer: ",v.options[v.correctIndex]]}),c.jsx("p",{style:{color:"var(--muted)",fontSize:"0.85rem"},children:"Waiting for next poll…"})]})}):c.jsxs("div",{style:se.pollPage,children:[c.jsxs("header",{style:se.pollHeader,children:[c.jsxs("span",{style:{fontFamily:"var(--font-display)",fontWeight:700},children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsxs("span",{style:{color:"var(--muted)",fontSize:"0.9rem"},children:["Signed in as ",c.jsx("strong",{children:e})]})]}),c.jsxs("div",{style:se.pollContent,className:"fade-up",children:[!s.ended&&c.jsxs(c.Fragment,{children:[c.jsx("div",{style:se.timerBar,children:c.jsx("div",{style:{...se.timerFill,width:`${d/s.duration*100}%`,background:d>s.duration*.4?"var(--accent2)":d>s.duration*.15?"#f59e0b":"var(--accent)"}})}),c.jsxs("div",{style:se.timerLabel,children:[d,"s remaining Β· ",P," responded"]})]}),s.ended&&c.jsx("div",{style:se.stoppedBanner,children:"⏰ Time's up β€” waiting for instructor"}),c.jsx("h2",{style:se.questionText,children:s.question}),c.jsx("div",{style:se.optionGrid,children:s.options.map((Y,X)=>{const et=I===X,Ee=s.correctIndex===X,Be=Object.values(s.responses||{}).filter(U=>U===X).length,R=P>0?Math.round(Be/P*100):0;return c.jsxs("button",{style:{...se.optionBtn,...et?se.optionSelected:{},...pe&&Ee?se.optionCorrect:{},...b||S?{cursor:"default"}:{}},onClick:()=>p(X),disabled:b||S,children:[c.jsx("span",{style:se.optionLetter,children:String.fromCharCode(65+X)}),c.jsx("span",{style:{flex:1,textAlign:"left"},children:Y}),z&&c.jsxs("span",{style:se.optionPct,children:[R,"%"]}),z&&c.jsx("div",{style:{...se.optionBar,width:`${R}%`,background:pe&&Ee?"rgba(22,163,74,0.15)":"rgba(37,99,235,0.1)"}})]},X)})}),!S&&!u&&!b&&c.jsx("button",{className:"btn btn-primary",style:{width:"100%",justifyContent:"center",padding:"0.85rem",fontSize:"1rem",marginTop:"0.5rem"},onClick:m,disabled:l===null,children:"Submit Answer"}),(u||S)&&!b&&c.jsx("div",{style:se.submittedBadge,children:"βœ“ Answer submitted"}),b&&!S&&!u&&c.jsx("div",{style:{...se.submittedBadge,background:"#fef9c3",color:"#854d0e",borderColor:"#fef08a"},children:"⏰ Time's up β€” no answer recorded"}),b&&(S||u)&&c.jsx("div",{style:se.submittedBadge,children:"βœ“ Answer submitted β€” waiting for instructor"})]})]}):c.jsx("div",{style:se.center,children:c.jsxs("div",{style:se.joinCard,className:"fade-up",children:[c.jsxs("div",{style:se.joinLogo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsx("h1",{style:{fontSize:"1.8rem",marginBottom:"0.25rem"},children:"Join Session"}),c.jsx("p",{style:{color:"var(--muted)",marginBottom:"1.5rem"},children:"Enter your name to start answering polls"}),c.jsxs("form",{onSubmit:g,style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[c.jsx("input",{className:"input",placeholder:"Your first name",value:e,onChange:Y=>n(Y.target.value),autoFocus:!0,style:{fontSize:"1.1rem",textAlign:"center"},required:!0}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{justifyContent:"center",padding:"0.75rem"},children:"Join β†’"})]}),c.jsx("button",{style:se.backLink,onClick:()=>t("/"),children:"← Back"})]})})}const se={center:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"var(--paper)"},joinCard:{background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"2.5rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},joinLogo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",marginBottom:"1.5rem",display:"block"},backLink:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",marginTop:"1rem",fontSize:"0.85rem",display:"block",textAlign:"center"},waitCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:"0.75rem",background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"3rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},pulse:{width:16,height:16,borderRadius:"50%",background:"var(--accent2)",boxShadow:"0 0 0 0 rgba(37,99,235,0.4)",animation:"pulse-ring 1.5s ease-out infinite"},pollPage:{minHeight:"100vh",background:"var(--paper)",display:"flex",flexDirection:"column"},pollHeader:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",display:"flex",justifyContent:"space-between",alignItems:"center",background:"white"},pollContent:{maxWidth:620,margin:"0 auto",padding:"2rem 1rem",width:"100%"},timerBar:{height:6,background:"var(--cream)",borderRadius:3,overflow:"hidden",marginBottom:"0.4rem"},timerFill:{height:"100%",borderRadius:3,transition:"width 0.5s linear, background 0.5s"},timerLabel:{color:"var(--muted)",fontSize:"0.82rem",marginBottom:"1.5rem"},stoppedBanner:{background:"#fef9c3",color:"#854d0e",border:"1px solid #fef08a",borderRadius:8,padding:"0.6rem 1rem",fontSize:"0.9rem",marginBottom:"1.5rem",textAlign:"center"},questionText:{fontFamily:"var(--font-display)",fontSize:"clamp(1.2rem, 3vw, 1.6rem)",lineHeight:1.25,marginBottom:"1.25rem"},optionGrid:{display:"flex",flexDirection:"column",gap:"0.6rem"},optionBtn:{position:"relative",overflow:"hidden",display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.9rem 1rem",borderRadius:10,border:"2px solid var(--border)",background:"white",cursor:"pointer",transition:"all 0.15s",textAlign:"left",fontFamily:"var(--font-body)",fontSize:"0.95rem"},optionSelected:{borderColor:"var(--accent2)",background:"#eff6ff"},optionCorrect:{borderColor:"var(--success)",background:"#f0fdf4"},optionLetter:{width:28,height:28,borderRadius:"50%",background:"var(--cream)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.8rem",fontWeight:700,flexShrink:0},optionPct:{color:"var(--muted)",fontSize:"0.82rem",fontWeight:600,flexShrink:0,zIndex:1},optionBar:{position:"absolute",left:0,top:0,height:"100%",transition:"width 0.4s ease",zIndex:0,pointerEvents:"none"},submittedBadge:{marginTop:"1rem",padding:"0.75rem",borderRadius:8,background:"#f0fdf4",color:"var(--success)",textAlign:"center",fontWeight:500,fontSize:"0.9rem",border:"1px solid #bbf7d0"}};function U_(t,e={}){const{duration:n=60,resultPolicy:r="on_submit",correctPolicy:i="with_results"}=e,s=t.split(/^---$/m).map(l=>l.trim()).filter(Boolean),o=[];for(const l of s){const a=l.split(` +`);let u="",h=[],d=null,f=n,v=r,w=i,_=0;for(;_=a.length)){for(u=a[_].replace(/^Q:\s*/i,"").trim(),_++;_{const r=[];return n.duration!==e.duration&&r.push(`duration: ${n.duration}`),n.resultPolicy!==e.resultPolicy&&r.push(`results: ${n.resultPolicy}`),n.correctPolicy!==e.correctPolicy&&r.push(`correct: ${n.correctPolicy}`),r.push(`Q: ${n.question}`),r.push(""),n.options.forEach((i,s)=>{const o=n.correctIndex===s?"* ":" ";r.push(`${o}${String.fromCharCode(65+s)}. ${i}`)}),r.join(` +`)}).join(` +--- +`)}const _b=[{value:"on_submit",label:"After they submit"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}],wb=[{value:"with_results",label:"With results"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}];function Sb(){const{id:t}=HS(),e=Sr(),[n,r]=C.useState(null),[i,s]=C.useState([]),[o,l]=C.useState(0),[a,u]=C.useState("form"),[h,d]=C.useState(""),[f,v]=C.useState(!1),[w,_]=C.useState(""),[E,g]=C.useState(!1),[p,m]=C.useState(!1),[S,I]=C.useState("");C.useEffect(()=>(localStorage.getItem("role")!=="instructor"&&e("/"),D_(t,y=>{y&&(r(y),s(y.polls||[]),I(y.name||""))})),[t]),C.useEffect(()=>{a==="text"&&n&&(d(yb(i,n.defaults||{})),v(!1),_(""))},[a]);function P(y){const x=(n==null?void 0:n.defaults)||{};return{...y,duration:y.duration??x.duration??60,resultPolicy:y.resultPolicy??x.resultPolicy??"on_submit",correctPolicy:y.correctPolicy??x.correctPolicy??"with_results"}}function b(y,x){s(i.map((T,O)=>O===o?{...T,[y]:x}:T))}function A(y,x){const T=P(i[o]).options.map((O,K)=>K===y?x:O);b("options",T)}function q(){const y=[...i[o].options||[],""];y.length<=6&&b("options",y)}function z(y){const x=i[o],T=x.options.filter((K,tt)=>tt!==y);if(T.length<2)return;let O=x.correctIndex;O===y?O=null:O>y&&(O=O-1),s(i.map((K,tt)=>tt===o?{...K,options:T,correctIndex:O}:K))}function pe(){const y=[...i,{question:"",options:["",""],correctIndex:null}];s(y),l(y.length-1)}function D(y){if(i.length<=1)return;const x=i.filter((T,O)=>O!==y);s(x),l(Math.min(y,x.length-1))}function Y(y,x){const T=y+x;if(T<0||T>=i.length)return;const O=[...i];[O[y],O[T]]=[O[T],O[y]],s(O),l(T)}function X(){_("");try{const y=U_(h,n.defaults||{});if(y.length===0){_("No polls found. Check your formatting.");return}s(y),v(!1),u("form"),l(0)}catch(y){_(y.message)}}async function et(){await Lo(t,{polls:i}),g(!0),setTimeout(()=>g(!1),2e3)}async function Ee(){await Lo(t,{name:S.trim()}),m(!1)}async function Be(){if(!i||i.length===0){alert("No polls in this set.");return}await Lo(t,{polls:i});const y=n.defaults||{},x=i[0];await L_(n.id,n.name,i.length),await Pl({question:x.question,options:x.options,correctIndex:x.correctIndex??null,duration:x.duration??y.duration??60,resultPolicy:x.resultPolicy??y.resultPolicy??"on_submit",correctPolicy:x.correctPolicy??y.correctPolicy??"with_results"}),e("/instructor")}if(!n)return c.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"var(--muted)"},children:"Loading…"});const R=i[o]?P(i[o]):null,U=n.defaults||{};return c.jsxs("div",{style:Z.page,children:[c.jsxs("header",{style:Z.header,children:[c.jsx("button",{style:Z.back,onClick:()=>e("/pollsets"),children:"← Poll Sets"}),c.jsx("div",{style:Z.titleArea,children:p?c.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[c.jsx("input",{className:"input",value:S,onChange:y=>I(y.target.value),style:{fontSize:"1rem",padding:"0.4rem 0.6rem"},autoFocus:!0,onKeyDown:y=>{y.key==="Enter"&&Ee(),y.key==="Escape"&&m(!1)}}),c.jsx("button",{className:"btn btn-primary",style:{padding:"0.4rem 0.8rem",fontSize:"0.85rem"},onClick:Ee,children:"Save"}),c.jsx("button",{className:"btn btn-secondary",style:{padding:"0.4rem 0.8rem",fontSize:"0.85rem"},onClick:()=>m(!1),children:"Cancel"})]}):c.jsxs("span",{style:Z.title,onClick:()=>m(!0),title:"Click to rename",children:[n.name," ✎"]})}),c.jsxs("div",{style:Z.viewToggle,children:[c.jsx("button",{style:{...Z.toggleBtn,...a==="form"?Z.toggleActive:{}},onClick:()=>u("form"),children:"Form view"}),c.jsx("button",{style:{...Z.toggleBtn,...a==="text"?Z.toggleActive:{}},onClick:()=>u("text"),children:"Text view"})]}),c.jsx("button",{className:"btn btn-secondary",onClick:et,style:{background:E?"#dcfce7":void 0,borderColor:E?"var(--success)":void 0,color:E?"var(--success)":void 0},children:E?"βœ“ Saved":"Save Changes"}),c.jsx("button",{className:"btn btn-primary",onClick:Be,children:"Launch β†’"})]}),c.jsxs("div",{style:Z.body,children:[a==="form"&&c.jsxs(c.Fragment,{children:[c.jsxs("aside",{style:Z.pollList,children:[c.jsxs("div",{style:Z.pollListHeader,children:[c.jsxs("span",{style:{fontSize:"0.8rem",color:"var(--muted)",fontWeight:600},children:[i.length," POLL",i.length!==1?"S":""]}),c.jsx("button",{className:"btn btn-ghost",style:{fontSize:"0.78rem",padding:"0.3rem 0.6rem"},onClick:pe,children:"+ Add"})]}),i.map((y,x)=>c.jsxs("div",{style:{...Z.pollItem,...o===x?Z.pollItemActive:{}},onClick:()=>l(x),children:[c.jsx("span",{style:Z.pollItemNum,children:x+1}),c.jsx("span",{style:Z.pollItemQ,children:y.question||c.jsx("em",{style:{color:"var(--muted)"},children:"Untitled"})}),c.jsxs("div",{style:Z.pollItemActions,children:[c.jsx("button",{style:Z.microBtn,onClick:T=>{T.stopPropagation(),Y(x,-1)},disabled:x===0,children:"↑"}),c.jsx("button",{style:Z.microBtn,onClick:T=>{T.stopPropagation(),Y(x,1)},disabled:x===i.length-1,children:"↓"}),c.jsx("button",{style:Z.microBtn,onClick:T=>{T.stopPropagation(),D(x)},disabled:i.length<=1,children:"βœ•"})]})]},x))]}),c.jsx("main",{style:Z.editor,children:R&&c.jsxs("div",{style:Z.editorInner,className:"fade-up",children:[c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Question"}),c.jsx("textarea",{className:"input",rows:3,placeholder:"Enter your question…",value:i[o].question,onChange:y=>b("question",y.target.value),style:{resize:"vertical",width:"100%"}})]}),c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Answer Options"}),c.jsx("p",{style:Z.hint,children:"Click a letter circle to mark the correct answer (optional)"}),c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:R.options.map((y,x)=>c.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[c.jsx("button",{type:"button",style:{...Z.correctBtn,...i[o].correctIndex===x?Z.correctBtnActive:{}},onClick:()=>b("correctIndex",i[o].correctIndex===x?null:x),children:i[o].correctIndex===x?"βœ“":String.fromCharCode(65+x)}),c.jsx("input",{className:"input",style:{flex:1},placeholder:`Option ${String.fromCharCode(65+x)}`,value:y,onChange:T=>A(x,T.target.value)}),c.jsx("button",{style:Z.removeBtn,onClick:()=>z(x),disabled:R.options.length<=2,children:"βœ•"})]},x))}),R.options.length<6&&c.jsx("button",{className:"btn btn-ghost",style:{marginTop:"0.5rem",fontSize:"0.85rem"},onClick:q,children:"+ Add option"})]}),c.jsxs("div",{style:Z.overridesBox,children:[c.jsxs("label",{className:"label",children:["Per-poll overrides",c.jsx("span",{style:{color:"var(--muted)",textTransform:"none",letterSpacing:0,marginLeft:"0.5rem",fontWeight:400,fontSize:"0.78rem"},children:"(leave blank to use set defaults)"})]}),c.jsxs("div",{style:Z.overridesRow,children:[c.jsxs("div",{children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Duration (s)"}),c.jsx("input",{className:"input",type:"number",min:10,max:300,placeholder:`default: ${U.duration??60}`,value:i[o].duration??"",onChange:y=>b("duration",y.target.value===""?null:Number(y.target.value)),style:{width:100}})]}),c.jsxs("div",{children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Show results"}),c.jsxs("select",{className:"input",value:i[o].resultPolicy??"",onChange:y=>b("resultPolicy",y.target.value||null),children:[c.jsxs("option",{value:"",children:["Set default (",U.resultPolicy??"on_submit",")"]}),_b.map(y=>c.jsx("option",{value:y.value,children:y.label},y.value))]})]}),c.jsxs("div",{children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Reveal answer"}),c.jsxs("select",{className:"input",value:i[o].correctPolicy??"",onChange:y=>b("correctPolicy",y.target.value||null),children:[c.jsxs("option",{value:"",children:["Set default (",U.correctPolicy??"with_results",")"]}),wb.map(y=>c.jsx("option",{value:y.value,children:y.label},y.value))]})]})]})]})]})})]}),a==="text"&&c.jsxs("div",{style:Z.textView,children:[c.jsxs("p",{style:Z.textHint,children:["Edit all polls as plain text. Use ",c.jsx("code",{children:"---"})," to separate polls. Per-poll overrides: ",c.jsx("code",{children:"duration: 90"}),", ",c.jsx("code",{children:"results: manual"}),", ",c.jsx("code",{children:"correct: never"}),". Click ",c.jsx("strong",{children:"Apply Changes"})," to update the form view, then ",c.jsx("strong",{children:"Save Changes"})," to persist."]}),c.jsx("textarea",{className:"input",value:h,onChange:y=>{d(y.target.value),v(!0),_("")},style:{fontFamily:"monospace",fontSize:"0.88rem",minHeight:"60vh",resize:"vertical",width:"100%"}}),w&&c.jsx("p",{style:Z.err,children:w}),c.jsxs("div",{style:{display:"flex",gap:"0.75rem",marginTop:"0.75rem"},children:[c.jsx("button",{className:"btn btn-primary",onClick:X,disabled:!f,children:"Apply Changes β†’"}),c.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("form"),_("")},children:"Cancel"})]})]})]})]})}const Z={page:{minHeight:"100vh",background:"var(--paper)",display:"flex",flexDirection:"column"},header:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",background:"white",display:"flex",alignItems:"center",gap:"0.75rem",flexWrap:"wrap"},back:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"0.9rem"},titleArea:{flex:1},title:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.15rem",cursor:"pointer",borderBottom:"1px dashed var(--border)"},viewToggle:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:8,padding:"0.25rem"},toggleBtn:{background:"none",border:"none",padding:"0.35rem 0.85rem",borderRadius:6,cursor:"pointer",fontSize:"0.85rem",color:"var(--muted)"},toggleActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},body:{display:"flex",flex:1,overflow:"hidden"},pollList:{width:220,borderRight:"1px solid var(--border)",background:"white",display:"flex",flexDirection:"column",overflowY:"auto"},pollListHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",borderBottom:"1px solid var(--border)"},pollItem:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.75rem 1rem",cursor:"pointer",borderBottom:"1px solid var(--cream)",transition:"background 0.1s"},pollItemActive:{background:"#eff6ff",borderLeft:"3px solid var(--accent2)"},pollItemNum:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"0.8rem",color:"var(--muted)",flexShrink:0,marginTop:"0.1rem"},pollItemQ:{fontSize:"0.82rem",flex:1,lineHeight:1.4,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},pollItemActions:{display:"flex",flexDirection:"column",gap:"0.15rem",flexShrink:0},microBtn:{background:"none",border:"none",cursor:"pointer",fontSize:"0.7rem",color:"var(--muted)",padding:"0.1rem 0.2rem",lineHeight:1},editor:{flex:1,overflowY:"auto",padding:"1.5rem"},editorInner:{maxWidth:"100%",display:"flex",flexDirection:"column",gap:"1.25rem"},hint:{fontSize:"0.82rem",color:"var(--muted)",marginBottom:"0.5rem"},overridesBox:{background:"var(--cream)",borderRadius:10,padding:"1rem",display:"flex",flexDirection:"column",gap:"0.75rem"},overridesRow:{display:"flex",gap:"1rem",flexWrap:"wrap",alignItems:"flex-end"},correctBtn:{width:32,height:32,borderRadius:"50%",border:"2px solid var(--border)",background:"var(--cream)",cursor:"pointer",fontWeight:700,fontSize:"0.8rem",flexShrink:0,transition:"all 0.15s"},correctBtnActive:{background:"var(--success)",color:"white",borderColor:"var(--success)"},removeBtn:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",fontSize:"0.9rem",padding:"0.25rem",borderRadius:4},textView:{flex:1,padding:"1.5rem",display:"flex",flexDirection:"column",gap:"0.75rem"},textHint:{fontSize:"0.85rem",color:"var(--muted)",lineHeight:1.6},err:{color:"var(--accent)",fontSize:"0.85rem"}},$p={duration:60,resultPolicy:"on_submit",correctPolicy:"with_results"},Vp=[{value:"on_submit",label:"After they submit"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}],Hp=[{value:"with_results",label:"With results"},{value:"manual",label:"When I choose"},{value:"never",label:"Never"}];function Cb(){const t=Sr(),[e,n]=C.useState([]),[r,i]=C.useState("list"),[s,o]=C.useState(null),[l,a]=C.useState(!1),[u,h]=C.useState(""),[d,f]=C.useState(""),[v,w]=C.useState($p),[_,E]=C.useState("text"),[g,p]=C.useState(""),[m,S]=C.useState(null),[I,P]=C.useState("");C.useEffect(()=>(localStorage.getItem("role")!=="instructor"&&t("/"),A_(n)),[]);function b(){f(""),w($p),E("text"),p(""),S(null),P(""),h("")}function A(){P("");try{const D=U_(g,v);if(D.length===0){P("No polls found. Check your formatting.");return}S(D)}catch(D){P(D.message)}}async function q(){if(h(""),!d.trim()){h("Please enter a set name.");return}if(!m||m.length===0){h("Preview your polls first.");return}a(!0);try{const D=await _c({name:d.trim(),defaults:v,polls:m});b(),i("list"),t(`/pollsets/${D}`)}catch(D){h("Error saving: "+D.message)}finally{a(!1)}}async function z(){if(h(""),!d.trim()){h("Please enter a set name.");return}a(!0);try{const D=await _c({name:d.trim(),defaults:v,polls:[]});b(),i("list"),t(`/pollsets/${D}`)}catch(D){h("Error saving: "+D.message)}finally{a(!1)}}function pe(D){O_(D),o(null)}return c.jsxs("div",{style:Q.page,children:[c.jsxs("header",{style:Q.header,children:[c.jsx("button",{style:Q.back,onClick:()=>t("/instructor"),children:"← Dashboard"}),c.jsx("span",{style:Q.title,children:"Poll Sets"}),r==="list"&&c.jsx("button",{className:"btn btn-primary",onClick:()=>i("create"),children:"+ New Set"}),r==="create"&&c.jsx("button",{className:"btn btn-secondary",onClick:()=>{i("list"),b()},children:"Cancel"})]}),c.jsxs("main",{style:Q.main,children:[r==="list"&&c.jsxs("div",{className:"fade-up",children:[e.length===0&&c.jsxs("div",{style:Q.empty,children:[c.jsx("span",{style:{fontSize:"2.5rem"},children:"πŸ“š"}),c.jsx("p",{children:"No poll sets yet."}),c.jsx("button",{className:"btn btn-primary",onClick:()=>i("create"),children:"Create your first set β†’"})]}),e.map(D=>{const Y=s===D.id;return c.jsxs("div",{style:Q.setCard,children:[c.jsxs("button",{style:Q.setCardBtn,onClick:()=>t(`/pollsets/${D.id}`),children:[c.jsxs("div",{children:[c.jsx("div",{style:Q.setName,children:D.name}),c.jsxs("div",{style:Q.setMeta,children:[(D.polls||[]).length," poll",(D.polls||[]).length!==1?"s":""," Β· Created ",new Date(D.createdAt).toLocaleDateString()]})]}),c.jsx("span",{style:{color:"var(--muted)"},children:"β†’"})]}),c.jsx("div",{style:Q.setActions,children:Y?c.jsxs("div",{style:Q.confirmRow,children:[c.jsx("span",{style:Q.confirmText,children:"Delete?"}),c.jsx("button",{className:"btn btn-primary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem",background:"#dc2626"},onClick:()=>pe(D.id),children:"Yes"}),c.jsx("button",{className:"btn btn-secondary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem"},onClick:()=>o(null),children:"Cancel"})]}):c.jsx("button",{style:Q.deleteBtn,onClick:()=>o(D.id),children:"πŸ—‘"})})]},D.id)})]}),r==="create"&&c.jsxs("div",{className:"fade-up",style:Q.createForm,children:[c.jsx("h2",{style:Q.sectionTitle,children:"New Poll Set"}),c.jsxs("div",{children:[c.jsx("label",{className:"label",children:"Set Name"}),c.jsx("input",{className:"input",placeholder:"e.g. Chapter 5 Review",value:d,onChange:D=>f(D.target.value),autoFocus:!0})]}),c.jsxs("div",{style:Q.defaultsBox,children:[c.jsx("label",{className:"label",children:"Default settings for all polls in this set"}),c.jsxs("div",{style:Q.defaultsRow,children:[c.jsxs("div",{children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Duration (seconds)"}),c.jsx("input",{className:"input",type:"number",min:10,max:300,value:v.duration,onChange:D=>w({...v,duration:Number(D.target.value)}),style:{width:100}})]}),c.jsxs("div",{style:{flex:1},children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Show results to students"}),c.jsx("select",{className:"input",value:v.resultPolicy,onChange:D=>w({...v,resultPolicy:D.target.value}),children:Vp.map(D=>c.jsx("option",{value:D.value,children:D.label},D.value))})]}),c.jsxs("div",{style:{flex:1},children:[c.jsx("label",{className:"label",style:{fontSize:"0.72rem"},children:"Reveal correct answer"}),c.jsx("select",{className:"input",value:v.correctPolicy,onChange:D=>w({...v,correctPolicy:D.target.value}),children:Hp.map(D=>c.jsx("option",{value:D.value,children:D.label},D.value))})]})]})]}),c.jsxs("div",{children:[c.jsxs("div",{style:Q.modeTabs,children:[c.jsx("button",{style:{...Q.modeTab,..._==="text"?Q.modeTabActive:{}},onClick:()=>E("text"),children:"Paste text"}),c.jsx("button",{style:{...Q.modeTab,..._==="manual"?Q.modeTabActive:{}},onClick:()=>E("manual"),children:"Build manually"})]}),_==="text"&&c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[c.jsx("textarea",{className:"input",rows:14,placeholder:`Q: What is photosynthesis? + +* A. Converts sunlight into energy + B. Breaks down glucose + C. Absorbs water through roots + D. Releases CO2 +--- +Q: Which organelle contains chlorophyll? +duration: 90 + + A. Mitochondria +* B. Chloroplast + C. Nucleus + D. Vacuole`,value:g,onChange:D=>{p(D.target.value),S(null),P("")},style:{fontFamily:"monospace",fontSize:"0.85rem",resize:"vertical",minHeight:"320px",width:"100%"}}),c.jsxs("div",{style:{display:"flex",gap:"0.75rem",alignItems:"center"},children:[c.jsx("button",{className:"btn btn-secondary",onClick:A,children:"Preview β†’"}),I&&c.jsx("span",{style:Q.err,children:I})]})]}),_==="manual"&&c.jsxs("div",{style:Q.manualBox,children:[c.jsx("p",{children:"The set will be created empty. You can add and edit polls one by one in the set detail view."}),u&&c.jsx("p",{style:Q.err,children:u}),c.jsx("button",{className:"btn btn-primary",style:{marginTop:"0.5rem"},onClick:z,disabled:l,children:l?"Creating…":"Create empty set β†’"})]})]}),_==="text"&&m&&c.jsxs("div",{style:Q.previewBox,children:[c.jsxs("label",{className:"label",children:["Preview β€” ",m.length," poll",m.length!==1?"s":""," found"]}),m.map((D,Y)=>{var X,et;return c.jsxs("div",{style:Q.previewPoll,children:[c.jsxs("div",{style:Q.previewQ,children:[Y+1,". ",D.question]}),c.jsx("div",{style:Q.previewOptions,children:D.options.map((Ee,Be)=>c.jsxs("div",{style:{...Q.previewOpt,...D.correctIndex===Be?Q.previewOptCorrect:{}},children:[D.correctIndex===Be?"βœ“":String.fromCharCode(65+Be),". ",Ee]},Be))}),c.jsxs("div",{style:Q.previewMeta,children:[D.duration,"s Β· Results: ",(X=Vp.find(Ee=>Ee.value===D.resultPolicy))==null?void 0:X.label," Β· Answer: ",(et=Hp.find(Ee=>Ee.value===D.correctPolicy))==null?void 0:et.label]})]},Y)}),u&&c.jsx("p",{style:Q.err,children:u}),c.jsx("button",{className:"btn btn-primary",onClick:q,disabled:l,children:l?"Saving…":"Save Set β†’"})]})]})]})]})}const Q={page:{minHeight:"100vh",background:"var(--paper)"},header:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",background:"white",display:"flex",alignItems:"center",gap:"1rem"},back:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"0.9rem"},title:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.2rem",flex:1},main:{maxWidth:960,margin:"0 auto",padding:"1.5rem 1rem"},empty:{textAlign:"center",padding:"4rem 2rem",color:"var(--muted)",display:"flex",flexDirection:"column",alignItems:"center",gap:"1rem"},setCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",marginBottom:"0.75rem",display:"flex",alignItems:"center",overflow:"hidden"},setCardBtn:{display:"flex",alignItems:"center",justifyContent:"space-between",flex:1,padding:"1rem",background:"none",border:"none",cursor:"pointer",textAlign:"left"},setName:{fontFamily:"var(--font-display)",fontWeight:600,fontSize:"1rem"},setMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},setActions:{padding:"0 0.75rem",display:"flex",alignItems:"center",gap:"0.4rem"},deleteBtn:{background:"none",border:"none",cursor:"pointer",fontSize:"1.1rem",padding:"0.25rem 0.4rem",borderRadius:6,opacity:.5},confirmRow:{display:"flex",alignItems:"center",gap:"0.4rem"},confirmText:{fontSize:"0.82rem",color:"var(--muted)",whiteSpace:"nowrap"},createForm:{display:"flex",flexDirection:"column",gap:"1.25rem"},sectionTitle:{fontSize:"1.4rem"},defaultsBox:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1rem",display:"flex",flexDirection:"column",gap:"0.75rem"},defaultsRow:{display:"flex",gap:"0.75rem",flexWrap:"wrap",alignItems:"flex-end"},modeTabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:8,padding:"0.25rem",marginBottom:"0.75rem",width:"fit-content"},modeTab:{background:"none",border:"none",padding:"0.35rem 0.85rem",borderRadius:6,cursor:"pointer",fontSize:"0.9rem",color:"var(--muted)"},modeTabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},manualBox:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1.25rem",color:"var(--muted)",fontSize:"0.9rem",display:"flex",flexDirection:"column",gap:"0.5rem"},previewBox:{background:"white",borderRadius:12,border:"1px solid var(--border)",padding:"1.25rem",display:"flex",flexDirection:"column",gap:"0.75rem"},previewPoll:{borderBottom:"1px solid var(--border)",paddingBottom:"0.75rem",display:"flex",flexDirection:"column",gap:"0.4rem"},previewQ:{fontWeight:600,fontSize:"0.95rem"},previewOptions:{display:"flex",flexDirection:"column",gap:"0.2rem",paddingLeft:"0.75rem"},previewOpt:{fontSize:"0.88rem",color:"var(--muted)"},previewOptCorrect:{color:"var(--success)",fontWeight:600},previewMeta:{fontSize:"0.75rem",color:"var(--muted)",marginTop:"0.25rem"},err:{color:"var(--accent)",fontSize:"0.85rem"}};function Eb(t,e=40){return t.length>e?t.slice(0,e)+"...":t}function xb(t){if(t==null)return"";const e=String(t);return e.includes(",")||e.includes('"')||e.includes(` +`)?`"${e.replace(/"/g,'""')}"`:e}function nt(t){return t.map(xb).join(",")}function Ib(t){const e=t.responses||{},n=t.correctIndex!=null,r=[];r.push(nt(["Question",t.question])),r.push(nt(["Date",new Date(t.startedAt).toLocaleString()])),n&&r.push(nt(["Correct Answer",`${String.fromCharCode(65+t.correctIndex)}. ${t.options[t.correctIndex]}`])),r.push("");const i=["Student","Response"];n&&i.push("Correct (1=yes 0=no)"),r.push(nt(i));const s=Object.keys(e).sort();return s.length===0?r.push(nt(["(no responses)","",""])):s.forEach(o=>{const l=e[o],a=l!=null?`${String.fromCharCode(65+l)}. ${t.options[l]}`:"(no answer)",u=[o,a];n&&u.push(l===t.correctIndex?"1":"0"),r.push(nt(u))}),r.join(` +`)}function kb(t,e){if(!e||e.length===0)return"";const n=new Set;e.forEach(o=>{Object.keys(o.responses||{}).forEach(l=>n.add(l))});const r=[...n].sort(),i=[];i.push(nt(["Set",t])),i.push(nt(["Date",new Date(e[0].startedAt).toLocaleString()])),i.push(nt(["Polls",e.length])),i.push("");const s=["Student"];return e.forEach((o,l)=>{const a=`Q${l+1}: ${Eb(o.question)}`;s.push(a),o.correctIndex!=null&&s.push(`Q${l+1} Correct (1=yes 0=no)`)}),i.push(nt(s)),r.forEach(o=>{const l=[o];e.forEach(a=>{const h=(a.responses||{})[o],d=h!=null?`${String.fromCharCode(65+h)}. ${a.options[h]}`:"(no answer)";l.push(d),a.correctIndex!=null&&l.push(h===a.correctIndex?"1":"0")}),i.push(nt(l))}),i.push(""),i.push(nt(["Summary"])),e.forEach((o,l)=>{const a=o.responses||{},u=Object.keys(a).length;i.push(""),i.push(nt([`Q${l+1}`,o.question])),o.options.forEach((h,d)=>{const f=Object.values(a).filter(_=>_===d).length,v=u>0?Math.round(f/u*100):0,w=o.correctIndex===d;i.push(nt([`${String.fromCharCode(65+d)}. ${h}`,`${f} responses`,`${v}%`,w?"correct answer":""]))})}),i.join(` +`)}function Gp(t,e){const n=new Blob([e],{type:"text/csv;charset=utf-8;"}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=t,i.click(),URL.revokeObjectURL(r)}const Tb="prof123";function bb(){const t=Sr(),[e,n]=C.useState(!1),[r,i]=C.useState(""),[s,o]=C.useState(""),[l,a]=C.useState([]),[u,h]=C.useState({}),[d,f]=C.useState("polls"),[v,w]=C.useState(new Set),[_,E]=C.useState(new Set),[g,p]=C.useState(null),[m,S]=C.useState(null),[I,P]=C.useState({}),[b,A]=C.useState({});C.useEffect(()=>{(localStorage.getItem("historyAuth")==="true"||localStorage.getItem("role")==="instructor")&&n(!0)},[]),C.useEffect(()=>{if(!e)return;const y=R_(a),x=xr(ne(re,"sessionStudents"),T=>{const O=T.val()||{},K={};Object.values(O).forEach(Ge=>{const L=Ge.date||"unknown";K[L]||(K[L]=new Set),K[L].add(Ge.name)});const tt={};Object.entries(K).forEach(([Ge,L])=>{tt[Ge]=[...L].sort()}),h(tt)});return()=>{y(),x()}},[e]);function q(y){y.preventDefault(),r===Tb?(localStorage.setItem("historyAuth","true"),n(!0)):(o("Incorrect password."),i(""))}function z(y){vr(ne(re,`pollHistory/${y}`)),p(null),w(x=>{const T=new Set(x);return T.delete(y),T})}function pe(y,x){x.forEach(T=>vr(ne(re,`pollHistory/${T.id}`))),S(null),E(T=>{const O=new Set(T);return O.delete(y),O})}function D(y){w(x=>{const T=new Set(x);return T.has(y)?T.delete(y):T.add(y),T})}function Y(y){E(x=>{const T=new Set(x);return T.has(y)?T.delete(y):T.add(y),T})}function X(y,x){P(T=>({...T,[y]:x}))}function et(y){A(x=>({...x,[y]:!0})),setTimeout(()=>A(x=>({...x,[y]:!1})),2e3)}function Ee(y){const x=Ib(y),T=new Date(y.startedAt).toLocaleDateString().replace(/\//g,"-");Gp(`poll_${T}_${y.id}.csv`,x)}function Be(y,x){const T=kb(y,x),O=new Date(x[0].startedAt).toLocaleDateString().replace(/\//g,"-"),K=y.replace(/[^a-z0-9]/gi,"_").toLowerCase();Gp(`session_${K}_${O}.csv`,T)}function R(y){const x={},T=[];return y.forEach(O=>{if(O.setId){const K=O.sessionKey||`${O.setId}_${new Date(O.startedAt).toLocaleDateString()}`;x[K]||(x[K]={key:K,setId:O.setId,setName:O.setName,date:new Date(O.startedAt).toLocaleDateString(),startedAt:O.startedAt,polls:[]}),x[K].polls.push(O)}else T.push(O)}),Object.values(x).forEach(O=>{O.polls.sort((K,tt)=>(K.setPosition??0)-(tt.setPosition??0))}),[...Object.values(x).map(O=>({type:"set",...O})),...T.map(O=>({type:"poll",...O}))].sort((O,K)=>(K.startedAt||0)-(O.startedAt||0))}if(!e)return c.jsx("div",{style:F.center,children:c.jsxs("div",{style:F.loginCard,className:"fade-up",children:[c.jsxs("div",{style:F.loginLogo,children:[c.jsx("span",{style:{color:"var(--accent)"},children:"●"})," ClassPoll"]}),c.jsx("h2",{style:{fontSize:"1.4rem",marginBottom:"0.25rem"},children:"Poll History"}),c.jsx("p",{style:{color:"var(--muted)",marginBottom:"1.5rem",fontSize:"0.9rem"},children:"Enter the instructor password to view history and attendance."}),c.jsxs("form",{onSubmit:q,style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[c.jsx("input",{className:"input",type:"password",placeholder:"Instructor password",value:r,onChange:y=>{i(y.target.value),o("")},autoFocus:!0,style:{textAlign:"center"}}),s&&c.jsx("span",{style:F.err,children:s}),c.jsx("button",{type:"submit",className:"btn btn-primary",style:{justifyContent:"center",padding:"0.75rem"},children:"View History β†’"})]}),c.jsx("button",{style:F.backLink,onClick:()=>t("/"),children:"← Back"})]})});const U=R(l);return c.jsxs("div",{style:F.page,children:[c.jsxs("header",{style:F.header,children:[c.jsx("button",{style:F.back,onClick:()=>t("/"),children:"← Back"}),c.jsx("span",{style:F.title,children:"Poll History"}),c.jsxs("div",{style:F.tabs,children:[c.jsx("button",{style:{...F.tab,...d==="polls"?F.tabActive:{}},onClick:()=>f("polls"),children:"Polls"}),c.jsx("button",{style:{...F.tab,...d==="attendance"?F.tabActive:{}},onClick:()=>f("attendance"),children:"Attendance"})]})]}),c.jsxs("main",{style:F.main,children:[d==="polls"&&c.jsxs("div",{className:"fade-up",children:[U.length===0&&c.jsx("div",{style:F.empty,children:"No polls yet. Run your first one in class!"}),U.map(y=>{if(y.type==="set"){const x=_.has(y.key),T=y.polls.reduce((O,K)=>O+Object.keys(K.responses||{}).length,0);return c.jsxs("div",{style:F.setGroup,children:[c.jsxs("div",{style:F.setGroupHeaderRow,children:[c.jsxs("button",{style:F.setGroupHeaderBtn,onClick:()=>Y(y.key),children:[c.jsx("span",{style:F.triangle,children:x?"β–Ό":"β–Ά"}),c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{style:F.setGroupName,children:["πŸ“š ",y.setName]}),c.jsxs("div",{style:F.setGroupMeta,children:[y.date," Β· ",y.polls.length," polls Β· ",T," total responses"]})]})]}),c.jsxs("div",{style:{display:"flex",gap:"0.4rem",alignItems:"center"},children:[c.jsx("button",{style:{...F.exportBtn,...b[y.key]?F.exportBtnSuccess:{}},onClick:()=>{Be(y.setName,y.polls),et(y.key)},children:b[y.key]?"βœ“ Downloading":"⬇ Session CSV"}),m!==y.key?c.jsx("button",{style:F.deleteBtn,onClick:()=>S(y.key),title:"Delete this session",children:"πŸ—‘"}):c.jsxs("div",{style:F.confirmRow,children:[c.jsxs("span",{style:F.confirmText,children:["Delete all ",y.polls.length," polls?"]}),c.jsx("button",{className:"btn btn-primary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem",background:"#dc2626"},onClick:()=>pe(y.key,y.polls),children:"Yes"}),c.jsx("button",{className:"btn btn-secondary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem"},onClick:()=>S(null),children:"Cancel"})]})]})]}),x&&c.jsx("div",{style:F.setGroupPolls,children:y.polls.map(O=>c.jsx(qp,{poll:O,expanded:v.has(O.id),viewMode:I[O.id]||"summary",confirmDelete:g,copyFeedback:b[O.id],onToggle:()=>D(O.id),onDelete:()=>z(O.id),onConfirmDelete:()=>p(O.id),onCancelDelete:()=>p(null),onSetView:K=>X(O.id,K),onDownload:()=>Ee(O),onDownloadFeedback:()=>et(O.id),positionLabel:`${(O.setPosition??0)+1}.`},O.id))})]},y.key)}return c.jsx(qp,{poll:y,expanded:v.has(y.id),viewMode:I[y.id]||"summary",confirmDelete:g,copyFeedback:b[y.id],onToggle:()=>D(y.id),onDelete:()=>z(y.id),onConfirmDelete:()=>p(y.id),onCancelDelete:()=>p(null),onSetView:x=>X(y.id,x),onDownload:()=>Ee(y),onDownloadFeedback:()=>et(y.id)},y.id)})]}),d==="attendance"&&c.jsxs("div",{className:"fade-up",children:[Object.keys(u).length===0&&c.jsx("div",{style:F.empty,children:"No attendance records yet."}),Object.entries(u).sort(([y],[x])=>x.localeCompare(y)).map(([y,x])=>c.jsxs("div",{style:F.pollCard,children:[c.jsx("div",{style:F.pollHeaderRow,children:c.jsxs("div",{style:{padding:"0.25rem 0"},children:[c.jsx("div",{style:F.pollQ,children:y}),c.jsxs("div",{style:F.pollMeta,children:[x.length," student",x.length!==1?"s":""]})]})}),c.jsx("div",{style:{padding:"0 1rem 1rem",display:"flex",flexWrap:"wrap",gap:"0.4rem"},children:x.map(T=>c.jsx("span",{style:F.chip,children:T},T))})]},y))]})]})]})}function qp({poll:t,expanded:e,viewMode:n,confirmDelete:r,copyFeedback:i,onToggle:s,onDelete:o,onConfirmDelete:l,onCancelDelete:a,onSetView:u,onDownload:h,onDownloadFeedback:d,positionLabel:f}){const v=t.responses||{},w=Object.keys(v).length,_=r===t.id,E=t.correctIndex!=null,g={};return t.options.forEach((p,m)=>{g[m]=[]}),Object.entries(v).forEach(([p,m])=>{g[m]!==void 0?g[m].push(p):g[m]=[p]}),c.jsxs("div",{style:F.pollCard,children:[c.jsxs("div",{style:F.pollHeaderRow,children:[c.jsxs("button",{style:F.pollHeaderBtn,onClick:s,children:[c.jsx("span",{style:F.triangle,children:e?"β–Ό":"β–Ά"}),c.jsxs("div",{children:[c.jsxs("div",{style:F.pollQ,children:[f&&c.jsxs("span",{style:F.posLabel,children:[f," "]}),t.question]}),c.jsxs("div",{style:F.pollMeta,children:[new Date(t.startedAt).toLocaleString()," Β· ",w," response",w!==1?"s":""]})]})]}),c.jsxs("div",{style:{display:"flex",gap:"0.4rem",alignItems:"center"},children:[!_&&c.jsx("button",{style:{...F.exportBtn,...i?F.exportBtnSuccess:{}},onClick:()=>{h(),d()},children:i?"βœ“ Downloading":"⬇ CSV"}),_?c.jsxs("div",{style:F.confirmRow,children:[c.jsx("span",{style:F.confirmText,children:"Delete?"}),c.jsx("button",{className:"btn btn-primary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem",background:"#dc2626"},onClick:o,children:"Yes"}),c.jsx("button",{className:"btn btn-secondary",style:{fontSize:"0.78rem",padding:"0.3rem 0.7rem"},onClick:a,children:"Cancel"})]}):c.jsx("button",{style:F.deleteBtn,onClick:l,title:"Delete",children:"πŸ—‘"})]})]}),e&&c.jsxs("div",{style:F.pollDetails,children:[c.jsxs("div",{style:F.viewTabs,children:[c.jsx("button",{style:{...F.viewTab,...n==="summary"?F.viewTabActive:{}},onClick:()=>u("summary"),children:"Summary"}),c.jsx("button",{style:{...F.viewTab,...n==="students"?F.viewTabActive:{}},onClick:()=>u("students"),children:"By student"})]}),n==="summary"&&c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.6rem"},children:t.options.map((p,m)=>{const S=Object.values(v).filter(b=>b===m).length,I=w>0?Math.round(S/w*100):0,P=E&&t.correctIndex===m;return c.jsxs("div",{style:F.histOpt,children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:4},children:[c.jsxs("span",{style:{fontWeight:P?600:400,color:P?"var(--success)":"inherit"},children:[String.fromCharCode(65+m),". ",p," ",P&&"βœ“"]}),c.jsxs("span",{style:{color:"var(--muted)",fontSize:"0.85rem"},children:[S," (",I,"%)"]})]}),c.jsx("div",{style:F.barBg,children:c.jsx("div",{style:{...F.barFill,width:`${I}%`,background:P?"var(--success)":"var(--accent2)"}})})]},m)})}),n==="students"&&c.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[t.options.map((p,m)=>{const S=g[m]||[],I=E&&t.correctIndex===m;return S.length===0?null:c.jsxs("div",{style:F.answerGroup,children:[c.jsxs("div",{style:{...F.answerGroupHeader,...I?F.answerGroupCorrect:{}},children:[c.jsxs("span",{style:{fontWeight:600},children:[String.fromCharCode(65+m),". ",p]}),I&&c.jsx("span",{style:F.correctTag,children:"βœ“ correct"}),c.jsxs("span",{style:F.answerCount,children:[S.length," student",S.length!==1?"s":""]})]}),c.jsx("div",{style:F.studentNames,children:S.sort().map(P=>c.jsx("span",{style:F.chip,children:P},P))})]},m)}),w===0&&c.jsx("div",{style:{color:"var(--muted)",fontSize:"0.9rem"},children:"No responses."})]})]})]})}const F={center:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"var(--paper)"},loginCard:{background:"white",borderRadius:16,border:"1px solid var(--border)",padding:"2.5rem 2rem",maxWidth:380,width:"100%",textAlign:"center",boxShadow:"var(--shadow)"},loginLogo:{fontFamily:"var(--font-display)",fontWeight:800,fontSize:"1.1rem",marginBottom:"1.5rem",display:"block"},err:{color:"var(--accent)",fontSize:"0.85rem"},backLink:{background:"none",border:"none",color:"var(--muted)",cursor:"pointer",marginTop:"1rem",fontSize:"0.85rem",display:"block",textAlign:"center"},page:{minHeight:"100vh",background:"var(--paper)"},header:{padding:"1rem 1.5rem",borderBottom:"1px solid var(--border)",background:"white",display:"flex",alignItems:"center",gap:"1rem",flexWrap:"wrap"},back:{background:"none",border:"none",color:"var(--accent2)",cursor:"pointer",fontSize:"0.9rem"},title:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"1.2rem",flex:1},tabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:8,padding:"0.25rem"},tab:{background:"none",border:"none",padding:"0.35rem 0.85rem",borderRadius:6,cursor:"pointer",fontSize:"0.9rem",color:"var(--muted)",transition:"all 0.15s"},tabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},main:{maxWidth:760,margin:"0 auto",padding:"1.5rem 1rem"},empty:{textAlign:"center",color:"var(--muted)",padding:"3rem",fontSize:"0.95rem"},setGroup:{background:"white",borderRadius:12,border:"1.5px solid var(--accent2)",marginBottom:"0.75rem",overflow:"hidden"},setGroupHeaderRow:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.85rem 1rem",borderBottom:"1px solid var(--cream)"},setGroupHeaderBtn:{display:"flex",alignItems:"center",gap:"0.75rem",background:"none",border:"none",cursor:"pointer",textAlign:"left",flex:1},setGroupName:{fontFamily:"var(--font-display)",fontWeight:700,fontSize:"0.95rem"},setGroupMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},setGroupPolls:{padding:"0.5rem 0.75rem",display:"flex",flexDirection:"column",gap:"0.4rem"},triangle:{fontSize:"0.7rem",color:"var(--muted)",flexShrink:0},exportBtn:{background:"var(--cream)",border:"1px solid var(--border)",borderRadius:6,padding:"0.3rem 0.65rem",fontSize:"0.78rem",cursor:"pointer",color:"var(--ink)",whiteSpace:"nowrap",transition:"all 0.15s",flexShrink:0},exportBtnSuccess:{background:"#dcfce7",borderColor:"var(--success)",color:"var(--success)"},pollCard:{background:"white",borderRadius:12,border:"1px solid var(--border)",marginBottom:"0.75rem",overflow:"hidden"},pollHeaderRow:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.75rem 1rem"},pollHeaderBtn:{display:"flex",alignItems:"center",gap:"0.6rem",background:"none",border:"none",cursor:"pointer",textAlign:"left",flex:1,padding:"0.25rem 0"},posLabel:{color:"var(--muted)",fontWeight:400},pollQ:{fontFamily:"var(--font-display)",fontWeight:600,fontSize:"0.95rem"},pollMeta:{color:"var(--muted)",fontSize:"0.8rem",marginTop:"0.2rem"},deleteBtn:{background:"none",border:"none",cursor:"pointer",fontSize:"1.1rem",padding:"0.25rem 0.4rem",borderRadius:6,opacity:.5},confirmRow:{display:"flex",alignItems:"center",gap:"0.4rem"},confirmText:{fontSize:"0.82rem",color:"var(--muted)",whiteSpace:"nowrap"},pollDetails:{padding:"0.75rem 1rem 1rem",borderTop:"1px solid var(--border)"},viewTabs:{display:"flex",gap:"0.25rem",background:"var(--cream)",borderRadius:6,padding:"0.2rem",marginBottom:"0.75rem",width:"fit-content"},viewTab:{background:"none",border:"none",padding:"0.25rem 0.65rem",borderRadius:4,cursor:"pointer",fontSize:"0.82rem",color:"var(--muted)"},viewTabActive:{background:"white",color:"var(--ink)",fontWeight:600,boxShadow:"0 1px 2px rgba(0,0,0,0.08)"},histOpt:{marginBottom:"0.6rem"},barBg:{height:6,borderRadius:3,background:"var(--cream)",overflow:"hidden"},barFill:{height:"100%",borderRadius:3,transition:"width 0.3s"},answerGroup:{borderRadius:8,border:"1px solid var(--border)",overflow:"hidden"},answerGroupHeader:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",background:"var(--cream)",flexWrap:"wrap"},answerGroupCorrect:{background:"#dcfce7"},correctTag:{fontSize:"0.75rem",color:"var(--success)",fontWeight:600,background:"#bbf7d0",borderRadius:4,padding:"0.1rem 0.4rem"},answerCount:{marginLeft:"auto",fontSize:"0.78rem",color:"var(--muted)"},studentNames:{padding:"0.5rem 0.75rem",display:"flex",flexWrap:"wrap",gap:"0.35rem"},chip:{background:"var(--cream)",borderRadius:4,padding:"0.2rem 0.5rem",fontSize:"0.78rem",color:"var(--ink)"}};function Pb(){return c.jsx(dC,{basename:"/classroom-polling",children:c.jsxs(aC,{children:[c.jsx(fn,{path:"/",element:c.jsx(fC,{})}),c.jsx(fn,{path:"/instructor",element:c.jsx(mb,{})}),c.jsx(fn,{path:"/student",element:c.jsx(vb,{})}),c.jsx(fn,{path:"/pollsets/:id",element:c.jsx(Sb,{})}),c.jsx(fn,{path:"/pollsets",element:c.jsx(Cb,{})}),c.jsx(fn,{path:"/history",element:c.jsx(bb,{})}),c.jsx(fn,{path:"*",element:c.jsx(oC,{to:"/"})})]})})}Za.createRoot(document.getElementById("root")).render(c.jsx(im.StrictMode,{children:c.jsx(Pb,{})}));