@donotdev/core 0.0.24 → 0.0.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.js CHANGED
@@ -1,4 +1,4 @@
1
- var uo=Object.create;var jt=Object.defineProperty;var lo=Object.getOwnPropertyDescriptor;var po=Object.getOwnPropertyNames;var fo=Object.getPrototypeOf,ho=Object.prototype.hasOwnProperty;var dr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),mo=(t,e)=>{for(var n in e)jt(t,n,{get:e[n],enumerable:!0})},go=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of po(e))!ho.call(t,i)&&i!==n&&jt(t,i,{get:()=>e[i],enumerable:!(r=lo(e,i))||r.enumerable});return t};var pr=(t,e,n)=>(n=t!=null?uo(fo(t)):{},go(e||!t||!t.__esModule?jt(n,"default",{value:t,enumerable:!0}):n,t));var Yi=dr(b=>{"use strict";var er=Symbol.for("react.transitional.element"),Zc=Symbol.for("react.portal"),eu=Symbol.for("react.fragment"),tu=Symbol.for("react.strict_mode"),nu=Symbol.for("react.profiler"),ru=Symbol.for("react.consumer"),iu=Symbol.for("react.context"),ou=Symbol.for("react.forward_ref"),su=Symbol.for("react.suspense"),au=Symbol.for("react.memo"),Wi=Symbol.for("react.lazy"),cu=Symbol.for("react.activity"),Vi=Symbol.iterator;function uu(t){return t===null||typeof t!="object"?null:(t=Vi&&t[Vi]||t["@@iterator"],typeof t=="function"?t:null)}var Gi={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},qi=Object.assign,ji={};function De(t,e,n){this.props=t,this.context=e,this.refs=ji,this.updater=n||Gi}De.prototype.isReactComponent={};De.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("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")};De.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Ki(){}Ki.prototype=De.prototype;function tr(t,e,n){this.props=t,this.context=e,this.refs=ji,this.updater=n||Gi}var nr=tr.prototype=new Ki;nr.constructor=tr;qi(nr,De.prototype);nr.isPureReactComponent=!0;var Bi=Array.isArray;function Zn(){}var _={H:null,A:null,T:null,S:null},zi=Object.prototype.hasOwnProperty;function rr(t,e,n){var r=n.ref;return{$$typeof:er,type:t,key:e,ref:r!==void 0?r:null,props:n}}function lu(t,e){return rr(t.type,e,t.props)}function ir(t){return typeof t=="object"&&t!==null&&t.$$typeof===er}function du(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var Hi=/\/+/g;function Qn(t,e){return typeof t=="object"&&t!==null&&t.key!=null?du(""+t.key):e.toString(36)}function pu(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(Zn,Zn):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function Oe(t,e,n,r,i){var o=typeof t;(o==="undefined"||o==="boolean")&&(t=null);var s=!1;if(t===null)s=!0;else switch(o){case"bigint":case"string":case"number":s=!0;break;case"object":switch(t.$$typeof){case er:case Zc:s=!0;break;case Wi:return s=t._init,Oe(s(t._payload),e,n,r,i)}}if(s)return i=i(t),s=r===""?"."+Qn(t,0):r,Bi(i)?(n="",s!=null&&(n=s.replace(Hi,"$&/")+"/"),Oe(i,e,n,"",function(p){return p})):i!=null&&(ir(i)&&(i=lu(i,n+(i.key==null||t&&t.key===i.key?"":(""+i.key).replace(Hi,"$&/")+"/")+s)),e.push(i)),1;s=0;var c=r===""?".":r+":";if(Bi(t))for(var u=0;u<t.length;u++)r=t[u],o=c+Qn(r,u),s+=Oe(r,e,n,o,i);else if(u=uu(t),typeof u=="function")for(t=u.call(t),u=0;!(r=t.next()).done;)r=r.value,o=c+Qn(r,u++),s+=Oe(r,e,n,o,i);else if(o==="object"){if(typeof t.then=="function")return Oe(pu(t),e,n,r,i);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return s}function Wt(t,e,n){if(t==null)return t;var r=[],i=0;return Oe(t,r,"","",function(o){return e.call(n,o,i++)}),r}function fu(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var $i=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}},hu={map:Wt,forEach:function(t,e,n){Wt(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return Wt(t,function(){e++}),e},toArray:function(t){return Wt(t,function(e){return e})||[]},only:function(t){if(!ir(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};b.Activity=cu;b.Children=hu;b.Component=De;b.Fragment=eu;b.Profiler=nu;b.PureComponent=tr;b.StrictMode=tu;b.Suspense=su;b.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=_;b.__COMPILER_RUNTIME={__proto__:null,c:function(t){return _.H.useMemoCache(t)}};b.cache=function(t){return function(){return t.apply(null,arguments)}};b.cacheSignal=function(){return null};b.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var r=qi({},t.props),i=t.key;if(e!=null)for(o in e.key!==void 0&&(i=""+e.key),e)!zi.call(e,o)||o==="key"||o==="__self"||o==="__source"||o==="ref"&&e.ref===void 0||(r[o]=e[o]);var o=arguments.length-2;if(o===1)r.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];r.children=s}return rr(t.type,i,r)};b.createContext=function(t){return t={$$typeof:iu,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:ru,_context:t},t};b.createElement=function(t,e,n){var r,i={},o=null;if(e!=null)for(r in e.key!==void 0&&(o=""+e.key),e)zi.call(e,r)&&r!=="key"&&r!=="__self"&&r!=="__source"&&(i[r]=e[r]);var s=arguments.length-2;if(s===1)i.children=n;else if(1<s){for(var c=Array(s),u=0;u<s;u++)c[u]=arguments[u+2];i.children=c}if(t&&t.defaultProps)for(r in s=t.defaultProps,s)i[r]===void 0&&(i[r]=s[r]);return rr(t,o,i)};b.createRef=function(){return{current:null}};b.forwardRef=function(t){return{$$typeof:ou,render:t}};b.isValidElement=ir;b.lazy=function(t){return{$$typeof:Wi,_payload:{_status:-1,_result:t},_init:fu}};b.memo=function(t,e){return{$$typeof:au,type:t,compare:e===void 0?null:e}};b.startTransition=function(t){var e=_.T,n={};_.T=n;try{var r=t(),i=_.S;i!==null&&i(n,r),typeof r=="object"&&r!==null&&typeof r.then=="function"&&r.then(Zn,$i)}catch(o){$i(o)}finally{e!==null&&n.types!==null&&(e.types=n.types),_.T=e}};b.unstable_useCacheRefresh=function(){return _.H.useCacheRefresh()};b.use=function(t){return _.H.use(t)};b.useActionState=function(t,e,n){return _.H.useActionState(t,e,n)};b.useCallback=function(t,e){return _.H.useCallback(t,e)};b.useContext=function(t){return _.H.useContext(t)};b.useDebugValue=function(){};b.useDeferredValue=function(t,e){return _.H.useDeferredValue(t,e)};b.useEffect=function(t,e){return _.H.useEffect(t,e)};b.useEffectEvent=function(t){return _.H.useEffectEvent(t)};b.useId=function(){return _.H.useId()};b.useImperativeHandle=function(t,e,n){return _.H.useImperativeHandle(t,e,n)};b.useInsertionEffect=function(t,e){return _.H.useInsertionEffect(t,e)};b.useLayoutEffect=function(t,e){return _.H.useLayoutEffect(t,e)};b.useMemo=function(t,e){return _.H.useMemo(t,e)};b.useOptimistic=function(t,e){return _.H.useOptimistic(t,e)};b.useReducer=function(t,e,n){return _.H.useReducer(t,e,n)};b.useRef=function(t){return _.H.useRef(t)};b.useState=function(t){return _.H.useState(t)};b.useSyncExternalStore=function(t,e,n){return _.H.useSyncExternalStore(t,e,n)};b.useTransition=function(){return _.H.useTransition()};b.version="19.2.4"});var or=dr((ry,Xi)=>{"use strict";Xi.exports=Yi()});var Lr={};mo(Lr,{AuthHardening:()=>yt,CURRENCY_MAP:()=>sn,DEFAULT_ERROR_MESSAGES:()=>ae,DoNotDevError:()=>k,SingletonManager:()=>dn,addMonths:()=>qe,addYears:()=>fn,calculateSubscriptionEndDate:()=>Ls,captureErrorToSentry:()=>rn,commonErrorCodeMappings:()=>He,compactToISOString:()=>an,configureProviders:()=>Ts,createAsyncSingleton:()=>ws,createErrorHandler:()=>$,createMetadata:()=>Jo,createMethodProxy:()=>Rs,createSingleton:()=>We,createSingletonWithParams:()=>_s,detectErrorSource:()=>tn,ensureSpreadable:()=>qo,filterVisibleFields:()=>Ds,formatCurrency:()=>Zo,formatDate:()=>Pr,formatRelativeTime:()=>ss,generateCodeChallenge:()=>xr,generateCodeVerifier:()=>kr,generateFirestoreRuleCondition:()=>ps,generatePKCEPair:()=>hs,getCurrencyLocale:()=>Rr,getCurrencySymbol:()=>Qo,getCurrentTimestamp:()=>ns,getListCardFieldNames:()=>Ge,getProvider:()=>Ss,getRoleFromClaims:()=>bs,getVisibleFields:()=>pn,getWeekFromISOString:()=>os,handleError:()=>y,hasProvider:()=>As,hasRestrictedVisibility:()=>Ns,hasRoleAccess:()=>gt,hasTierAccess:()=>Is,isCompactDateString:()=>cn,isFieldVisible:()=>Nr,isPKCESupported:()=>ms,isoToCompactString:()=>es,lazyImport:()=>Es,mapToDoNotDevError:()=>ce,maybeTranslate:()=>fs,normalizeToISOString:()=>ts,parseDate:()=>un,parseDateToNoonUTC:()=>cs,parseISODate:()=>Us,parseServerCookie:()=>Bs,resetProviders:()=>Cs,safeValidate:()=>Go,showNotification:()=>Vo,timestampToISOString:()=>is,toDateOnly:()=>us,toISOString:()=>rs,translateArray:()=>Ko,translateArrayRange:()=>Yo,translateArrayWithIndices:()=>Xo,translateObjectArray:()=>zo,updateMetadata:()=>Ps,validateCodeChallenge:()=>vs,validateCodeVerifier:()=>gs,validateEnvVar:()=>Vs,validateMetadata:()=>Fs,validateUrl:()=>Ms,validateWithSchema:()=>Wo,withErrorHandling:()=>Fo,withGracefulDegradation:()=>ys,wrapAuthError:()=>$o,wrapCrudError:()=>Bo,wrapStorageError:()=>Ho});var O={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function Wu(t){Object.assign(O,t)}var Fe={FREE:"free",PRO:"pro",PREMIUM:"premium"};function Gu(t){Object.assign(Fe,t)}var Kt={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function qu(t){Object.assign(Kt,t)}var zt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function ju(t){Object.assign(zt,t)}import*as l from"valibot";var ve={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function zu(t){Object.assign(ve,t)}var pt={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function Yu(t){Object.assign(pt,t)}var Xu={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function Ju(t){return{tier:"free",status:"active",subscriptionId:null,customerId:t,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var fr={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},Qu={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as a from"valibot";var hr=a.object({userId:a.string(),productId:a.optional(a.string()),priceId:a.string(),successUrl:a.pipe(a.string(),a.url()),cancelUrl:a.pipe(a.string(),a.url()),customerEmail:a.optional(a.pipe(a.string(),a.email())),userEmail:a.optional(a.pipe(a.string(),a.email())),metadata:a.optional(a.record(a.string(),a.string())),allowPromotionCodes:a.optional(a.boolean()),mode:a.optional(a.picklist([pt.PAYMENT,pt.SUBSCRIPTION]))}),mr=a.object({sessionId:a.string(),sessionUrl:a.nullable(a.pipe(a.string(),a.url()))}),gr=a.object({userId:a.string(),tier:a.string(),status:a.picklist(Object.values(ve)),subscriptionId:a.nullable(a.string()),customerId:a.string(),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp())}),vr=a.object({tier:a.string(),subscriptionId:a.nullable(a.string()),customerId:a.string(),status:a.picklist(Object.values(ve)),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp()),isDefault:a.optional(a.boolean())}),yr=a.object({id:a.string(),type:a.string(),data:a.object({object:a.any()}),created:a.pipe(a.string(),a.isoTimestamp())}),Er=a.looseObject({userId:a.optional(a.string()),firebaseUid:a.optional(a.string()),productType:a.optional(a.string())});function tl(t){return a.safeParse(hr,t)}function nl(t){return a.safeParse(mr,t)}function rl(t){return a.safeParse(gr,t)}function il(t){return a.safeParse(vr,t)}function ol(t){return a.safeParse(yr,t)}function sl(t){return a.safeParse(Er,t)}var vo=a.object({type:a.literal("StripePayment"),name:a.pipe(a.string(),a.minLength(1,"Product name is required")),description:a.optional(a.string()),price:a.string(),currency:a.optional(a.pipe(a.string(),a.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a.pipe(a.string(),a.minLength(1,"Stripe price ID is required")),tier:a.pipe(a.string(),a.minLength(1,"Tier is required")),duration:a.pipe(a.string(),a.minLength(1,"Duration is required")),allowPromotionCodes:a.optional(a.boolean()),metadata:a.optional(a.record(a.string(),a.string()))}),yo=a.object({type:a.literal("StripeSubscription"),name:a.pipe(a.string(),a.minLength(1,"Product name is required")),description:a.optional(a.string()),price:a.string(),currency:a.optional(a.pipe(a.string(),a.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a.pipe(a.string(),a.minLength(1,"Stripe price ID is required")),tier:a.pipe(a.string(),a.minLength(1,"Tier is required")),duration:a.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:a.optional(a.boolean()),metadata:a.optional(a.record(a.string(),a.string()))}),Eo=a.variant("type",[vo,yo]),al=a.record(a.string(),Eo),bo=a.record(a.string(),a.object({name:a.string(),price:a.string(),currency:a.string(),description:a.optional(a.string()),features:a.optional(a.array(a.string())),priceId:a.string(),allowPromotionCodes:a.optional(a.boolean())})),Io=a.record(a.string(),a.object({type:a.picklist(["StripePayment","StripeSubscription"]),name:a.string(),price:a.number(),currency:a.string(),priceId:a.string(),tier:a.string(),duration:a.string(),description:a.optional(a.string()),metadata:a.optional(a.record(a.string(),a.string())),allowPromotionCodes:a.optional(a.boolean())}));function cl(t){return a.parse(bo,t)}function ul(t){return a.parse(Io,t)}function ll(){let t={createCheckoutSessionRequest:a.safeParse(hr,{}),createCheckoutSessionResponse:a.safeParse(mr,{}),subscriptionData:a.safeParse(gr,{}),subscriptionClaims:a.safeParse(vr,{}),webhookEvent:a.safeParse(yr,{}),checkoutSessionMetadata:a.safeParse(Er,{})};return{success:Object.values(t).every(e=>e.success),results:t}}var br=l.object({id:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),emailVerified:l.optional(l.boolean()),lastLoginAt:l.optional(l.string()),providerData:l.optional(l.array(l.object({providerId:l.string(),uid:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),phoneNumber:l.optional(l.nullable(l.string()))}))),role:l.optional(l.picklist(Object.values(O))),customClaims:l.optional(l.record(l.string(),l.any()))}),Yt=l.object({userId:l.string(),tier:l.picklist(Object.values(Fe)),status:l.picklist(Object.values(ve)),isActive:l.optional(l.boolean()),features:l.optional(l.array(l.string())),subscriptionId:l.nullable(l.string()),customerId:l.string(),subscriptionEnd:l.nullable(l.pipe(l.string(),l.isoTimestamp())),cancelAtPeriodEnd:l.boolean(),updatedAt:l.pipe(l.string(),l.isoTimestamp())}),Ir=l.object({role:l.optional(l.picklist(Object.values(O))),subscription:l.optional(Yt),features:l.optional(l.array(l.picklist(Object.values(Kt)))),permissions:l.optional(l.array(l.picklist(Object.values(zt)))),githubAccess:l.optional(l.object({username:l.optional(l.string()),teamAccess:l.optional(l.array(l.string())),repoAccess:l.optional(l.array(l.string()))}))});function yl(t){return l.safeParse(br,t)}function El(t){return l.safeParse(Yt,t)}function bl(t){return l.safeParse(Ir,t)}function Il(){let t={authUser:l.safeParse(br,{}),userSubscription:l.safeParse(Yt,{}),customClaims:l.safeParse(Ir,{}),getUserAuthStatus:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1))}),{}),getCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.optional(l.array(l.string()))}),{}),setCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claims:l.record(l.string(),l.any()),merge:l.optional(l.boolean(),!1)}),{}),removeCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.pipe(l.array(l.string()),l.minLength(1))}),{})};return{success:Object.values(t).every(e=>e.success),results:t}}var Sl={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Al(t){return{userId:t,role:"user",preferences:{},metadata:{}}}var S={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},oe={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},P={CLIENT:"client",SERVER:"server",BUILD:"build"},N={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},Ve={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},xl={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},Ol={USER:"user",GLOBAL:"global",SESSION:"session"},Dl={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},Nl={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},Ll={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var Ml={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},Fl={TRUE:!0,FALSE:!1,ADMIN:"admin",CREATE_ONLY:"create-only"},Xt={create:"admin",read:"guest",update:"admin",delete:"admin"},se={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},Vl={ASC:"asc",DESC:"desc"},Bl={LIST:"list",LIST_CARD:"listCard"},Hl=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var Gl={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},ql={EQ:se.EQ,NEQ:se.NEQ,LT:se.LT,LTE:se.LTE,GT:se.GT,GTE:se.GTE};import*as h from"valibot";var ft=/^[0-9a-zA-Z]+$/,Jl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),data:h.record(h.string(),h.unknown()),idempotencyKey:h.optional(h.string())}),Ql=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),Zl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required")),data:h.record(h.string(),h.unknown()),merge:h.optional(h.boolean(),!1)}),ed=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),td=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),limit:h.optional(h.pipe(h.number(),h.minValue(1),h.maxValue(1e3)),50),offset:h.optional(h.pipe(h.number(),h.minValue(0)),0),orderBy:h.optional(h.string()),orderDirection:h.optional(h.picklist(["asc","desc"]),"desc"),where:h.optional(h.array(h.object({field:h.string(),operator:h.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:h.unknown()})))});var Be={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},ld={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},ht={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Jt={[Be.PERMISSION_DENIED]:{type:ht.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[Be.NOT_FOUND]:{type:ht.NOT_FOUND,message:"The requested resource was not found"},[Be.ALREADY_EXISTS]:{type:ht.ALREADY_EXISTS,message:"The resource already exists"},[Be.INVALID_ARGUMENT]:{type:ht.VALIDATION_ERROR,message:"Invalid argument provided"}},Tr=class extends Error{type;originalError;constructor(e,n,r){super(n),this.name="EntityHookError",this.type=e,this.originalError=r}},dd={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"},k=class t extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(e,n=Be.INTERNAL,r){super(e),Object.setPrototypeOf(this,t.prototype),this.code=n,this.details=r?.details,this.source=r?.source,this.originalError=r?.originalError,this.context=r?.context,this.displayable=r?.displayable??!0,this.userMessageProvided=r?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var md={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var vd={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var Ed={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var Id={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var Sd={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var Qt={mobile:0,tablet:768,laptop:1024,desktop:1440},To={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function So(t){return t>=Qt.desktop?"desktop":t>=Qt.laptop?"laptop":t>=Qt.tablet?"tablet":"mobile"}function Ud(t,e){let n=To[e];return t>=n.min&&t<=n.max}function Md(t,e){let n=So(t);return{current:n,width:t,height:e,isMobile:n==="mobile",isTablet:n==="tablet",isLaptop:n==="laptop",isDesktop:n==="desktop",isMobileOrTablet:n==="mobile"||n==="tablet",isLaptopOrDesktop:n==="laptop"||n==="desktop"}}var Vd="landing",Bd={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var Sr=["pull","push","admin","maintain","triage"];import"valibot";import*as f from"valibot";var Zt=f.object({owner:f.pipe(f.string(),f.minLength(1,"Repository owner is required")),repo:f.pipe(f.string(),f.minLength(1,"Repository name is required"))}),Ao=f.picklist([...Sr]),Xd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Zt,permission:f.optional(Ao,"push"),customClaims:f.optional(f.record(f.string(),f.any()))}),Jd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Zt}),Qd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Zt}),Zd=f.object({provider:f.string(),purpose:f.picklist(["authentication","api-access"]),code:f.pipe(f.string(),f.minLength(1,"Authorization code is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required")),codeVerifier:f.optional(f.string()),state:f.optional(f.string()),instance:f.optional(f.pipe(f.string(),f.url()))}),ep=f.object({provider:f.string(),refreshToken:f.pipe(f.string(),f.minLength(1,"Refresh token is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required"))}),tp=f.object({provider:f.string()}),np=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required"))});var cp={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as g from"valibot";var Ar=g.object({name:g.string(),color:g.string(),icon:g.string(),customParameters:g.optional(g.record(g.string(),g.string())),button:g.object({backgroundColor:g.string(),textColor:g.string(),borderColor:g.string(),hoverBackgroundColor:g.string(),focusOutlineColor:g.string(),fontWeight:g.optional(g.string(),"500"),textKey:g.optional(g.string())})}),Co=g.object({...Ar.entries,type:g.picklist(["auth","both"]),scopes:g.optional(g.array(g.string())),firebaseProviderId:g.optional(g.string())}),mt=g.union([g.literal(""),g.pipe(g.string(),g.url())]),_o=g.object({authUrl:mt,tokenUrl:mt,profileUrl:mt,revokeUrl:g.optional(mt)}),wo=g.object({authentication:g.optional(g.array(g.string())),"api-access":g.array(g.string())}),Ro=g.optional(g.object({pkce:g.optional(g.boolean(),!1),codeChallengeMethod:g.optional(g.picklist(["S256","plain"]),"S256")})),Po=g.object({...Ar.entries,type:g.picklist(["oauth","both"]),scopes:wo,endpoints:_o,capabilities:Ro}),ye={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},en={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},ko=g.record(g.string(),Co),xo=g.record(g.string(),Po);function lp(){return g.safeParse(ko,ye)}function dp(){return g.safeParse(xo,en)}function Oo(t){return t in ye}function Do(t){return t in en}var Cr={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Ip={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Tp={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:Cr.ANALYTICS},marketing:{requiresConsent:Cr.MARKETING}};function tn(t){return t instanceof Error&&"source"in t&&typeof t.source=="string"?t.source:typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&t.code.startsWith("auth/")?"auth":typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&t.code.startsWith("oauth/")?"oauth":typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(t.code)?"firebase":typeof t=="object"&&t!==null&&"issues"in t&&Array.isArray(t.issues)&&"name"in t&&t.name==="ValiError"?"validation":t instanceof Error&&t.name==="EntityHookError"?"entity":typeof t=="object"&&t!==null&&("response"in t||"status"in t||"statusText"in t)?"api":typeof t=="object"&&t!==null&&"componentStack"in t?"ui":"unknown"}import*as wr from"valibot";function $(t){return(e,n)=>{if(e instanceof k)return e;if(typeof e!="object"||e===null){let c=typeof e=="string"?e:t.defaultErrorMessage;return new k(n||c,t.defaultErrorCode,{details:{originalError:e},source:t.errorSource})}let r;t.extractErrorCode?r=t.extractErrorCode(e):"code"in e&&typeof e.code=="string"&&(r=e.code);let i=t.defaultErrorCode;r&&t.errorCodeMapping&&r in t.errorCodeMapping&&(i=t.errorCodeMapping[r]);let o;t.extractErrorMessage?o=t.extractErrorMessage(e):("message"in e&&typeof e.message=="string"||e instanceof Error)&&(o=e.message),r&&t.friendlyMessageMapping&&r in t.friendlyMessageMapping&&(o=t.friendlyMessageMapping[r]),o||(o=t.defaultErrorMessage);let s;return t.processMetadata?s=t.processMetadata(e):(s={originalError:e},r&&(s.originalCode=r)),"originalError"in s||(s.originalError=e),new k(n||o,i,{details:s,source:t.errorSource})}}var He={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"};var ae={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},No={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},nn={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},Z={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...He},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...He},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(No).map(([t,e])=>[t,e])),friendlyMessageMapping:{},extractErrorCode:t=>{if(typeof t!="object"||t===null)return;let e;return"response"in t&&t.response&&"status"in t.response?e=t.response.status:"status"in t&&typeof t.status=="number"&&(e=t.status),e?.toString()},processMetadata:t=>{let e={originalError:t};return typeof t!="object"||t===null||("response"in t&&t.response?("status"in t.response&&(e.statusCode=t.response.status),"data"in t.response&&(e.responseData=t.response.data)):"status"in t&&(e.statusCode=t.status)),e}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:He,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ae.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:t=>{let e={originalError:t};return typeof t=="object"&&t!==null&&"componentStack"in t&&(e.componentStack=t.componentStack),e}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:ae["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ae.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:t=>{if(t instanceof Error)return t.name}}},Lo=t=>t instanceof wr.ValiError?new k(ae["validation-failed"],"validation-failed",{details:{validationErrors:t.issues.map(e=>({path:e.path.join("."),message:e.message})),originalError:t},source:"validation"}):$(Z.validation)(t),Uo=t=>{if(t instanceof Error&&"type"in t&&typeof t.type=="string"&&t.type in nn){let e=t,n=nn[e.type]||"unknown";return new k(e.message||ae[n],n,{details:{originalError:t},source:"entity"})}if(typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&Jt[t.code]){let e=t,n=Jt[e.code];if(n){let r=nn[n.type]||"unknown";return new k(n.message||ae[r],r,{details:{originalCode:e.code,originalError:t},source:"entity"})}}return $(Z.entity)(t)},_r={auth:$(Z.auth),oauth:$(Z.oauth),api:$(Z.api),firebase:$(Z.firebase),ui:$(Z.ui),validation:Lo,entity:Uo,unknown:$(Z.unknown)};function ce(t,e,n){return t instanceof k?t:(_r[e]||_r.unknown)(t,n)}function rn(t,e,n={}){let r=globalThis.Sentry;r&&r.withScope(i=>{i.setTag("errorSource",e),i.setTag("errorCode",t.code),t.details&&Object.entries(t.details).forEach(([o,s])=>{if(typeof s!="function"&&o!=="originalError")try{i.setExtra(o,s)}catch{i.setExtra(o,`[${typeof s}]`)}}),Object.entries(n).forEach(([o,s])=>{if(typeof s!="function")try{i.setExtra(`context.${o}`,s)}catch{i.setExtra(`context.${o}`,`[${typeof s}]`)}}),(t.details?.userId||n.userId)&&i.setUser({id:t.details?.userId||n.userId,email:t.details?.userEmail||n.userEmail}),r.captureException(t)})}function Mo(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!0}function y(t,e){let n=typeof e=="string"?{userMessage:e}:e||{},{userMessage:r,context:i={},log:o=!0,reportToSentry:s=!0,showNotification:c=!1,severity:u="error"}=n,p=tn(t),m=t instanceof k?t:ce(t,p,r);if(r&&!m.userMessageProvided&&(m.message.includes("Error")||m.message.includes("Failed")||m.message.length<10?m=new k(r,m.code,{details:{...m.details,originalMessage:m.message},source:p,userMessageProvided:!0}):m=new k(m.message,m.code,{details:{...m.details,userMessage:r},source:p,userMessageProvided:!0})),o){let T=Mo()||typeof window<"u"&&window.__DNDEV_DEBUG,x={code:m.code,message:m.message,source:p};switch(u){case"warning":break;case"info":break;case"success":break;default:}}return s&&rn(m,p,i),m}function Fo(t,e){return async(...n)=>{try{return await t(...n)}catch(r){throw y(r,e)}}}function Vo(t,e="info",n){let r=Date.now().toString();return r}function Bo(t,e,n,r,i){let o=`${e}.${n}(${r}${i?`, ${i}`:""})`;return ce(t,"api",`${o}: ${on(t)}`)}function Ho(t,e,n,r){let i=`${e}.${n}(${r})`;return ce(t,"api",`${i}: ${on(t)}`)}function $o(t,e,n,r){let i=r?` ${JSON.stringify(r)}`:"",o=`${e}.${n}(${i})`;return ce(t,"auth",`${o}: ${on(t)}`)}function on(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t)}import*as $e from"valibot";function Wo(t,e,n){try{return $e.parse(t,e)}catch(r){throw r instanceof $e.ValiError?new k(`Validation failed in ${n}: ${r.message}`,"validation-failed",{details:{issues:r.issues,input:e},source:"validation"}):new k(`Unexpected validation error in ${n}: ${jo(r)}`,"validation-failed",{originalError:r instanceof Error?r:new Error(String(r)),source:"validation"})}}function Go(t,e){try{return $e.parse(t,e)}catch{return null}}function qo(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{value:t}}function jo(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t)}function Ko(t,e,n,r={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=r;return Array.from({length:n},(c,u)=>{let p=`${e}.${u}`;return t(p)}).filter((c,u)=>{let p=`${e}.${u}`;return!(c===p||o&&c.trim()===""||c.length<i||s&&!s(c,u))})}function zo(t,e,n,r){return Array.from({length:n},(i,o)=>{let s=`${e}.${o}.${String(r[0])}`;if(t(s)===s)return null;let u={};for(let p of r){let m=`${e}.${o}.${String(p)}`;u[p]=t(m)}return u}).filter(i=>i!==null)}function Yo(t,e,n,r,i={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:c}=i;return Array.from({length:r-n},(u,p)=>{let m=n+p,T=`${e}.${m}`;return t(T)}).filter((u,p)=>{let m=n+p,T=`${e}.${m}`;return!(u===T||s&&u.trim()===""||u.length<o||c&&!c(u,m))})}function Xo(t,e,n,r={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=r;return Array.from({length:n},(c,u)=>{let p=`${e}.${u}`;return{item:t(p),originalIndex:u}}).filter(({item:c,originalIndex:u})=>{let p=`${e}.${u}`;return!(c===p||o&&c.trim()===""||c.length<i||s&&!s(c,u))})}function Jo(t){let e=new Date().toISOString();return{_createdAt:e,_updatedAt:e,_createdBy:t,_updatedBy:t}}var sn={AED:{locale:"ar-AE",symbol:"\u062F.\u0625"},ARS:{locale:"es-AR",symbol:"$"},AUD:{locale:"en-AU",symbol:"$"},BDT:{locale:"bn-BD",symbol:"\u09F3"},BGN:{locale:"bg-BG",symbol:"\u043B\u0432"},BHD:{locale:"ar-BH",symbol:"\u062F.\u0628"},BRL:{locale:"pt-BR",symbol:"R$"},CAD:{locale:"en-CA",symbol:"$"},CHF:{locale:"fr-CH",symbol:"CHF"},CLP:{locale:"es-CL",symbol:"$"},CNY:{locale:"zh-CN",symbol:"\xA5"},COP:{locale:"es-CO",symbol:"$"},CZK:{locale:"cs-CZ",symbol:"K\u010D"},DKK:{locale:"da-DK",symbol:"kr"},EGP:{locale:"ar-EG",symbol:"E\xA3"},EUR:{locale:"fr-FR",symbol:"\u20AC"},GBP:{locale:"en-GB",symbol:"\xA3"},HKD:{locale:"zh-HK",symbol:"$"},HUF:{locale:"hu-HU",symbol:"Ft"},IDR:{locale:"id-ID",symbol:"Rp"},ILS:{locale:"he-IL",symbol:"\u20AA"},INR:{locale:"en-IN",symbol:"\u20B9"},JOD:{locale:"ar-JO",symbol:"\u062F.\u0623"},JPY:{locale:"ja-JP",symbol:"\xA5"},KES:{locale:"sw-KE",symbol:"KSh"},KRW:{locale:"ko-KR",symbol:"\u20A9"},KWD:{locale:"ar-KW",symbol:"\u062F.\u0643"},LKR:{locale:"si-LK",symbol:"Rs"},MXN:{locale:"es-MX",symbol:"$"},MYR:{locale:"ms-MY",symbol:"RM"},NGN:{locale:"en-NG",symbol:"\u20A6"},NOK:{locale:"nb-NO",symbol:"kr"},NZD:{locale:"en-NZ",symbol:"$"},OMR:{locale:"ar-OM",symbol:"\u0631.\u0639."},PEN:{locale:"es-PE",symbol:"S/."},PHP:{locale:"en-PH",symbol:"\u20B1"},PKR:{locale:"ur-PK",symbol:"\u20A8"},PLN:{locale:"pl-PL",symbol:"z\u0142"},QAR:{locale:"ar-QA",symbol:"\u0631.\u0642"},RON:{locale:"ro-RO",symbol:"lei"},RUB:{locale:"ru-RU",symbol:"\u20BD"},SAR:{locale:"ar-SA",symbol:"\u0631.\u0633"},SEK:{locale:"sv-SE",symbol:"kr"},SGD:{locale:"en-SG",symbol:"$"},THB:{locale:"th-TH",symbol:"\u0E3F"},TRY:{locale:"tr-TR",symbol:"\u20BA"},TWD:{locale:"zh-TW",symbol:"$"},UAH:{locale:"uk-UA",symbol:"\u20B4"},USD:{locale:"en-US",symbol:"$"},UYU:{locale:"es-UY",symbol:"$"},VND:{locale:"vi-VN",symbol:"\u20AB"},ZAR:{locale:"en-ZA",symbol:"R"}};function Rr(t){return sn[t]?.locale??"en-US"}function Qo(t){return!t||typeof t!="string"?t??"":sn[t]?.symbol??t}function Zo(t,e,n={}){if(t==null||isNaN(t))return"";let r=Rr(e);return new Intl.NumberFormat(r,{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:0,currencyDisplay:"symbol",...n}).format(t)}function an(t){let e=t.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!e||e.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${t}`);let n=e[1],r=e[2],i=e[3],o=e[4],s=e[5],c=new Date(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(o,10),parseInt(s,10));if(isNaN(c.getTime()))throw new Error(`Invalid date values in compact format: ${t}`);return c.toISOString()}function es(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let n=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),s=String(e.getUTCMinutes()).padStart(2,"0");return`${n}${r}${i}:${o}${s}`}function cn(t){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(t)}function ts(t){if(!t)return new Date().toISOString();if(t instanceof Date){if(isNaN(t.getTime()))throw new Error("Invalid Date object");return t.toISOString()}if(typeof t=="string"){if(cn(t))return an(t);let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid date string: ${t}`);return e.toISOString()}if(typeof t=="number"){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid timestamp: ${t}`);return e.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t){let e=t;if(typeof e.toDate=="function")return e.toDate().toISOString()}throw new Error(`Unsupported date type: ${typeof t}`)}function ns(){return new Date().toISOString()}function rs(t){return t.toISOString()}function is(t){return new Date(t).toISOString()}function os(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let n=new Date(e.getFullYear(),0,1),r=Math.floor((e.getTime()-n.getTime())/(1440*60*1e3));return`Week ${Math.ceil((r+n.getDay()+1)/7)}, ${e.getFullYear()}`}var U={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function ss(t,e="en",n={}){if(!t)return"";let{style:r="long",numeric:i="auto",fallbackThreshold:o=U.WEEK}=n,s;if(t instanceof Date)s=t;else if(typeof t=="string")s=new Date(t);else if(typeof t=="number")s=new Date(t);else if(typeof t=="object"&&"toDate"in t)s=t.toDate();else return"";if(isNaN(s.getTime()))return"";let c=new Date,u=s.getTime()-c.getTime(),p=Math.round(u/1e3),m=Math.abs(p);if(m>o)return Pr(s.toISOString(),e);let T=new Intl.RelativeTimeFormat(e,{style:r,numeric:i});return m<U.MINUTE?T.format(p,"second"):m<U.HOUR?T.format(Math.round(p/U.MINUTE),"minute"):m<U.DAY?T.format(Math.round(p/U.HOUR),"hour"):m<U.WEEK?T.format(Math.round(p/U.DAY),"day"):m<U.MONTH?T.format(Math.round(p/U.WEEK),"week"):m<U.YEAR?T.format(Math.round(p/U.MONTH),"month"):T.format(Math.round(p/U.YEAR),"year")}function as(t){switch(t){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function Pr(t,e="en",n="long"){if(!t)return"";let r;if(t instanceof Date)r=t;else if(typeof t=="string")r=new Date(t);else if(typeof t=="number")r=new Date(t);else if(typeof t=="object"&&"toDate"in t)r=t.toDate();else return"";if(isNaN(r.getTime()))return"";let i=typeof n=="string"?as(n):n;return new Intl.DateTimeFormat(e,i).format(r)}function un(t){if(t!=null){if(t instanceof Date)return isNaN(t.getTime())?void 0:t.toISOString();if(typeof t=="string"){let e=t.trim();if(!e)return;if(cn(e))try{return an(e)}catch{return}let n=new Date(e);return isNaN(n.getTime())?void 0:n.toISOString()}if(typeof t=="number"){if(!Number.isFinite(t))return;let e=new Date(t);return isNaN(e.getTime())?void 0:e.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t){let e=t;if(typeof e.toDate=="function")try{let n=e.toDate();return isNaN(n.getTime())?void 0:n.toISOString()}catch{return}}if(typeof t=="object"&&t!==null&&"seconds"in t&&typeof t.seconds=="number"){let e=t,n=e.seconds*1e3+(e.nanoseconds||0)/1e6,r=new Date(n);return isNaN(r.getTime())?void 0:r.toISOString()}}}function cs(t){let e=un(t);if(!e)return;let n=new Date(e);return n.setUTCHours(12,0,0,0),n.toISOString()}function us(t){let e=un(t);return e&&e.split("T")[0]||""}function ls(t){return typeof t=="string"?`'${t.replace(/'/g,"\\'")}'`:typeof t=="boolean"?t?"true":"false":String(t)}function ds(t){let e=`resource.data.${t.field}`,n=ls(t.value);return`${e} ${t.op} ${n}`}function ps(t){let e=[];if(t.publicCondition&&t.publicCondition.length>0){let n=t.publicCondition.map(ds).join(" && ");e.push(`(${n})`)}for(let n of t.ownerFields)e.push(`request.auth.uid == resource.data.${n}`);return e.length===0?"false":e.join(" || ")}function fs(t,e){return e?!e.includes(".")&&!e.includes(":")?e:t(e):""}function kr(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Or(t)}async function xr(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Or(new Uint8Array(r))}async function hs(){let t=kr(),e=await xr(t);return{codeVerifier:t,codeChallenge:e}}function Or(t){return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ms(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function gs(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}function vs(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}async function ys(t,e,n){try{return await t()}catch{return e(),!1}}var ln=new Map;function Es(t,e){if(ln.has(e))return ln.get(e);let n=t();return ln.set(e,n),n}var Dr={[O.GUEST]:0,[O.USER]:1,[O.ADMIN]:2,[O.SUPER]:3};function gt(t,e){if(!t)return!1;let n=Dr[t]??-1,r=Dr[e]??1/0;return n>=r}function bs(t){return t?t.role===O.SUPER||t.isSuper===!0?O.SUPER:t.role===O.ADMIN||t.isAdmin===!0?O.ADMIN:t.role===O.USER?O.USER:t.role||O.USER:O.USER}function Is(t,e,n){if(!t)return!1;let r=n??fr,i=r[t]?.level??-1,o=r[e]?.level??1/0;return i>=o}var Ee=null;function Ts(t){Ee=t}function Ss(t){if(!Ee)throw new Error(`[dndev] Provider "${t}" not available. Call configureProviders() at app startup.`);let e=Ee[t];if(!e)throw new Error(`[dndev] Provider "${t}" not configured. Pass it to configureProviders().`);return e}function As(t){return!!Ee?.[t]}function Cs(){Ee=null}function We(t,...e){let n=null,r=!1;return function(){if(n!==null)return n;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof t=="function"&&t.prototype?n=new t(...e):n=t(),n}finally{r=!1}}}function _s(t){let e=null,n=!1;return function(...i){if(e!==null)return e;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof t=="function"&&t.prototype?e=new t(...i):e=t(...i),e}finally{n=!1}}}function ws(t){let e=null,n=!1,r=null;return async function(){if(e!==null)return e;if(n&&r)return r;if(n)throw new Error("Circular dependency detected in async singleton initialization");n=!0;try{return r=t(),e=await r,e}finally{n=!1,r=null}}}function Rs(t,e){return new Proxy({},{get(n,r){if(e.includes(r)){let o=t(),s=o[r];return typeof s=="function"?s.bind(o):s}return t()[r]}})}var dn=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(e,n,r={}){if(this.instances.has(e))return this.instances.get(e);if(this.initialized.has(e))return this.instances.get(e);if(this.initializing.has(e))throw new Error(`Circular dependency detected for singleton: ${e}`);if(r.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u",r.fallbackFactory){let i=r.fallbackFactory();return this.instances.set(e,i),this.initialized.add(e),i}throw new Error(`Singleton ${e} requires client-side environment`)}this.initializing.add(e);try{let i=await n();return this.instances.set(e,i),this.initialized.add(e),i}catch(i){if(typeof process<"u",r.cacheFailures&&this.initialized.add(e),r.fallbackFactory){let o=r.fallbackFactory();return this.instances.set(e,o),this.initialized.add(e),o}throw i}finally{this.initializing.delete(e)}}static isInitialized(e){return this.initialized.has(e)}static clear(e){this.instances.delete(e),this.initialized.delete(e),this.initializing.delete(e)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};function Ps(t){return{_updatedAt:new Date().toISOString(),_updatedBy:t}}import"valibot";import"valibot";function ks(t){return typeof t=="object"&&t!==null&&"visibility"in t&&typeof t.visibility=="string"}function xs(t){if(ks(t))return t.visibility}function Nr(t,e){let n=t??"guest";return n==="hidden"?!1:n==="technical"?gt(e,"admin"):n==="owner"?!1:gt(e,n)}function Os(t,e,n){for(let r of n.ownerFields)if(t[r]===e)return!0;return!1}function pn(t,e,n){let r=t;if(!r||typeof r!="object"||!r.entries)return[];let i=r.entries,o=[],{documentData:s,uid:c,ownership:u}=n??{},p=u&&c!=null&&s&&Os(s,c,u);for(let[m,T]of Object.entries(i)){let x=xs(T);if(x==="owner"){p&&o.push(m);continue}Nr(x,e)&&o.push(m)}return o}function Ds(t,e,n,r){if(!t)return{};let i=r?.uid!=null&&r?.ownership!=null?{documentData:r.documentData??t,uid:r.uid,ownership:r.ownership}:void 0,o=pn(e,n,i),s={};for(let c of o)Object.prototype.hasOwnProperty.call(t,c)&&(s[c]=t[c]);return s}function Ge(t){let e=t.listCardFields;if(e){if(Array.isArray(e))return e;let n=e,r=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(r)]}return t.listFields&&t.listFields.length>0?t.listFields:t.fields?Object.keys(t.fields):[]}import"valibot";function vt(t){if(!(!t||typeof t!="object")){if(t.entries&&typeof t.entries=="object")return t.entries;if(Array.isArray(t.pipe))for(let e of t.pipe){let n=vt(e);if(n)return n}if(t.wrapped)return vt(t.wrapped);if(Array.isArray(t.options))for(let e of t.options){let n=vt(e);if(n)return n}}}function Ns(t){let e=vt(t);if(!e)return!1;for(let n of Object.values(e)){let r=n?.visibility;if(r!==void 0&&r!=="guest")return!0}return!1}var yt=class{store=new Map;maxAttempts;lockoutMs;sessionTimeoutMs;constructor(e={}){this.maxAttempts=e.maxAttempts??5,this.lockoutMs=e.lockoutMs??900*1e3,this.sessionTimeoutMs=e.sessionTimeoutMs??480*60*1e3}checkLockout(e){let n=this.store.get(e);if(n?.lockedUntil){if(Date.now()<n.lockedUntil){let r=Math.ceil((n.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${r} minute${r===1?"":"s"}.`)}this.store.delete(e)}}recordFailure(e){let n=Date.now();!this.store.has(e)&&this.store.size>=1e4&&this._evictExpired(n);let r=this.store.get(e)??{attempts:0,lastAttempt:0,lockedUntil:null};return r.attempts+=1,r.lastAttempt=n,r.attempts>=this.maxAttempts&&(r.lockedUntil=n+this.lockoutMs),this.store.set(e,r),{attempts:r.attempts,locked:r.lockedUntil!==null&&Date.now()<r.lockedUntil,lockedUntil:r.lockedUntil}}_evictExpired(e){for(let[n,r]of this.store)r.lockedUntil!==null&&e>r.lockedUntil?this.store.delete(n):r.lockedUntil===null&&e-r.lastAttempt>this.lockoutMs&&this.store.delete(n)}recordSuccess(e){this.store.delete(e)}isSessionExpired(e){return Date.now()-e>this.sessionTimeoutMs}getEntry(e){return this.store.get(e)}};function qe(t,e){let n=new Date(t),r=n.getDate();return n.setMonth(n.getMonth()+e),n.getDate()!==r&&n.setDate(0),n}function fn(t,e){let n=new Date(t),r=n.getDate();return n.setFullYear(n.getFullYear()+e),n.getDate()!==r&&n.setDate(0),n}function Ls(t,e=new Date){if(t==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return t==="1month"?n=qe(e,1):t==="3months"?n=qe(e,3):t==="6months"?n=qe(e,6):t==="1year"?n=fn(e,1):t==="2years"?n=fn(e,2):n=qe(e,1),n.toISOString()}function Us(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);return e}function Ms(t,e="URL"){try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol))throw new Error(`Invalid protocol: ${n.protocol}`);return t}catch(n){throw new Error(`Invalid ${e}: ${t}. ${n instanceof Error?n.message:"Invalid URL format"}`)}}function Fs(t){let e={};for(let[n,r]of Object.entries(t)){if(typeof r!="string")throw new Error(`Metadata value for key '${n}' must be a string, got ${typeof r}`);let i=r.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(i.length>1e3)throw new Error(`Metadata value for key '${n}' is too long (max 1000 characters)`);if(n.length>100)throw new Error(`Metadata key '${n}' is too long (max 100 characters)`);e[n]=i}return e}function Vs(t,e=!0){let n=process.env[t];if(e&&!n)throw new Error(`Required environment variable '${t}' is not set`);return n||""}function Bs(t,e){if(!t)return null;let n=`${encodeURIComponent(e)}=`,r=t.split(";");for(let i=0;i<r.length;i++){let o=r[i];if(o){for(;o.charAt(0)===" ";)o=o.substring(1,o.length);if(o.indexOf(n)===0)return decodeURIComponent(o.substring(n.length,o.length))}}return null}import*as z from"valibot";var Hs={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};var Ur=function(t){let e=[],n=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023),e[n++]=i>>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},$s=function(t){let e=[],n=0,r=0;for(;n<t.length;){let i=t[n++];if(i<128)e[r++]=String.fromCharCode(i);else if(i>191&&i<224){let o=t[n++];e[r++]=String.fromCharCode((i&31)<<6|o&63)}else if(i>239&&i<365){let o=t[n++],s=t[n++],c=t[n++],u=((i&7)<<18|(o&63)<<12|(s&63)<<6|c&63)-65536;e[r++]=String.fromCharCode(55296+(u>>10)),e[r++]=String.fromCharCode(56320+(u&1023))}else{let o=t[n++],s=t[n++];e[r++]=String.fromCharCode((i&15)<<12|(o&63)<<6|s&63)}}return e.join("")},Mr={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_();let n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let i=0;i<t.length;i+=3){let o=t[i],s=i+1<t.length,c=s?t[i+1]:0,u=i+2<t.length,p=u?t[i+2]:0,m=o>>2,T=(o&3)<<4|c>>4,x=(c&15)<<2|p>>6,H=p&63;u||(H=64,s||(x=64)),r.push(n[m],n[T],n[x],n[H])}return r.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(Ur(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):$s(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();let n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let i=0;i<t.length;){let o=n[t.charAt(i++)],c=i<t.length?n[t.charAt(i)]:0;++i;let p=i<t.length?n[t.charAt(i)]:64;++i;let T=i<t.length?n[t.charAt(i)]:64;if(++i,o==null||c==null||p==null||T==null)throw new mn;let x=o<<2|c>>4;if(r.push(x),p!==64){let H=c<<4&240|p>>2;if(r.push(H),T!==64){let ie=p<<6&192|T;r.push(ie)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}},mn=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},Ws=function(t){let e=Ur(t);return Mr.encodeByteArray(e,!0)},vn=function(t){return Ws(t).replace(/\./g,"")},yn=function(t){try{return Mr.decodeString(t,!0)}catch{}return null};function En(t){try{return(t.startsWith("http://")||t.startsWith("https://")?new URL(t).hostname:t).endsWith(".cloudworkstations.dev")}catch{return!1}}function V(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function Fr(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(V())}function Vr(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function Br(){let t=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof t=="object"&&t.id!==void 0}function Hr(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function $r(){try{return typeof indexedDB=="object"}catch{return!1}}function Wr(){return new Promise((t,e)=>{try{let n=!0,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=()=>{e(i.error?.message||"")}}catch(n){e(n)}})}var Gs="FirebaseError",W=class t extends Error{constructor(e,n,r){super(n),this.code=e,this.customData=r,this.name=Gs,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,X.prototype.create)}},X=class{constructor(e,n,r){this.service=e,this.serviceName=n,this.errors=r}create(e,...n){let r=n[0]||{},i=`${this.service}/${e}`,o=this.errors[e],s=o?qs(o,r):"Error",c=`${this.serviceName}: ${s} (${i}).`;return new W(i,c,r)}};function qs(t,e){return t.replace(js,(n,r)=>{let i=e[r];return i!=null?String(i):`<${r}?>`})}var js=/\{\$([^}]+)}/g;function Et(t){let e=[];for(let[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("&"):""}function be(t){let e={};return t.replace(/^\?/,"").split("&").forEach(r=>{if(r){let[i,o]=r.split("=");e[decodeURIComponent(i)]=decodeURIComponent(o)}}),e}function Ie(t){let e=t.indexOf("?");if(!e)return"";let n=t.indexOf("#",e);return t.substring(e,n>0?n:void 0)}function Gr(t,e){let n=new gn(t,e);return n.subscribe.bind(n)}var gn=class{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.");Ks(e,["next","error","complete"])?i=e:i={next:e,error:n,complete:r},i.next===void 0&&(i.next=hn),i.error===void 0&&(i.error=hn),i.complete===void 0&&(i.complete=hn);let o=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),o}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<this.observers.length;n++)this.sendOne(n,e)}sendOne(e,n){this.task.then(()=>{if(this.observers!==void 0&&this.observers[e]!==void 0)try{n(this.observers[e])}catch{}})}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 Ks(t,e){if(typeof t!="object"||t===null)return!1;for(let n of e)if(n in t&&typeof t[n]=="function")return!0;return!1}function hn(){}var Uh=14400*1e3;function je(t){return t&&t._delegate?t._delegate:t}Hs.NODE_CLIENT=!0;var J=class{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}};var zs=[],A;(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"})(A||(A={}));var Ys={debug:A.DEBUG,verbose:A.VERBOSE,info:A.INFO,warn:A.WARN,error:A.ERROR,silent:A.SILENT},Xs=A.INFO,Js={[A.DEBUG]:"log",[A.VERBOSE]:"log",[A.INFO]:"info",[A.WARN]:"warn",[A.ERROR]:"error"},Qs=(t,e,...n)=>{if(e<t.logLevel)return;let r=new Date().toISOString(),i=Js[e];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},Te=class{constructor(e){this.name=e,this._logLevel=Xs,this._logHandler=Qs,this._userLogHandler=null,zs.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in A))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?Ys[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,A.DEBUG,...e),this._logHandler(this,A.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,A.VERBOSE,...e),this._logHandler(this,A.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,A.INFO,...e),this._logHandler(this,A.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,A.WARN,...e),this._logHandler(this,A.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,A.ERROR,...e),this._logHandler(this,A.ERROR,...e)}};var Zs=(t,e)=>e.some(n=>t instanceof n),qr,jr;function ea(){return qr||(qr=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ta(){return jr||(jr=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Kr=new WeakMap,In=new WeakMap,zr=new WeakMap,bn=new WeakMap,Sn=new WeakMap;function na(t){let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("success",o),t.removeEventListener("error",s)},o=()=>{n(G(t.result)),i()},s=()=>{r(t.error),i()};t.addEventListener("success",o),t.addEventListener("error",s)});return e.then(n=>{n instanceof IDBCursor&&Kr.set(n,t)}).catch(()=>{}),Sn.set(e,t),e}function ra(t){if(In.has(t))return;let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("complete",o),t.removeEventListener("error",s),t.removeEventListener("abort",s)},o=()=>{n(),i()},s=()=>{r(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",o),t.addEventListener("error",s),t.addEventListener("abort",s)});In.set(t,e)}var Tn={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return In.get(t);if(e==="objectStoreNames")return t.objectStoreNames||zr.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return G(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 Yr(t){Tn=t(Tn)}function ia(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){let r=t.call(bt(this),e,...n);return zr.set(r,e.sort?e.sort():[e]),G(r)}:ta().includes(t)?function(...e){return t.apply(bt(this),e),G(Kr.get(this))}:function(...e){return G(t.apply(bt(this),e))}}function oa(t){return typeof t=="function"?ia(t):(t instanceof IDBTransaction&&ra(t),Zs(t,ea())?new Proxy(t,Tn):t)}function G(t){if(t instanceof IDBRequest)return na(t);if(bn.has(t))return bn.get(t);let e=oa(t);return e!==t&&(bn.set(t,e),Sn.set(e,t)),e}var bt=t=>Sn.get(t);function Jr(t,e,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){let s=indexedDB.open(t,e),c=G(s);return r&&s.addEventListener("upgradeneeded",u=>{r(G(s.result),u.oldVersion,u.newVersion,G(s.transaction),u)}),n&&s.addEventListener("blocked",u=>n(u.oldVersion,u.newVersion,u)),c.then(u=>{o&&u.addEventListener("close",()=>o()),i&&u.addEventListener("versionchange",p=>i(p.oldVersion,p.newVersion,p))}).catch(()=>{}),c}var sa=["get","getKey","getAll","getAllKeys","count"],aa=["put","add","delete","clear"],An=new Map;function Xr(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(An.get(e))return An.get(e);let n=e.replace(/FromIndex$/,""),r=e!==n,i=aa.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||sa.includes(n)))return;let o=async function(s,...c){let u=this.transaction(s,i?"readwrite":"readonly"),p=u.store;return r&&(p=p.index(c.shift())),(await Promise.all([p[n](...c),i&&u.done]))[0]};return An.set(e,o),o}Yr(t=>({...t,get:(e,n,r)=>Xr(e,n)||t.get(e,n,r),has:(e,n)=>!!Xr(e,n)||t.has(e,n)}));var _n=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(n=>{if(ua(n)){let r=n.getImmediate();return`${r.library}/${r.version}`}else return null}).filter(n=>n).join(" ")}};function ua(t){return t.getComponent()?.type==="VERSION"}var wn="@firebase/app",Qr="0.14.8";var Q=new Te("@firebase/app"),la="@firebase/app-compat",da="@firebase/analytics-compat",pa="@firebase/analytics",fa="@firebase/app-check-compat",ha="@firebase/app-check",ma="@firebase/auth",ga="@firebase/auth-compat",va="@firebase/database",ya="@firebase/data-connect",Ea="@firebase/database-compat",ba="@firebase/functions",Ia="@firebase/functions-compat",Ta="@firebase/installations",Sa="@firebase/installations-compat",Aa="@firebase/messaging",Ca="@firebase/messaging-compat",_a="@firebase/performance",wa="@firebase/performance-compat",Ra="@firebase/remote-config",Pa="@firebase/remote-config-compat",ka="@firebase/storage",xa="@firebase/storage-compat",Oa="@firebase/firestore",Da="@firebase/ai",Na="@firebase/firestore-compat",La="firebase",Ua="12.9.0";var Ma={[wn]:"fire-core",[la]:"fire-core-compat",[pa]:"fire-analytics",[da]:"fire-analytics-compat",[ha]:"fire-app-check",[fa]:"fire-app-check-compat",[ma]:"fire-auth",[ga]:"fire-auth-compat",[va]:"fire-rtdb",[ya]:"fire-data-connect",[Ea]:"fire-rtdb-compat",[ba]:"fire-fn",[Ia]:"fire-fn-compat",[Ta]:"fire-iid",[Sa]:"fire-iid-compat",[Aa]:"fire-fcm",[Ca]:"fire-fcm-compat",[_a]:"fire-perf",[wa]:"fire-perf-compat",[Ra]:"fire-rc",[Pa]:"fire-rc-compat",[ka]:"fire-gcs",[xa]:"fire-gcs-compat",[Oa]:"fire-fst",[Na]:"fire-fst-compat",[Da]:"fire-vertex","fire-js":"fire-js",[La]:"fire-js-all"};var Fa=new Map,Va=new Map,Zr=new Map;function ei(t,e){try{t.container.addComponent(e)}catch(n){Q.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n)}}function Ae(t){let e=t.name;if(Zr.has(e))return Q.debug(`There were multiple attempts to register component ${e}.`),!1;Zr.set(e,t);for(let n of Fa.values())ei(n,t);for(let n of Va.values())ei(n,t);return!0}function ue(t){return t==null?!1:t.settings!==void 0}var Ba={"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."},kn=new X("app","Firebase",Ba);var It=Ua;function Se(t,e,n){let r=Ma[t]??t;n&&(r+=`-${n}`);let i=r.match(/\s|\//),o=e.match(/\s|\//);if(i||o){let s=[`Unable to register library "${r}" with version "${e}":`];i&&s.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&o&&s.push("and"),o&&s.push(`version name "${e}" contains illegal characters (whitespace or "/")`),Q.warn(s.join(" "));return}Ae(new J(`${r}-version`,()=>({library:r,version:e}),"VERSION"))}var Ha="firebase-heartbeat-database",$a=1,Ke="firebase-heartbeat-store",Cn=null;function ii(){return Cn||(Cn=Jr(Ha,$a,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(Ke)}catch{}}}}).catch(t=>{throw kn.create("idb-open",{originalErrorMessage:t.message})})),Cn}async function Wa(t){try{let n=(await ii()).transaction(Ke),r=await n.objectStore(Ke).get(oi(t));return await n.done,r}catch(e){if(e instanceof W)Q.warn(e.message);else{let n=kn.create("idb-get",{originalErrorMessage:e?.message});Q.warn(n.message)}}}async function ti(t,e){try{let r=(await ii()).transaction(Ke,"readwrite");await r.objectStore(Ke).put(e,oi(t)),await r.done}catch(n){if(n instanceof W)Q.warn(n.message);else{let r=kn.create("idb-set",{originalErrorMessage:n?.message});Q.warn(r.message)}}}function oi(t){return`${t.name}!${t.options.appId}`}var Ga=1024,qa=30,Rn=class{constructor(e){this.container=e,this._heartbeatsCache=null;let n=this.container.getProvider("app").getImmediate();this._storage=new Pn(n),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r))}async triggerHeartbeat(){try{let n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=ni();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(i=>i.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:n}),this._heartbeatsCache.heartbeats.length>qa){let i=Ka(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(i,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(e){Q.warn(e)}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return"";let e=ni(),{heartbeatsToSend:n,unsentEntries:r}=ja(this._heartbeatsCache.heartbeats),i=vn(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return Q.warn(e),""}}};function ni(){return new Date().toISOString().substring(0,10)}function ja(t,e=Ga){let n=[],r=t.slice();for(let i of t){let o=n.find(s=>s.agent===i.agent);if(o){if(o.dates.push(i.date),ri(n)>e){o.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),ri(n)>e){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}var Pn=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return $r()?Wr().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let n=await Wa(this.app);return n?.heartbeats?n:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return ti(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return ti(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}else return}};function ri(t){return vn(JSON.stringify({version:2,heartbeats:t})).length}function Ka(t){if(t.length===0)return-1;let e=0,n=t[0].date;for(let r=1;r<t.length;r++)t[r].date<n&&(n=t[r].date,e=r);return e}function za(t){Ae(new J("platform-logger",e=>new _n(e),"PRIVATE")),Ae(new J("heartbeat",e=>new Rn(e),"PRIVATE")),Se(wn,Qr,t),Se(wn,Qr,"esm2020"),Se("fire-js","")}za("");function hi(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}var mi=hi,gi=new X("auth","Firebase",hi());var _t=new Te("@firebase/auth");function Ya(t,...e){_t.logLevel<=A.WARN&&_t.warn(`Auth (${It}): ${t}`,...e)}function At(t,...e){_t.logLevel<=A.ERROR&&_t.error(`Auth (${It}): ${t}`,...e)}function Ce(t,...e){throw Yn(t,...e)}function zn(t,...e){return Yn(t,...e)}function vi(t,e,n){let r={...mi(),[e]:n};return new X("auth","Firebase",r).create(e,{appName:t.name})}function Ct(t){return vi(t,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Yn(t,...e){if(typeof t!="string"){let n=e[0],r=[...e.slice(1)];return r[0]&&(r[0].appName=t.name),t._errorFactory.create(n,...r)}return gi.create(t,...e)}function I(t,e,...n){if(!t)throw Yn(e,...n)}function q(t){let e="INTERNAL ASSERTION FAILED: "+t;throw At(e),new Error(e)}function wt(t,e){t||q(e)}function Xa(){return si()==="http:"||si()==="https:"}function si(){return typeof self<"u"&&self.location?.protocol||null}function Ja(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(Xa()||Br()||"connection"in navigator)?navigator.onLine:!0}function Qa(){if(typeof navigator>"u")return null;let t=navigator;return t.languages&&t.languages[0]||t.language||null}var Nn=class{constructor(e,n){this.shortDelay=e,this.longDelay=n,wt(n>e,"Short delay should be less than long delay!"),this.isMobile=Fr()||Hr()}get(){return Ja()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}};function Za(t,e){wt(t.emulator,"Emulator should always be set here");let{url:n}=t.emulator;return e?`${n}${e.startsWith("/")?e.slice(1):e}`:n}var Je=class{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;q("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;q("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;q("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}};var ec={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"};var tc=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],nc=new Nn(3e4,6e4);function j(t,e){return t.tenantId&&!e.tenantId?{...e,tenantId:t.tenantId}:e}async function K(t,e,n,r,i={}){return yi(t,i,async()=>{let o={},s={};r&&(e==="GET"?s=r:o={body:JSON.stringify(r)});let c=Et({key:t.config.apiKey,...s}).slice(1),u=await t._getAdditionalHeaders();u["Content-Type"]="application/json",t.languageCode&&(u["X-Firebase-Locale"]=t.languageCode);let p={method:e,headers:u,...o};return Vr()||(p.referrerPolicy="no-referrer"),t.emulatorConfig&&En(t.emulatorConfig.host)&&(p.credentials="include"),Je.fetch()(await Ei(t,t.config.apiHost,n,c),p)})}async function yi(t,e,n){t._canInitEmulator=!1;let r={...ec,...e};try{let i=new Ln(t),o=await Promise.race([n(),i.promise]);i.clearNetworkTimeout();let s=await o.json();if("needConfirmation"in s)throw Tt(t,"account-exists-with-different-credential",s);if(o.ok&&!("errorMessage"in s))return s;{let c=o.ok?s.errorMessage:s.error.message,[u,p]=c.split(" : ");if(u==="FEDERATED_USER_ID_ALREADY_LINKED")throw Tt(t,"credential-already-in-use",s);if(u==="EMAIL_EXISTS")throw Tt(t,"email-already-in-use",s);if(u==="USER_DISABLED")throw Tt(t,"user-disabled",s);let m=r[u]||u.toLowerCase().replace(/[_\s]+/g,"-");if(p)throw vi(t,m,p);Ce(t,m)}}catch(i){if(i instanceof W)throw i;Ce(t,"network-request-failed",{message:String(i)})}}async function Ft(t,e,n,r,i={}){let o=await K(t,e,n,r,i);return"mfaPendingCredential"in o&&Ce(t,"multi-factor-auth-required",{_serverResponse:o}),o}async function Ei(t,e,n,r){let i=`${e}${n}?${r}`,o=t,s=o.config.emulator?Za(t.config,i):`${t.config.apiScheme}://${i}`;return tc.includes(n)&&(await o._persistenceManagerAvailable,o._getPersistenceType()==="COOKIE")?o._getPersistence()._getFinalTarget(s).toString():s}function rc(t){switch(t){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}var Ln=class{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((n,r)=>{this.timer=setTimeout(()=>r(zn(this.auth,"network-request-failed")),nc.get())})}};function Tt(t,e,n){let r={appName:t.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);let i=zn(t,e,r);return i.customData._tokenResponse=n,i}function ai(t){return t!==void 0&&t.enterprise!==void 0}var Un=class{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],e.recaptchaKey===void 0)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0)return null;for(let n of this.recaptchaEnforcementState)if(n.provider&&n.provider===e)return rc(n.enforcementState);return null}isProviderEnabled(e){return this.getProviderEnforcementState(e)==="ENFORCE"||this.getProviderEnforcementState(e)==="AUDIT"}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}};async function ic(t,e){return K(t,"GET","/v2/recaptchaConfig",j(t,e))}async function oc(t,e){return K(t,"POST","/v1/accounts:delete",e)}async function Rt(t,e){return K(t,"POST","/v1/accounts:lookup",e)}function Ye(t){if(t)try{let e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function bi(t,e=!1){let n=je(t),r=await n.getIdToken(e),i=Ii(r);I(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");let o=typeof i.firebase=="object"?i.firebase:void 0,s=o?.sign_in_provider;return{claims:i,token:r,authTime:Ye(xn(i.auth_time)),issuedAtTime:Ye(xn(i.iat)),expirationTime:Ye(xn(i.exp)),signInProvider:s||null,signInSecondFactor:o?.sign_in_second_factor||null}}function xn(t){return Number(t)*1e3}function Ii(t){let[e,n,r]=t.split(".");if(e===void 0||n===void 0||r===void 0)return At("JWT malformed, contained fewer than 3 sections"),null;try{let i=yn(n);return i?JSON.parse(i):(At("Failed to decode base64 JWT payload"),null)}catch(i){return At("Caught error parsing JWT payload as JSON",i?.toString()),null}}function ci(t){let e=Ii(t);return I(e,"internal-error"),I(typeof e.exp<"u","internal-error"),I(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}async function Mn(t,e,n=!1){if(n)return e;try{return await e}catch(r){throw r instanceof W&&sc(r)&&t.auth.currentUser===t&&await t.auth.signOut(),r}}function sc({code:t}){return t==="auth/user-disabled"||t==="auth/user-token-expired"}var Fn=class{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){if(e){let n=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),n}else{this.errorBackoff=3e4;let r=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,r)}}schedule(e=!1){if(!this.isRunning)return;let n=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},n)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}};var Qe=class{constructor(e,n){this.createdAt=e,this.lastLoginAt=n,this._initializeTime()}_initializeTime(){this.lastSignInTime=Ye(this.lastLoginAt),this.creationTime=Ye(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}};async function Pt(t){let e=t.auth,n=await t.getIdToken(),r=await Mn(t,Rt(e,{idToken:n}));I(r?.users.length,e,"internal-error");let i=r.users[0];t._notifyReloadListener(i);let o=i.providerUserInfo?.length?Si(i.providerUserInfo):[],s=ac(t.providerData,o),c=t.isAnonymous,u=!(t.email&&i.passwordHash)&&!s?.length,p=c?u:!1,m={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 Qe(i.createdAt,i.lastLoginAt),isAnonymous:p};Object.assign(t,m)}async function Ti(t){let e=je(t);await Pt(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function ac(t,e){return[...t.filter(r=>!e.some(i=>i.providerId===r.providerId)),...e]}function Si(t){return t.map(({providerId:e,...n})=>({providerId:e,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}))}async function cc(t,e){let n=await yi(t,{},async()=>{let r=Et({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:i,apiKey:o}=t.config,s=await Ei(t,i,"/v1/token",`key=${o}`),c=await t._getAdditionalHeaders();c["Content-Type"]="application/x-www-form-urlencoded";let u={method:"POST",headers:c,body:r};return t.emulatorConfig&&En(t.emulatorConfig.host)&&(u.credentials="include"),Je.fetch()(s,u)});return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function uc(t,e){return K(t,"POST","/v2/accounts:revokeToken",j(t,e))}var Xe=class t{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){I(e.idToken,"internal-error"),I(typeof e.idToken<"u","internal-error"),I(typeof e.refreshToken<"u","internal-error");let n="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):ci(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}updateFromIdToken(e){I(e.length!==0,"internal-error");let n=ci(e);this.updateTokensAndExpiration(e,null,n)}async getToken(e,n=!1){return!n&&this.accessToken&&!this.isExpired?this.accessToken:(I(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){let{accessToken:r,refreshToken:i,expiresIn:o}=await cc(e,n);this.updateTokensAndExpiration(r,i,Number(o))}updateTokensAndExpiration(e,n,r){this.refreshToken=n||null,this.accessToken=e||null,this.expirationTime=Date.now()+r*1e3}static fromJSON(e,n){let{refreshToken:r,accessToken:i,expirationTime:o}=n,s=new t;return r&&(I(typeof r=="string","internal-error",{appName:e}),s.refreshToken=r),i&&(I(typeof i=="string","internal-error",{appName:e}),s.accessToken=i),o&&(I(typeof o=="number","internal-error",{appName:e}),s.expirationTime=o),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new t,this.toJSON())}_performRefresh(){return q("not implemented")}};function ee(t,e){I(typeof t=="string"||typeof t>"u","internal-error",{appName:e})}var le=class t{constructor({uid:e,auth:n,stsTokenManager:r,...i}){this.providerId="firebase",this.proactiveRefresh=new Fn(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new Qe(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){let n=await Mn(this,this.stsTokenManager.getToken(this.auth,e));return I(n,this.auth,"internal-error"),this.accessToken!==n&&(this.accessToken=n,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),n}getIdTokenResult(e){return bi(this,e)}reload(){return Ti(this)}_assign(e){this!==e&&(I(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=>({...n})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let n=new t({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return n.metadata._copy(this.metadata),n}_onReload(e){I(!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 Pt(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(ue(this.auth.app))return Promise.reject(Ct(this.auth));let e=await this.getIdToken();return await Mn(this,oc(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,n){let r=n.displayName??void 0,i=n.email??void 0,o=n.phoneNumber??void 0,s=n.photoURL??void 0,c=n.tenantId??void 0,u=n._redirectEventId??void 0,p=n.createdAt??void 0,m=n.lastLoginAt??void 0,{uid:T,emailVerified:x,isAnonymous:H,providerData:ie,stsTokenManager:dt}=n;I(T&&dt,e,"internal-error");let D=Xe.fromJSON(this.name,dt);I(typeof T=="string",e,"internal-error"),ee(r,e.name),ee(i,e.name),I(typeof x=="boolean",e,"internal-error"),I(typeof H=="boolean",e,"internal-error"),ee(o,e.name),ee(s,e.name),ee(c,e.name),ee(u,e.name),ee(p,e.name),ee(m,e.name);let R=new t({uid:T,auth:e,email:i,emailVerified:x,displayName:r,isAnonymous:H,photoURL:s,phoneNumber:o,tenantId:c,stsTokenManager:D,createdAt:p,lastLoginAt:m});return ie&&Array.isArray(ie)&&(R.providerData=ie.map(Y=>({...Y}))),u&&(R._redirectEventId=u),R}static async _fromIdTokenResponse(e,n,r=!1){let i=new Xe;i.updateFromServerResponse(n);let o=new t({uid:n.localId,auth:e,stsTokenManager:i,isAnonymous:r});return await Pt(o),o}static async _fromGetAccountInfoResponse(e,n,r){let i=n.users[0];I(i.localId!==void 0,"internal-error");let o=i.providerUserInfo!==void 0?Si(i.providerUserInfo):[],s=!(i.email&&i.passwordHash)&&!o?.length,c=new Xe;c.updateFromIdToken(r);let u=new t({uid:i.localId,auth:e,stsTokenManager:c,isAnonymous:s}),p={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:o,metadata:new Qe(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!o?.length};return Object.assign(u,p),u}};var ui=new Map;function de(t){wt(t instanceof Function,"Expected a class definition");let e=ui.get(t);return e?(wt(e instanceof t,"Instance stored in cache mismatched with class"),e):(e=new t,ui.set(t,e),e)}var kt=class{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,n){this.storage[e]=n}async _get(e){let n=this.storage[e];return n===void 0?null:n}async _remove(e){delete this.storage[e]}_addListener(e,n){}_removeListener(e,n){}};kt.type="NONE";var Vn=kt;function On(t,e,n){return`firebase:${t}:${e}:${n}`}var xt=class t{constructor(e,n,r){this.persistence=e,this.auth=n,this.userKey=r;let{config:i,name:o}=this.auth;this.fullUserKey=On(this.userKey,i.apiKey,o),this.fullPersistenceKey=On("persistence",i.apiKey,o),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(){let e=await this.persistence._get(this.fullUserKey);if(!e)return null;if(typeof e=="string"){let n=await Rt(this.auth,{idToken:e}).catch(()=>{});return n?le._fromGetAccountInfoResponse(this.auth,n,e):null}return le._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;let 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 t(de(Vn),e,r);let i=(await Promise.all(n.map(async p=>{if(await p._isAvailable())return p}))).filter(p=>p),o=i[0]||de(Vn),s=On(r,e.config.apiKey,e.name),c=null;for(let p of n)try{let m=await p._get(s);if(m){let T;if(typeof m=="string"){let x=await Rt(e,{idToken:m}).catch(()=>{});if(!x)break;T=await le._fromGetAccountInfoResponse(e,x,m)}else T=le._fromJSON(e,m);p!==o&&(c=T),o=p;break}}catch{}let u=i.filter(p=>p._shouldAllowMigration);return!o._shouldAllowMigration||!u.length?new t(o,e,r):(o=u[0],c&&await o._set(s,c.toJSON()),await Promise.all(n.map(async p=>{if(p!==o)try{await p._remove(s)}catch{}})),new t(o,e,r))}};function li(t){let e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(fc(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(lc(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(mc(e))return"Blackberry";if(gc(e))return"Webos";if(dc(e))return"Safari";if((e.includes("chrome/")||pc(e))&&!e.includes("edge/"))return"Chrome";if(hc(e))return"Android";{let n=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=t.match(n);if(r?.length===2)return r[1]}return"Other"}function lc(t=V()){return/firefox\//i.test(t)}function dc(t=V()){let e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function pc(t=V()){return/crios\//i.test(t)}function fc(t=V()){return/iemobile/i.test(t)}function hc(t=V()){return/android/i.test(t)}function mc(t=V()){return/blackberry/i.test(t)}function gc(t=V()){return/webos/i.test(t)}function Ai(t,e=[]){let n;switch(t){case"Browser":n=li(V());break;case"Worker":n=`${li(V())}-${t}`;break;default:n=t}let r=e.length?e.join(","):"FirebaseCore-web";return`${n}/JsCore/${It}/${r}`}var Bn=class{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,n){let r=o=>new Promise((s,c)=>{try{let u=e(o);s(u)}catch(u){c(u)}});r.onAbort=n,this.queue.push(r);let i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let n=[];try{for(let r of this.queue)await r(e),r.onAbort&&n.push(r.onAbort)}catch(r){n.reverse();for(let i of n)try{i()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:r?.message})}}};async function vc(t,e={}){return K(t,"GET","/v2/passwordPolicy",j(t,e))}var yc=6,Hn=class{constructor(e){let n=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=n.minPasswordLength??yc,n.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=n.maxPasswordLength),n.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=n.containsLowercaseCharacter),n.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=n.containsUppercaseCharacter),n.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=n.containsNumericCharacter),n.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=n.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){let n={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,n),this.validatePasswordCharacterOptions(e,n),n.isValid&&(n.isValid=n.meetsMinPasswordLength??!0),n.isValid&&(n.isValid=n.meetsMaxPasswordLength??!0),n.isValid&&(n.isValid=n.containsLowercaseLetter??!0),n.isValid&&(n.isValid=n.containsUppercaseLetter??!0),n.isValid&&(n.isValid=n.containsNumericCharacter??!0),n.isValid&&(n.isValid=n.containsNonAlphanumericCharacter??!0),n}validatePasswordLengthOptions(e,n){let 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<e.length;i++)r=e.charAt(i),this.updatePasswordCharacterOptionsStatuses(n,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,n,r,i,o){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=o))}};var Ot=class{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 Dt(this),this.idTokenSubscription=new Dt(this),this.beforeStateQueue=new Bn(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=gi,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion,this._persistenceManagerAvailable=new Promise(o=>this._resolvePersistenceManagerAvailable=o)}_initializeWithPersistence(e,n){return n&&(this._popupRedirectResolver=de(n)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await xt.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(n),this.lastNotifiedUid=this.currentUser?.uid||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;let 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{let n=await Rt(this,{idToken:e}),r=await le._fromGetAccountInfoResponse(this,n,e);await this.directlySetCurrentUser(r)}catch{await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(ue(this.app)){let o=this.app.settings.authIdToken;return o?new Promise(s=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(o).then(s,s))}):this.directlySetCurrentUser(null)}let n=await this.assertedPersistence.getCurrentUser(),r=n,i=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let o=this.redirectUser?._redirectEventId,s=r?._redirectEventId,c=await this.tryRedirectSignIn(e);(!o||o===s)&&c?.user&&(r=c.user,i=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(r)}catch(o){r=n,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(o))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return I(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}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 Pt(e)}catch(n){if(n?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=Qa()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(ue(this.app))return Promise.reject(Ct(this));let n=e?je(e):null;return n&&I(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&&I(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 ue(this.app)?Promise.reject(Ct(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return ue(this.app)?Promise.reject(Ct(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(de(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let 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(){let e=await vc(this),n=new Hn(e);this.tenantId===null?this._projectPasswordPolicy=n:this._tenantPasswordPolicies[this.tenantId]=n}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new X("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{let r=this.onAuthStateChanged(()=>{r(),e()},n)}})}async revokeAccessToken(e){if(this.currentUser){let n=await this.currentUser.getIdToken(),r={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:n};this.tenantId!=null&&(r.tenantId=this.tenantId),await uc(this,r)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,n){let r=await this.getOrInitRedirectPersistenceManager(n);return e===null?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let n=e&&de(e)||this._popupRedirectResolver;I(n,this,"argument-error"),this.redirectPersistenceManager=await xt.create(this,[de(n._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);let e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,n,r,i){if(this._deleted)return()=>{};let o=typeof n=="function"?n:n.next.bind(n),s=!1,c=this._isInitialized?Promise.resolve():this._initializationPromise;if(I(c,this,"internal-error"),c.then(()=>{s||o(this.currentUser)}),typeof n=="function"){let u=e.addObserver(n,r,i);return()=>{s=!0,u()}}else{let u=e.addObserver(n);return()=>{s=!0,u()}}}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 I(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Ai(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){let e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);let n=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();n&&(e["X-Firebase-Client"]=n);let r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(ue(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&Ya(`Error while retrieving App Check token: ${e.error}`),e?.token}};function Ci(t){return je(t)}var Dt=class{constructor(e){this.auth=e,this.observer=null,this.addObserver=Gr(n=>this.observer=n)}get next(){return I(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}};var _i={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function Ec(t){return _i.loadJS(t)}function bc(){return _i.recaptchaEnterpriseScript}var $n=class{constructor(){this.enterprise=new Wn}ready(e){e()}execute(e,n){return Promise.resolve("token")}render(e,n){return""}},Wn=class{ready(e){e()}execute(e,n){return Promise.resolve("token")}render(e,n){return""}},Ic="recaptcha-enterprise",wi="NO_RECAPTCHA",Gn=class{constructor(e){this.type=Ic,this.auth=Ci(e)}async verify(e="verify",n=!1){async function r(o){if(!n){if(o.tenantId==null&&o._agentRecaptchaConfig!=null)return o._agentRecaptchaConfig.siteKey;if(o.tenantId!=null&&o._tenantRecaptchaConfigs[o.tenantId]!==void 0)return o._tenantRecaptchaConfigs[o.tenantId].siteKey}return new Promise(async(s,c)=>{ic(o,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(u=>{if(u.recaptchaKey===void 0)c(new Error("recaptcha Enterprise site key undefined"));else{let p=new Un(u);return o.tenantId==null?o._agentRecaptchaConfig=p:o._tenantRecaptchaConfigs[o.tenantId]=p,s(p.siteKey)}}).catch(u=>{c(u)})})}function i(o,s,c){let u=window.grecaptcha;ai(u)?u.enterprise.ready(()=>{u.enterprise.execute(o,{action:e}).then(p=>{s(p)}).catch(()=>{s(wi)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new $n().execute("siteKey",{action:"verify"}):new Promise((o,s)=>{r(this.auth).then(c=>{if(!n&&ai(window.grecaptcha))i(c,o,s);else{if(typeof window>"u"){s(new Error("RecaptchaVerifier is only supported in browser"));return}let u=bc();u.length!==0&&(u+=c),Ec(u).then(()=>{i(c,o,s)}).catch(p=>{s(p)})}}).catch(c=>{s(c)})})}};async function ze(t,e,n,r=!1,i=!1){let o=new Gn(t),s;if(i)s=wi;else try{s=await o.verify(n)}catch{s=await o.verify(n,!0)}let c={...e};if(n==="mfaSmsEnrollment"||n==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in c){let u=c.phoneEnrollmentInfo.phoneNumber,p=c.phoneEnrollmentInfo.recaptchaToken;Object.assign(c,{phoneEnrollmentInfo:{phoneNumber:u,recaptchaToken:p,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in c){let u=c.phoneSignInInfo.recaptchaToken;Object.assign(c,{phoneSignInInfo:{recaptchaToken:u,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return c}return r?Object.assign(c,{captchaResp:s}):Object.assign(c,{captchaResponse:s}),Object.assign(c,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(c,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),c}async function di(t,e,n,r,i){if(i==="EMAIL_PASSWORD_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){let o=await ze(t,e,n,n==="getOobCode");return r(t,o)}else return r(t,e).catch(async o=>{if(o.code==="auth/missing-recaptcha-token"){let s=await ze(t,e,n,n==="getOobCode");return r(t,s)}else return Promise.reject(o)});else if(i==="PHONE_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){let o=await ze(t,e,n);return r(t,o).catch(async s=>{if(t._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")==="AUDIT"&&(s.code==="auth/missing-recaptcha-token"||s.code==="auth/invalid-app-credential")){let c=await ze(t,e,n,!1,!0);return r(t,c)}return Promise.reject(s)})}else{let o=await ze(t,e,n,!1,!0);return r(t,o)}else return Promise.reject(i+" provider is not supported.")}function Tc(t,e){let n=e?.persistence||[],r=(Array.isArray(n)?n:[n]).map(de);e?.errorMap&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(r,e?.popupRedirectResolver)}var Ze=class{constructor(e,n){this.providerId=e,this.signInMethod=n}toJSON(){return q("not implemented")}_getIdTokenResponse(e){return q("not implemented")}_linkToIdToken(e,n){return q("not implemented")}_getReauthenticationResolver(e){return q("not implemented")}};async function Sc(t,e){return K(t,"POST","/v1/accounts:signUp",e)}async function Ac(t,e){return Ft(t,"POST","/v1/accounts:signInWithPassword",j(t,e))}async function Cc(t,e){return Ft(t,"POST","/v1/accounts:signInWithEmailLink",j(t,e))}async function _c(t,e){return Ft(t,"POST","/v1/accounts:signInWithEmailLink",j(t,e))}var et=class t extends Ze{constructor(e,n,r,i=null){super("password",r),this._email=e,this._password=n,this._tenantId=i}static _fromEmailAndPassword(e,n){return new t(e,n,"password")}static _fromEmailAndCode(e,n,r=null){return new t(e,n,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let n=typeof e=="string"?JSON.parse(e):e;if(n?.email&&n?.password){if(n.signInMethod==="password")return this._fromEmailAndPassword(n.email,n.password);if(n.signInMethod==="emailLink")return this._fromEmailAndCode(n.email,n.password,n.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":let n={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return di(e,n,"signInWithPassword",Ac,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return Cc(e,{email:this._email,oobCode:this._password});default:Ce(e,"internal-error")}}async _linkToIdToken(e,n){switch(this.signInMethod){case"password":let r={idToken:n,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return di(e,r,"signUpPassword",Sc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return _c(e,{idToken:n,email:this._email,oobCode:this._password});default:Ce(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}};async function Dn(t,e){return Ft(t,"POST","/v1/accounts:signInWithIdp",j(t,e))}var wc="http://localhost",pe=class t extends Ze{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let n=new t(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):Ce("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){let n=typeof e=="string"?JSON.parse(e):e,{providerId:r,signInMethod:i,...o}=n;if(!r||!i)return null;let s=new t(r,i);return s.idToken=o.idToken||void 0,s.accessToken=o.accessToken||void 0,s.secret=o.secret,s.nonce=o.nonce,s.pendingToken=o.pendingToken||null,s}_getIdTokenResponse(e){let n=this.buildRequest();return Dn(e,n)}_linkToIdToken(e,n){let r=this.buildRequest();return r.idToken=n,Dn(e,r)}_getReauthenticationResolver(e){let n=this.buildRequest();return n.autoCreate=!1,Dn(e,n)}buildRequest(){let e={requestUri:wc,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let 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=Et(n)}return e}};function Rc(t){switch(t){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}function Pc(t){let e=be(Ie(t)).link,n=e?be(Ie(e)).deep_link_id:null,r=be(Ie(t)).deep_link_id;return(r?be(Ie(r)).link:null)||r||n||e||t}var Nt=class t{constructor(e){let n=be(Ie(e)),r=n.apiKey??null,i=n.oobCode??null,o=Rc(n.mode??null);I(r&&i&&o,"argument-error"),this.apiKey=r,this.operation=o,this.code=i,this.continueUrl=n.continueUrl??null,this.languageCode=n.lang??null,this.tenantId=n.tenantId??null}static parseLink(e){let n=Pc(e);try{return new t(n)}catch{return null}}};var _e=class t{constructor(){this.providerId=t.PROVIDER_ID}static credential(e,n){return et._fromEmailAndPassword(e,n)}static credentialWithLink(e,n){let r=Nt.parseLink(n);return I(r,"argument-error"),et._fromEmailAndCode(e,r.code,r.tenantId)}};_e.PROVIDER_ID="password";_e.EMAIL_PASSWORD_SIGN_IN_METHOD="password";_e.EMAIL_LINK_SIGN_IN_METHOD="emailLink";var qn=class{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}};var we=class extends qn{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}};var Re=class t extends we{constructor(){super("facebook.com")}static credential(e){return pe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return t.credential(e.oauthAccessToken)}catch{return null}}};Re.FACEBOOK_SIGN_IN_METHOD="facebook.com";Re.PROVIDER_ID="facebook.com";var Pe=class t extends we{constructor(){super("google.com"),this.addScope("profile")}static credential(e,n){return pe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:n})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthIdToken:n,oauthAccessToken:r}=e;if(!n&&!r)return null;try{return t.credential(n,r)}catch{return null}}};Pe.GOOGLE_SIGN_IN_METHOD="google.com";Pe.PROVIDER_ID="google.com";var ke=class t extends we{constructor(){super("github.com")}static credential(e){return pe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return t.credential(e.oauthAccessToken)}catch{return null}}};ke.GITHUB_SIGN_IN_METHOD="github.com";ke.PROVIDER_ID="github.com";var xe=class t extends we{constructor(){super("twitter.com")}static credential(e,n){return pe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:n})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthAccessToken:n,oauthTokenSecret:r}=e;if(!n||!r)return null;try{return t.credential(n,r)}catch{return null}}};xe.TWITTER_SIGN_IN_METHOD="twitter.com";xe.PROVIDER_ID="twitter.com";function kc(t,e){return K(t,"POST","/v2/accounts/mfaEnrollment:start",j(t,e))}function xc(t,e){return K(t,"POST","/v2/accounts/mfaEnrollment:finalize",j(t,e))}var pi="@firebase/auth",fi="1.12.0";var jn=class{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;let n=this.auth.onIdTokenChanged(r=>{e(r?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,n),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let n=this.internalListeners.get(e);n&&(this.internalListeners.delete(e),n(),this.updateProactiveRefresh())}assertAuthConfigured(){I(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}};function Oc(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 Dc(t){Ae(new J("auth",(e,{options:n})=>{let r=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),o=e.getProvider("app-check-internal"),{apiKey:s,authDomain:c}=r.options;I(s&&!s.includes(":"),"invalid-api-key",{appName:r.name});let u={apiKey:s,authDomain:c,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Ai(t)},p=new Ot(r,i,o,u);return Tc(p,n),p},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,n,r)=>{e.getProvider("auth-internal").initialize()})),Ae(new J("auth-internal",e=>{let n=Ci(e.getProvider("auth").getImmediate());return(r=>new jn(r))(n)},"PRIVATE").setInstantiationMode("EXPLICIT")),Se(pi,fi,Oc(t)),Se(pi,fi,"esm2020")}Je.initialize(fetch,Headers,Response);Dc("Node");var hm=zn("operation-not-supported-in-this-environment");Ot.prototype.setPersistence=async()=>{};function Nc(t,e){return K(t,"POST","/v2/accounts/mfaSignIn:finalize",j(t,e))}var Kn=class{constructor(e){this.factorId=e}_process(e,n,r){switch(n.type){case"enroll":return this._finalizeEnroll(e,n.credential,r);case"signin":return this._finalizeSignIn(e,n.credential);default:return q("unexpected MultiFactorSessionType")}}},Lt=class{static assertionForEnrollment(e,n){return Ut._fromSecret(e,n)}static assertionForSignIn(e,n){return Ut._fromEnrollmentId(e,n)}static async generateSecret(e){let n=e;I(typeof n.user?.auth<"u","internal-error");let r=await kc(n.user.auth,{idToken:n.credential,totpEnrollmentInfo:{}});return Mt._fromStartTotpMfaEnrollmentResponse(r,n.user.auth)}};Lt.FACTOR_ID="totp";var Ut=class t extends Kn{constructor(e,n,r){super("totp"),this.otp=e,this.enrollmentId=n,this.secret=r}static _fromSecret(e,n){return new t(n,void 0,e)}static _fromEnrollmentId(e,n){return new t(n,e)}async _finalizeEnroll(e,n,r){return I(typeof this.secret<"u",e,"argument-error"),xc(e,{idToken:n,displayName:r,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,n){I(this.enrollmentId!==void 0&&this.otp!==void 0,e,"argument-error");let r={verificationCode:this.otp};return Nc(e,{mfaPendingCredential:n,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:r})}},Mt=class t{constructor(e,n,r,i,o,s,c){this.sessionInfo=s,this.auth=c,this.secretKey=e,this.hashingAlgorithm=n,this.codeLength=r,this.codeIntervalSeconds=i,this.enrollmentCompletionDeadline=o}static _fromStartTotpMfaEnrollmentResponse(e,n){return new t(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,n)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,n){let r=!1;return(St(e)||St(n))&&(r=!0),r&&(St(e)&&(e=this.auth.currentUser?.email||"unknownuser"),St(n)&&(n=this.auth.name)),`otpauth://totp/${n}:${e}?secret=${this.secretKey}&issuer=${n}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}};function St(t){return typeof t>"u"||t?.length===0}import*as E from"valibot";function M(){return typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?globalThis._DNDEV_CONFIG_:null}var te=null;function rt(){return Pi().platform}function Pi(){if(te)return te;let t=M();if(t?.platform)return te={platform:t.platform,mode:t.mode,context:t.context,version:t.version,metadata:{detectedAt:t.timestamp}},te;let e=[];e.push(...Uc()),e.push(...Mc()),e.push(...Fc());let n=e.sort((r,i)=>i.confidence-r.confidence)[0];return!n||n.confidence<N.MINIMUM?(te={platform:S.UNKNOWN,mode:Ri(),context:Vc(),metadata:{detectedAt:Date.now()}},te):(te={platform:n.platform,mode:Ri(),context:n.context,version:Bc(n.platform),metadata:{...n.metadata,detectedAt:Date.now()}},te)}var tt=null,nt=null;function ki(){if(typeof globalThis<"u"&&globalThis.__NEXT_DATA__||typeof process<"u"&&process.env?.NEXT_RUNTIME)return nt=!0,!0;if(nt===!0)return!0;let t=M();if(t?.platform){let n=t.platform===S.NEXTJS;return n&&(nt=!0),n}let e=rt()===S.NEXTJS;return e&&(nt=!0),e}function xi(){if(tt!==null)return tt;let t=M();if(t?.platform)return tt=t.platform===S.VITE,tt;let e=rt()===S.VITE;return tt=e,e}function F(){return typeof window<"u"&&typeof document<"u"}function Xn(){return typeof process<"u"&&!!process.versions?.node}function Uc(){let t=[];if(F()){globalThis.__vite_plugin_react_preamble_installed__&&t.push({platform:S.VITE,confidence:N.HIGH,context:P.CLIENT,metadata:{viteHmrPort:globalThis.__vite_hmr_port}});let e=M();e?.platform===S.VITE&&t.push({platform:S.VITE,confidence:N.HIGH,context:P.CLIENT}),e?.i18n?.mapping&&t.push({platform:S.VITE,confidence:N.MEDIUM,context:P.CLIENT}),typeof globalThis<"u"&&globalThis.import?.meta?.hot!==void 0&&t.push({platform:S.VITE,confidence:N.LOW,context:P.CLIENT})}return Xn()&&(process.env.VITE&&t.push({platform:S.VITE,confidence:N.MEDIUM,context:P.SERVER}),process.env.npm_lifecycle_event?.includes(S.VITE)&&t.push({platform:S.VITE,confidence:N.LOW,context:P.BUILD})),t}function Mc(){let t=[];return Xn()&&(process.env.NEXT_RUNTIME&&t.push({platform:S.NEXTJS,confidence:N.HIGH,context:P.SERVER,metadata:{nextjsRuntime:process.env.NEXT_RUNTIME}}),process.env.__NEXT_PRIVATE_PREBUNDLED_REACT&&t.push({platform:S.NEXTJS,confidence:N.MEDIUM,context:P.SERVER}),process.env._DNDEV_CONFIG_&&t.push({platform:S.NEXTJS,confidence:N.LOW,context:P.SERVER})),F()&&(M()?.platform===S.NEXTJS&&t.push({platform:S.NEXTJS,confidence:N.HIGH,context:P.CLIENT}),globalThis.__NEXT_DATA__&&t.push({platform:S.NEXTJS,confidence:N.LOW,context:P.CLIENT})),t}function Fc(){let t=[];try{typeof globalThis<"u"&&globalThis.expo?.Constants?.expoConfig&&t.push({platform:S.EXPO,confidence:N.HIGH,context:P.CLIENT})}catch{}try{typeof globalThis<"u"&&globalThis.Platform?.OS&&!F()&&t.push({platform:S.REACT_NATIVE,confidence:N.MEDIUM,context:P.CLIENT})}catch{}let e=M();return e?.platform===S.EXPO?t.push({platform:S.EXPO,confidence:N.HIGH,context:P.CLIENT}):e?.platform===S.REACT_NATIVE&&t.push({platform:S.REACT_NATIVE,confidence:N.HIGH,context:P.CLIENT}),t}function Ri(){let t;return typeof import.meta<"u"&&import.meta.env?.MODE?t=import.meta.env.MODE:typeof process<"u"&&(t="production"),t===oe.PRODUCTION?oe.PRODUCTION:t===oe.TEST?oe.TEST:oe.DEVELOPMENT}function Vc(){return F()?P.CLIENT:Xn()?oe.PRODUCTION==="production"&&!process.env.NEXT_RUNTIME?P.BUILD:P.SERVER:P.CLIENT}function Bc(t){if(!(typeof process>"u"))return t===S.VITE?process.env.VITE_APP_VERSION||process.env.VITE_VERSION||process.env.APP_VERSION:t===S.NEXTJS?process.env.NEXT_PUBLIC_APP_VERSION||process.env.NEXT_PUBLIC_VERSION||process.env.__NEXT_VERSION||process.env.APP_VERSION:process.env.APP_VERSION||process.env.VITE_APP_VERSION||process.env.NEXT_PUBLIC_APP_VERSION}function Oi(t){return t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function Hc(t){let e,n=M();return n?.env&&typeof n.env=="object"&&(e=n.env[t]),e===void 0&&typeof import.meta<"u"&&import.meta.env&&(e=import.meta.env[t]),Oi(e)}function $c(t){let e=M(),n;return e?.env&&typeof e.env=="object"&&(n=e.env[t]),n===void 0&&typeof process<"u"&&process.env&&(n=process.env[t]),Oi(n)}function L(t,e){if(t==="NODE_ENV"||t==="VITE_NODE_ENV"||t==="NEXT_PUBLIC_NODE_ENV"||t==="MODE"||t==="DEV"||t==="PROD"){let s=M();if(s?.env?.MODE)return t==="DEV"?s.env.MODE==="development"?"true":"false":t==="PROD"?s.env.MODE==="production"?"true":"false":s.env.MODE;if(typeof import.meta<"u"&&import.meta.env){let c=import.meta.env;if(t==="MODE"&&c.MODE)return c.MODE;if(t==="DEV")return c.DEV?"true":"false";if(t==="PROD")return c.PROD?"true":"false"}if(typeof process<"u"){let c="production";return t==="DEV"?c==="development"?"true":"false":t==="PROD"?c==="production"?"true":"false":c}return t==="DEV"?"true":t==="PROD"?"false":"development"}let n=M()?.platform,r=e||n||(xi()?"vite":ki()?"nextjs":rt()),i=["MODE","DEV","PROD","SSR"],o;return r==="vite"?i.includes(t)||t.startsWith("VITE_")?o=t:o=`VITE_${t}`:r==="nextjs"?t.startsWith("NEXT_PUBLIC_")?o=t:o=`NEXT_PUBLIC_${t}`:o=t,r==="vite"?Hc(o):r==="nextjs"?$c(o):void 0}function ne(){if(typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production"))return!0;let t=L("APP_ENV"),e=L("NODE_ENV");return(t||e||"development").toLowerCase()!=="production"}var Di=E.object({name:E.string(),color:E.string(),icon:E.string(),button:E.object({backgroundColor:E.string(),textColor:E.string(),borderColor:E.string(),hoverBackgroundColor:E.string(),focusOutlineColor:E.string(),fontWeight:E.optional(E.string(),"500")})}),Wc=E.object({...Di.entries,type:E.picklist(["auth","both"]),scopes:E.optional(E.array(E.string())),firebaseProviderId:E.optional(E.string())}),Vt=E.union([E.literal(""),E.pipe(E.string(),E.url())]),Gc=E.object({authUrl:Vt,tokenUrl:Vt,profileUrl:Vt,revokeUrl:E.optional(Vt)}),qc=E.object({authentication:E.optional(E.array(E.string())),"api-access":E.array(E.string())}),ev=E.object({...Di.entries,type:E.picklist(["oauth","both"]),scopes:qc,endpoints:Gc}),it=null;function jc(){let t=[];for(let[e,n]of Object.entries(ye))E.safeParse(Wc,n).success?t.push(e):typeof window<"u"&&ne();return t}function Bt(){if(it!==null)return it;let t=L("AUTH_PARTNERS");if(!t)return it=[],it;let e=jc(),n=t.split(",").map(r=>r.trim().toLowerCase()).filter(r=>e.includes(r));return it=n,n}function ot(t){return typeof t=="object"&&t!==null&&"currentUser"in t&&typeof t.currentUser=="object"&&t.currentUser!==null}var Kc=12e4,Jn=class{refreshTimerId=null;refreshAttempts=0;refreshBuffer;maxRefreshAttempts;autoRefresh;authInstance;onTokenExpired;onFatalError;refreshCallback;tokenInfo={token:null,expiresAt:null,status:"not-initialized"};constructor(e=null,n={}){this.authInstance=e,this.refreshBuffer=n.refreshBufferMs??Kc,this.maxRefreshAttempts=n.maxRefreshAttempts??3,this.autoRefresh=n.autoRefresh!==!1,this.onTokenExpired=n.onTokenExpired,this.onFatalError=n.onFatalError}initialize(e){this.clearRefreshTimer(),this.refreshAttempts=0;let n=this.calculateTokenStatus(e.expiresAt);this.tokenInfo={...e,status:n},this.autoRefresh&&e.expiresAt&&this.scheduleRefresh(e.expiresAt)}getTokenInfo(){return this.tokenInfo}reset(){this.clearRefreshTimer(),this.tokenInfo={token:null,expiresAt:null,status:"not-initialized"}}async forceRefresh(e){try{if(this.refreshCallback&&await this.refreshCallback()&&this.tokenInfo.token)return this.tokenInfo.token;if(e&&typeof e.getIdToken=="function"){let n=await e.getIdToken(!0),r=new Date(Date.now()+3600*1e3);return this.updateTokenInfo({token:n,expiresAt:r}),this.refreshAttempts=0,n}else if(e&&typeof e.getIdTokenResult=="function"){let n=await e.getIdTokenResult(!0),r=new Date(n.expirationTime);return this.updateTokenInfo({token:n.token,expiresAt:r}),this.refreshAttempts=0,n.token}if(ot(this.authInstance)){let n=await this.authInstance.currentUser.getIdTokenResult(!0),r=new Date(n.expirationTime);return this.updateTokenInfo({token:n.token,expiresAt:r}),this.refreshAttempts=0,n.token}throw y(new Error("No valid refresh method available"),{userMessage:"Unable to refresh authentication token",severity:"warning",context:{component:"TokenManager"}})}catch(n){return this.handleError(n instanceof Error?n:new Error("Unknown error during token refresh")),null}}async getValidToken(){let{status:e,token:n}=this.tokenInfo;if(e==="valid")return n;if((e==="expiring-soon"||e==="expired")&&this.autoRefresh)try{if(this.refreshCallback&&await this.refreshCallback())return this.tokenInfo.token;if(ot(this.authInstance))return await this.forceRefresh(this.authInstance.currentUser)}catch(r){this.handleError(r instanceof Error?r:new Error("Failed to refresh token"))}return e==="expired"||e==="not-initialized"||e==="error"?null:n}onRefreshNeeded(e){return this.refreshCallback=e,()=>{this.refreshCallback=void 0}}updateTokenInfo(e){let n={token:e.token??this.tokenInfo.token,expiresAt:e.expiresAt??this.tokenInfo.expiresAt,refreshToken:e.refreshToken??this.tokenInfo.refreshToken,idToken:e.idToken??this.tokenInfo.idToken},r=this.calculateTokenStatus(n.expiresAt);this.tokenInfo={...n,status:r},this.autoRefresh&&n.expiresAt&&this.scheduleRefresh(n.expiresAt)}calculateTokenStatus(e){if(!e)return this.tokenInfo.token?"valid":"not-initialized";let n=new Date;if(n>=e)return"expired";let r=new Date(e.getTime()-this.refreshBuffer);return n>=r?"expiring-soon":"valid"}scheduleRefresh(e){this.clearRefreshTimer();let n=new Date,r=e.getTime()-n.getTime()-this.refreshBuffer;if(r<=0){ot(this.authInstance)&&this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)});return}this.refreshTimerId=setTimeout(()=>{ot(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)}):this.refreshCallback&&this.refreshCallback().catch(i=>{this.handleRefreshError(i)})},r)}handleRefreshError(e){if(ne(),this.refreshAttempts++,this.refreshAttempts<=this.maxRefreshAttempts){let n=Math.min(1e3*Math.pow(2,this.refreshAttempts-1),3e4);ne(),setTimeout(()=>{ot(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(r=>{this.handleRefreshError(r)}):this.refreshCallback&&this.refreshCallback().catch(r=>{this.handleRefreshError(r)})},n)}else this.tokenInfo={...this.tokenInfo,status:"error",error:e instanceof Error?e:new Error("Max token refresh attempts reached")},this.onTokenExpired&&this.onTokenExpired(),this.onFatalError&&this.onFatalError(e instanceof Error?e:new Error("Max token refresh attempts reached"))}handleError(e){ne(),this.tokenInfo={...this.tokenInfo,status:"error",error:e}}clearRefreshTimer(){this.refreshTimerId!==null&&(clearTimeout(this.refreshTimerId),this.refreshTimerId=null)}},Ev=We(Jn,null,{});var Ht=class{buildKey(e,n,r,i=!1){let o="dndev";switch(n){case"user":if(!r){if(i)return null;throw y(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:e,scope:n}})}return`${o}:user:${r}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}};var fe=null,zc="dndev-keys",st="encryption-keys",Ni="main";async function Li(){return new Promise((t,e)=>{let n=indexedDB.open(zc,1);n.onupgradeneeded=()=>{n.result.createObjectStore(st)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Yc(t){let e=await Li();return new Promise((n,r)=>{let i=e.transaction(st,"readwrite");i.objectStore(st).put(t,Ni),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async function Xc(){try{let t=await Li();return new Promise((e,n)=>{let i=t.transaction(st,"readonly").objectStore(st).get(Ni);i.onsuccess=()=>e(i.result??null),i.onerror=()=>n(i.error)})}catch{return null}}async function Jc(){try{return await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw y(t,{userMessage:"Failed to generate encryption key",context:{algorithm:"AES-GCM"}})}}async function Ui(){if(fe)return fe;try{let t=await Xc();return t?(fe=t,fe):(fe=await Jc(),await Yc(fe),fe)}catch(t){throw y(t,{userMessage:"Failed to get or create encryption key"})}}async function Mi(t){try{let e=await Ui(),n=window.crypto.getRandomValues(new Uint8Array(12)),r=typeof t=="string"?t:JSON.stringify(t),o=new TextEncoder().encode(r),s=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,o),c=new Uint8Array(n.length+s.byteLength);return c.set(n,0),c.set(new Uint8Array(s),n.length),btoa(String.fromCharCode(...c))}catch(e){throw y(e,{userMessage:"Failed to encrypt data"})}}async function Fi(t){try{let e=await Ui(),n=Uint8Array.from(atob(t),u=>u.charCodeAt(0)),r=n.slice(0,12),i=n.slice(12),o=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i),c=new TextDecoder().decode(o);try{return JSON.parse(c)}catch{return c}}catch(e){throw y(e,{userMessage:"Failed to decrypt data"})}}var re=class extends Ht{userId=null;constructor(e=null){super(),this.userId=e}setUserId(e){this.userId=e}async get(e,n={}){let{scope:r="user",encryption:i=!1}=n,o=this.buildKey(e,r,this.userId,!0);if(!o)return null;try{if(!F())return null;let s=localStorage.getItem(o);if(!s)return null;let c=JSON.parse(s);if(c.expiresAt&&new Date(c.expiresAt)<new Date)return await this.remove(e),null;let u=c.value;return i&&typeof u=="string"&&(u=await Fi(u)),u}catch(s){throw y(s,{userMessage:"Failed to retrieve data from local storage",context:{key:e,options:n}})}}async set(e,n,r={}){let{scope:i="user",encryption:o=!1,expiry:s=0}=r,c=this.buildKey(e,i,this.userId,!0);if(c)try{let u=n;o&&(u=await Mi(n));let p=s>0?new Date(Date.now()+s*1e3).toISOString():null,m=JSON.stringify({value:u,expiresAt:p,createdAt:new Date().toISOString()});typeof window<"u"&&localStorage.setItem(c,m)}catch(u){let p=u?.name==="QuotaExceededError"||u?.code===22?"Storage quota exceeded. Please free up space or login to sync to cloud.":u?.name==="SecurityError"||u?.code===18?"Storage access denied. Please enable localStorage or login to sync to cloud.":"Failed to store data in local storage";throw y(u,{userMessage:p,context:{key:e,options:r}})}}async remove(e){let n=["user","global","session"];for(let r of n)try{let i=this.buildKey(e,r,this.userId,!0);if(!i)continue;typeof window<"u"&&localStorage.removeItem(i)}catch{}}async clear(e){if(!e){let s=(typeof window<"u"?Object.keys(localStorage):[]).filter(c=>c.startsWith("dndev:"));for(let c of s)typeof window<"u"&&localStorage.removeItem(c);return}let n=e==="user"&&this.userId?`dndev:user:${this.userId}:`:`dndev:${e}:`,i=(typeof window<"u"?Object.keys(localStorage):[]).filter(o=>o.startsWith(n));for(let o of i)typeof window<"u"&&localStorage.removeItem(o)}};var at=class{localStrategy;userId;apiEndpoint;constructor(e,n="/api/storage"){if(!e)throw y("User ID is required for HybridStorageStrategy");this.userId=e,this.localStrategy=new re(e),this.apiEndpoint=n}async get(e,n={}){try{let r=await this.localStrategy.get(e,n);return r!==null?r:await this.getFromCloud(e,n)}catch(r){try{return await this.localStrategy.get(e,n)}catch(i){throw y(r,{userMessage:"Failed to retrieve data from storage",context:{key:e,options:n,fallbackError:i}})}}}async set(e,n,r={}){try{await this.localStrategy.set(e,n,r),this.setToCloud(e,n,r).catch(i=>{})}catch(i){throw y(i,{userMessage:"Failed to store data",context:{key:e,options:r}})}}async remove(e){try{await this.localStrategy.remove(e),this.removeFromCloud(e).catch(n=>{})}catch(n){throw y(n,{userMessage:"Failed to remove data",context:{key:e}})}}async clear(e){try{await this.localStrategy.clear(e),this.clearFromCloud(e).catch(n=>{})}catch(n){throw y(n,{userMessage:"Failed to clear storage",context:{scope:e}})}}buildKey(e,n,r,i=!1){let o="dndev";switch(n){case"user":if(!r){if(i)return null;throw y(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:e,scope:n}})}return`${o}:user:${r}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}async getFromCloud(e,n){try{let{scope:r="user"}=n,i=this.buildKey(e,r,this.userId,!0);if(!i)return null;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`);if(!o.ok){if(o.status===404)return null;throw y(new Error(`Cloud storage API error: ${o.status} ${o.statusText}`),{userMessage:"Failed to retrieve data from cloud storage",severity:"warning",context:{key:e,status:o.status}})}let s=await o.json();return s.expiresAt&&new Date(s.expiresAt)<new Date?(this.removeFromCloud(e).catch(console.warn),null):(this.localStrategy.set(e,s.value,n).catch(console.warn),s.value)}catch{return null}}async setToCloud(e,n,r){let{scope:i="user",expiry:o=0}=r,s=this.buildKey(e,i,this.userId,!0);if(!s)return;let c=o>0?new Date(Date.now()+o*1e3).toISOString():null,u={value:n,expiresAt:c,createdAt:new Date().toISOString()},p=await fetch(`${this.apiEndpoint}/${encodeURIComponent(s)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw y(new Error(`Cloud storage API error: ${p.status} ${p.statusText}`),{userMessage:"Failed to save data to cloud storage",severity:"error",context:{key:e,status:p.status}})}async removeFromCloud(e){let n=["user","global","session"];for(let r of n)try{let i=this.buildKey(e,r,this.userId,!0);if(!i)continue;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`,{method:"DELETE"});!o.ok&&o.status}catch{}}async clearFromCloud(e){try{let n=new URLSearchParams;e&&n.append("scope",e),e==="user"&&n.append("userId",this.userId);let r=n.toString(),i=r?`${this.apiEndpoint}/clear?${r}`:`${this.apiEndpoint}/clear`;(await fetch(i,{method:"DELETE"})).ok}catch{}}};var $t=class{strategy;initialized=!1;userId=null;isPro=!1;constructor(e=new re){this.strategy=e}initialize(){if(!this.initialized)try{this.initialized=!0}catch{ne()}}setStrategy(e){this.initialize(),this.strategy=e}updateUser(e,n){this.initialize(),n&&e?this.strategy=new at(e):this.strategy=new re(e)}updateStrategy(){this.isPro&&this.userId?this.strategy=new at(this.userId):this.strategy=new re(this.userId)}async get(e,n={}){return this.initialize(),this.strategy.get(e,n)}async set(e,n,r={}){return this.initialize(),this.strategy.set(e,n,r)}async remove(e){return this.initialize(),this.strategy.remove(e)}async clear(e){return this.initialize(),this.strategy.clear(e)}async setSecure(e,n,r={}){return this.initialize(),this.set(e,n,{...r,encryption:!0})}async getSecure(e,n={}){return this.initialize(),this.get(e,{...n,encryption:!0})}},Qc=We($t);var B={AUTH:"auth",OAUTH:"oauth",I18N:"i18n",BILLING:"billing",ROUTES:"routes",THEMES:"themes",COMPONENTS:"components",CRUD:"crud",FORMS:"forms",REALTIME:"realtime",STORAGE:"storage"};function he(t){return!!t&&t.trim()!==""}var Zv={[B.AUTH]:()=>Bt().length>0,[B.OAUTH]:()=>["VITE_OAUTH_GOOGLE_CLIENT_ID","VITE_OAUTH_GITHUB_CLIENT_ID","VITE_OAUTH_FACEBOOK_CLIENT_ID","VITE_OAUTH_TWITTER_CLIENT_ID","VITE_OAUTH_LINKEDIN_CLIENT_ID","VITE_OAUTH_DISCORD_CLIENT_ID","VITE_OAUTH_SLACK_CLIENT_ID","VITE_OAUTH_MICROSOFT_CLIENT_ID","VITE_OAUTH_APPLE_CLIENT_ID"].some(e=>he(L(e))),[B.I18N]:()=>!0,[B.BILLING]:()=>!!(he(L("STRIPE_PUBLISHABLE_KEY"))||he(L("BILLING_ENABLED"))&&L("BILLING_ENABLED")==="true"),[B.ROUTES]:()=>!0,[B.THEMES]:()=>!0,[B.COMPONENTS]:()=>!0,[B.CRUD]:()=>!0,[B.FORMS]:()=>!0,[B.REALTIME]:()=>!!(he(L("REALTIME_ENABLED"))&&L("REALTIME_ENABLED")==="true"||he(L("FIREBASE_CONFIG"))),[B.STORAGE]:()=>!!(he(L("STORAGE_ENABLED"))&&L("STORAGE_ENABLED")==="true"||he(L("FIREBASE_CONFIG")))};var mu=pr(or(),1);var gu=pr(or(),1);var sr=class{events=new Map;eventCache=new Map;maxListeners=10;cacheTTL=180*1e3;on(e,n,r){if(typeof n!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:n,once:!1,context:r};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,n)}}once(e,n,r){if(typeof n!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:n,once:!0,context:r};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,n)}}off(e,n){let r=this.events.get(e);if(!r||r.length===0)return!1;let i=r.findIndex(o=>o.handler===n);return i===-1?!1:(r.splice(i,1),r.length===0&&this.events.delete(e),!0)}emit(e,...n){this.cacheEvent(e,n);let r=this.events.get(e);if(!r||r.length===0)return!1;let i=[...r],o=[];for(let s of i)try{s.context?s.handler.apply(s.context,n):s.handler(...n),s.once&&o.push(s)}catch(c){y(c,{userMessage:`Error in event handler for ${e}`,context:{eventName:e,args:n},severity:"warning"})}if(o.length>0){let s=this.events.get(e);if(s){let c=s.filter(u=>!o.includes(u));c.length===0?this.events.delete(e):this.events.set(e,c)}}return!0}hasListeners(e){let n=this.events.get(e);return!!n&&n.length>0}listenerCount(e){return this.events.get(e)?.length||0}eventNames(){return Array.from(this.events.keys())}listeners(e){let n=this.events.get(e);return n?n.map(r=>r.handler):[]}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}setMaxListeners(e){return this.maxListeners=e>0?e:1/0,this}getMaxListeners(){return this.maxListeners}getListeners(e){let n=this.events.get(e);return n||(n=[],this.events.set(e,n)),n}checkListenerCount(e){let n=this.listenerCount(e);this.maxListeners!==1/0&&n>this.maxListeners}cacheEvent(e,n){let r=this.eventCache.get(e);r||(r=[],this.eventCache.set(e,r)),r.push({data:n,timestamp:Date.now()}),this.cleanupCache(e)}getCachedEvents(e){let n=this.eventCache.get(e);return!n||n.length===0?[]:(this.cleanupCache(e),(this.eventCache.get(e)||[]).map(i=>i.data))}clearCachedEvents(e){this.eventCache.delete(e)}clearAllCachedEvents(){this.eventCache.clear()}getCacheStats(){let e=0,n=null,r=null;for(let[o,s]of this.eventCache.entries()){e+=s.length;for(let c of s)(n===null||c.timestamp<n)&&(n=c.timestamp),(r===null||c.timestamp>r)&&(r=c.timestamp)}let i=`${Math.round(e*200/1024)}KB`;return{totalEvents:e,eventTypes:this.eventCache.size,oldestEvent:n,newestEvent:r,memoryEstimate:i}}cleanupCache(e){let n=Date.now()-this.cacheTTL;if(e){let r=this.eventCache.get(e);if(r){let i=r.filter(o=>o.timestamp>n);i.length===0?this.eventCache.delete(e):this.eventCache.set(e,i)}}else for(let[r,i]of this.eventCache.entries()){let o=i.filter(s=>s.timestamp>n);o.length===0?this.eventCache.delete(r):this.eventCache.set(r,o)}}},My=new sr;var Wy={user:null,userProfile:null,userSubscription:null,loading:!1,reauthenticateWithPassword:async()=>{},reauthenticateWithProvider:async()=>{},deleteAccount:async()=>{},error:null,emailVerification:{status:"pending"},getPartnerState:()=>"idle",setPartnerState:()=>{},partnerError:null,status:Ve.DEGRADED,hasRole:async()=>!1,hasTier:async()=>!1,hasFeature:async()=>!1,getCustomClaims:()=>({}),getCustomClaim:()=>null,signInWithEmail:async()=>null,createUserWithEmail:async()=>null,signInWithPartner:async()=>null,linkWithPartner:async()=>null,signInWithGoogleCredential:async()=>null,signOut:async()=>{},sendPasswordResetEmail:async()=>{},updatePassword:async()=>{},sendEmailVerification:async()=>{},getEmailVerificationStatus:async()=>({status:"pending"}),isEmailVerificationEnabled:async()=>!1,sendSignInLinkToEmail:async()=>{},signInWithEmailLink:async()=>null,isSignInWithEmailLink:()=>!1,getCurrentUser:async()=>null,isAuthenticated:!1,userRole:O.GUEST,userTier:Fe.FREE,can:{navigate:t=>t===!1||typeof t=="object"&&!t.required,view:()=>!1,edit:()=>!1,delete:()=>!1,create:()=>!1,perform:()=>!1,has:()=>!1},isAvailable:!1},Gy={status:Ve.DEGRADED,error:null,loading:!1,checkout:async()=>({sessionId:"",sessionUrl:null,success:!1,error:"Billing not available - consent required"}),cancelSubscription:async()=>({success:!1,endsAt:""}),changePlan:async()=>({success:!1}),refreshStatus:async()=>{},openCustomerPortal:async()=>{},clearError:()=>{},isAvailable:!1},qy={status:Ve.DEGRADED,data:null,loading:!1,error:null,get:async()=>null,set:async()=>{},update:async()=>{},delete:async()=>{},add:async()=>"",query:async()=>[],subscribe:()=>()=>{},subscribeToCollection:()=>()=>{},invalidate:async()=>{},isAvailable:!1},jy={status:Ve.DEGRADED,error:null,partners:{},connectedPartners:[],connect:async()=>{},disconnect:async()=>{},isConnected:()=>!1,getCredentials:()=>null,handleCallback:async()=>{},isAvailable:!1};import*as d from"valibot";var ct=new Map;function v(t,e){ct.set(t,e)}function AE(t){return ct.has(t)}function CE(){return Array.from(ct.keys())}function _E(){ct.clear()}function C(t,e){return e?t:d.nullish(t)}var Gt=t=>{let e=[];t.validation?.minLength!==void 0&&e.push(d.minLength(t.validation.minLength,`Must be at least ${t.validation.minLength} characters`)),t.validation?.maxLength!==void 0&&e.push(d.maxLength(t.validation.maxLength,`Must be at most ${t.validation.maxLength} characters`)),t.validation?.pattern&&e.push(d.regex(new RegExp(t.validation.pattern),"Invalid format"));let n=e.length>0?d.pipe(d.string(),...e):d.string();return C(n,t.validation?.required)},vu=t=>{let e=d.pipe(d.string(),d.email("Invalid email address"));return C(e,t.validation?.required)},yu=t=>{let e=t.validation?.minLength!==void 0?d.pipe(d.string(),d.minLength(t.validation.minLength,`Must be at least ${t.validation.minLength} characters`)):d.string();return C(e,t.validation?.required)},Eu=t=>{let e=d.pipe(d.string(),d.url("Invalid URL"));return C(e,t.validation?.required)},Ne=t=>{let e=[];t.validation?.min!==void 0&&e.push(d.minValue(t.validation.min,`Must be at least ${t.validation.min}`)),t.validation?.max!==void 0&&e.push(d.maxValue(t.validation.max,`Must be at most ${t.validation.max}`));let n=e.length>0?d.pipe(d.number(),...e):d.number();return C(n,t.validation?.required)},Ji=t=>{let e=d.boolean();return C(e,t.validation?.required)},Le=t=>{let e=d.pipe(d.string(),d.isoTimestamp("Invalid date format"));return C(e,t.validation?.required)},to=d.object({url:d.string(),filename:d.string(),size:d.number(),mimeType:d.nullish(d.string()),uploadedAt:d.nullish(d.string())}),Qi=t=>{let e=d.nullable(to);return C(e,t.validation?.required)},Zi=t=>{let e=d.array(to);return C(e,t.validation?.required)},no=d.object({fullUrl:d.string(),thumbUrl:d.string()}),bu=t=>C(no,t.validation?.required),Iu=t=>{let e=d.array(no);return C(e,t.validation?.required)},Tu=t=>{let e=d.object({lat:d.number(),lng:d.number()});return C(e,t.validation?.required)},Su=t=>{let e=d.object({formatted_address:d.string(),latitude:d.number(),longitude:d.number(),street_number:d.nullish(d.string()),route:d.nullish(d.string()),locality:d.nullish(d.string()),administrative_area_level_1:d.nullish(d.string()),administrative_area_level_2:d.nullish(d.string()),country:d.nullish(d.string()),postal_code:d.nullish(d.string())});return C(e,t.validation?.required)},Au=t=>{let e=d.record(d.string(),d.unknown());return C(e,t.validation?.required)},Cu=t=>{let e=d.array(d.unknown());return C(e,t.validation?.required)},ar=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let r=e.map(o=>o.value),i=d.picklist(r);return C(i,t.validation?.required)}let n=d.union([d.string(),d.number()]);return C(n,t.validation?.required)},_u=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let r=e.map(o=>o.value),i=d.array(d.picklist(r));return C(i,t.validation?.required)}let n=d.array(d.string());return C(n,t.validation?.required)},wu=t=>{let e=d.pipe(d.string(),d.regex(ft,"Invalid ID format"));return C(e,t.validation?.required)},cr=t=>{let e=d.string();return C(e,t.validation?.required)},Ru=t=>{let e=d.string();return C(e,t.validation?.required)},Pu=t=>{let e=t.validation?.minLength??15,n=t.validation?.maxLength??34,r=t.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",i=[];if(e!==void 0&&i.push(d.minLength(e,`IBAN must be at least ${e} characters`)),n!==void 0&&i.push(d.maxLength(n,`IBAN must not exceed ${n} characters`)),r){let s=typeof r=="string"?new RegExp(r):r;i.push(d.regex(s,"Invalid IBAN format"))}let o=i.length>0?d.pipe(d.string(),...i):d.string();return C(o,t.validation?.required)},eo=()=>d.never(),ku=t=>{let e=t.options?.fieldSpecific;if(e?.checkedValue&&e?.uncheckedValue){let r=[e.checkedValue,e.uncheckedValue],i=d.picklist(r);return C(i,t.validation?.required)}let n=d.boolean();return C(n,t.validation?.required)},xu=t=>d.custom(n=>t.validation?.required?typeof n=="object"&&n!==null?n.gdprConsent===!0:!1:n===!1||n===null||n===void 0?!0:typeof n=="object"&&n!==null?n.gdprConsent===!0:!1,"GDPR consent must be given"),Ou=t=>{let e=d.object({amount:d.number(),currency:d.optional(d.string()),vatIncluded:d.optional(d.boolean()),discountPercent:d.optional(d.pipe(d.number(),d.minValue(0),d.maxValue(100)))});return C(e,t.validation?.required)};function Du(){v("text",Gt),v("textarea",Gt),v("richtext",Gt),v("color",Gt),v("email",vu),v("password",yu),v("url",Eu),v("tel",Ru),v("iban",Pu),v("number",Ne),v("currency",Ne),v("price",Ou),v("range",Ne),v("year",Ne),v("rating",Ne),v("duration",Ne),v("boolean",Ji),v("checkbox",Ji),v("gdprConsent",xu),v("date",Le),v("datetime-local",Le),v("time",Le),v("week",Le),v("month",Le),v("timestamp",Le),v("file",Qi),v("files",Zi),v("document",Qi),v("documents",Zi),v("image",bu),v("images",Iu),v("geopoint",Tu),v("address",Su),v("map",Au),v("array",Cu),v("select",ar),v("multiselect",_u),v("radio",ar),v("combobox",ar),v("switch",ku),v("reference",wu),v("hidden",cr),v("avatar",cr),v("badge",cr),v("submit",eo),v("reset",eo)}Du();function ut(t){if(t.validation?.schema){let r=t.validation.schema;return C(r,t.validation?.required)}let e=ct.get(t.type);if(e){let r=e(t);if(r!==null)return r}let n=d.unknown();return C(n,t.validation?.required)}var ur=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],PE="available",kE=["draft","deleted"],Ue=["id","createdAt","updatedAt","createdById","updatedById"],Nu=[...Ue,"status"];function xE(t){return Nu.includes(t)}function OE(t){return Ue.includes(t)}var w={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...ur]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0,pattern:ft.source}},createdAt:{name:"_createdAt",type:"timestamp",visibility:"technical",label:"crud:fields._createdAt",validation:{required:!0}},updatedAt:{name:"_updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields._updatedAt",validation:{required:!0}},createdById:{name:"_createdById",type:"reference",visibility:"technical",label:"crud:fields._createdById",validation:{required:!0}},updatedById:{name:"_updatedById",type:"reference",visibility:"technical",label:"crud:fields._updatedById",validation:{required:!0}}};function lt(t,e){return Object.assign(t,{visibility:e})}function me(t,e){let n=t;return n.metadata={collection:e.collection,entity:e.name,...e.uniqueKeys&&{uniqueKeys:e.uniqueKeys}},n}function ro(t){let e=ut(t);return lt(e,t.visibility)}function io(t){let e=ut({...t,validation:{...t.validation,required:!1}});return lt(e,t.visibility)}function Lu(t){let e=t.fields,n={};for(let[D,R]of Object.entries(e))R.visibility!=="hidden"&&(n[D]=ro(R));let r=me(z.object(n),t),i={};for(let[D,R]of Object.entries(e))R.visibility!=="hidden"&&(Ue.includes(D)||(i[D]=ro(R)));let o=me(z.object(i),t),s={};for(let[D,R]of Object.entries(e))if(R.visibility!=="hidden"&&!Ue.includes(D))if(D==="status"){let Y=z.literal("draft");s[D]=lt(Y,R.visibility)}else s[D]=io(R);let c=me(z.object(s),t),u={};for(let[D,R]of Object.entries(e))R.visibility!=="hidden"&&(Ue.includes(D)||(u[D]=io(R)));u.id=lt(ut(w.id),"technical");let p=me(z.object(u),t),m;if(t.listFields&&t.listFields.length>0){let D=["id","status"],R=[...new Set([...D,...t.listFields])];m={};for(let Y of R){let Me=n[Y];Me&&(m[Y]=Me)}}else m=n;let T=me(z.object(m),t),x,H=Ge(t);if(H.length>0){let D=["id","status"],R=[...new Set([...D,...H])];x={};for(let Y of R){let Me=n[Y];Me&&(x[Y]=Me)}}else x=n;let ie=me(z.object(x),t),dt=me(z.object({id:lt(ut(w.id),"technical")}),t);return{create:o,draft:c,update:p,get:r,list:T,listCard:ie,delete:dt}}import"valibot";function $E(t,e){let n=t;return n.metadata=e,n}var oo=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function so(t){return typeof t=="string"&&t.length>=19&&t.includes("-")&&t.includes(":")}function qt(t,e=""){if(Array.isArray(t))t.forEach((n,r)=>{let i=`${e}[${r}]`;if(typeof n=="string"&&so(n)){if(!oo.test(n))throw y({userMessage:`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:i,value:n},severity:"error"})}else typeof n=="object"&&n!==null&&qt(n,i)});else if(typeof t=="object"&&t!==null)for(let[n,r]of Object.entries(t)){let i=e?`${e}.${n}`:n;if(typeof r=="string"&&so(r)){if(!oo.test(r))throw y({userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:i,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&qt(r,i)}}import*as co from"valibot";var lr={};function KE(t){lr.uniqueConstraintValidator=t}async function ao(t,e,n){let{uniqueFields:r=[],collection:i}=t.metadata;r.length!==0&&lr.uniqueConstraintValidator&&await Promise.all(r.map(async({field:o,errorMessage:s})=>{let c=e[o];if(c==null)return;if(await lr.uniqueConstraintValidator.checkDuplicate(i,o,c,n))throw y({userMessage:s||`${o} must be unique`,code:"already-exists",context:{field:o}})}))}async function JE(t,e,n,r){co.parse(t,e),qt(e),await ao(t,e,r),t.metadata.customValidate&&await t.metadata.customValidate(e,n)}function Uu(t){return t!=null&&typeof t=="object"&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null}function sb(t){if(!Uu(t)){let e=t,n=e&&typeof e=="object"&&"constructor"in e&&e.constructor&&e.constructor.name||"unknown";throw y(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:n}})}return t.metadata.collection}function Mu(t){let e=t.field.endsWith("Id")?t.field.slice(0,-2):t.field,n=t.collection||(e.endsWith("y")?e.slice(0,-1)+"ies":e+"s");return{name:t.field,label:`crud:fields.${t.field}`,type:"reference",visibility:"technical",editable:"create-only",validation:{required:!0,reference:n}}}function Fu(t,e){if(!e||e.length===0)return t.map(i=>({value:i.value,label:i.label}));let n=t.map(i=>({value:i.value,label:i.label})),r=new Set(t.map(i=>i.value));for(let i of e)r.has(i.value)||n.push(i);return n}function Vu(t,e){if(!(!t.uniqueKeys||t.uniqueKeys.length===0))for(let n=0;n<t.uniqueKeys.length;n++){let r=t.uniqueKeys[n];if(!r)continue;if(!r.fields||r.fields.length===0)throw y(new Error(`uniqueKeys[${n}] for entity '${t.name}' must have at least one field`),{userMessage:`uniqueKeys[${n}] for entity '${t.name}' must have at least one field`,context:{entityName:t.name,uniqueKeyIndex:n},severity:"error"});let i=r.fields.filter(o=>!e.has(o));if(i.length>0)throw y(new Error(`uniqueKeys[${n}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${n}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:t.name,uniqueKeyIndex:n,invalidFields:i},severity:"error"})}}function Bu(t){let{form:e,fields:n}=t,r=Object.keys(n);if(e){if(e.type==="multi-step"||e.type==="wizard"){if(!e.steps||e.steps.length===0)throw y(new Error(`Multi-step form for entity '${t.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${t.name}' must have at least one step`,context:{entityName:t.name,operation:"validateFormConfig"},severity:"error"});let i=e.steps.flatMap(u=>u.fields),o=i.filter(u=>!r.includes(u));if(o.length>0)throw y(new Error(`Multi-step form for entity '${t.name}' references non-existent fields: ${o.join(", ")}`),{userMessage:`Multi-step form for entity '${t.name}' references non-existent fields: ${o.join(", ")}`,context:{entityName:t.name,invalidFields:o,operation:"validateFormConfig"},severity:"error"});let s=new Set(i);r.filter(u=>!s.has(u)).length>0}e.rules&&e.rules.forEach((i,o)=>{let c=(Array.isArray(i.condition)?i.condition.map(m=>m.field):[i.condition.field]).filter(m=>!r.includes(m));if(c.length>0)throw y(new Error(`Dynamic form rule ${o} for entity '${t.name}' references non-existent condition fields: ${c.join(", ")}`),{userMessage:`Dynamic form rule ${o} for entity '${t.name}' references non-existent condition fields: ${c.join(", ")}`,context:{entityName:t.name,ruleIndex:o,invalidFields:c,operation:"validateFormConfig"},severity:"error"});let p=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(m=>!r.includes(m));if(p.length>0)throw y(new Error(`Dynamic form rule ${o} for entity '${t.name}' references non-existent affected fields: ${p.join(", ")}`),{userMessage:`Dynamic form rule ${o} for entity '${t.name}' references non-existent affected fields: ${p.join(", ")}`,context:{entityName:t.name,ruleIndex:o,invalidFields:p,operation:"validateFormConfig"},severity:"error"})}),Object.entries(n).forEach(([i,o])=>{if(o.dependsOn&&!r.includes(o.dependsOn.field))throw y(new Error(`Field '${i}' in entity '${t.name}' depends on non-existent field: ${o.dependsOn.field}`),{userMessage:`Field '${i}' in entity '${t.name}' depends on non-existent field: ${o.dependsOn.field}`,context:{entityName:t.name,fieldName:i,dependsOnField:o.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function Hu(t){return t.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...t.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function db(t){try{Bu(t);let e=Hu(t),n={...t.fields,...w,...t.fields.createdAt&&{createdAt:{...w.createdAt,...t.fields.createdAt,type:w.createdAt.type,visibility:w.createdAt.visibility}},...t.fields.updatedAt&&{updatedAt:{...w.updatedAt,...t.fields.updatedAt,type:w.updatedAt.type,visibility:w.updatedAt.visibility}},...t.fields.createdById&&{createdById:{...w.createdById,...t.fields.createdById,type:w.createdById.type,visibility:w.createdById.visibility}},...t.fields.updatedById&&{updatedById:{...w.updatedById,...t.fields.updatedById,type:w.updatedById.type,visibility:w.updatedById.visibility}},...t.fields.status&&{status:{...w.status,...t.fields.status,type:w.status.type,visibility:w.status.visibility,editable:w.status.editable,validation:{...w.status.validation,required:!0,nullable:t.fields.status.validation?.nullable,options:Fu(ur,t.fields.status.validation?.options)}}},...t.scope&&{[t.scope.field]:Mu(t.scope)}};if(t.listFields){let o=new Set(Object.keys(n)),s=t.listFields.filter(c=>!o.has(c));if(s.length>0)throw y(new Error(`Entity '${t.name}' defines listFields that do not exist: ${s.join(", ")}`),{userMessage:`Entity '${t.name}' defines listFields that do not exist: ${s.join(", ")}`,context:{entityName:t.name,invalidFields:s,operation:"defineEntity"},severity:"error"})}if(t.listCardFields){let o=new Set(Object.keys(n)),c=Ge(t).filter(u=>!o.has(u));if(c.length>0)throw y(new Error(`Entity '${t.name}' defines listCardFields that do not exist: ${c.join(", ")}`),{userMessage:`Entity '${t.name}' defines listCardFields that do not exist: ${c.join(", ")}`,context:{entityName:t.name,invalidFields:c,operation:"defineEntity"},severity:"error"})}if(t.uniqueKeys){let o=new Set(Object.keys(n));Vu(t,o)}let r={...Xt,...t.access||{}},i=t.namespace||`entity-${t.name.toLowerCase()}`;return{...t,form:e,fields:n,access:r,namespace:i}}catch(e){throw y(e,{userMessage:`Failed to define entity '${t.name}'`,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}}function fb(t,e,n=1,r=!1){let i=[];if(r)for(let o=e;o>=t;o-=n)i.push({value:String(o),label:String(o)});else for(let o=t;o<=e;o+=n)i.push({value:String(o),label:String(o)});return i}var ge=new Map;function mb(t,e){ge.has(t),ge.set(t,e)}function gb(t){ge.delete(t)}function vb(t){let e=ge.get(t);return e?e():null}function yb(t){return ge.has(t)}function Eb(){return Array.from(ge.keys())}function bb(){ge.clear()}export{ql as AGGREGATE_FILTER_OPERATORS,Gl as AGGREGATE_OPERATIONS,md as AUTH_EVENTS,ye as AUTH_PARTNERS,Sl as AUTH_PARTNER_STATE,yt as AuthHardening,br as AuthUserSchema,Ue as BACKEND_GENERATED_FIELD_NAMES,vd as BILLING_EVENTS,To as BREAKPOINT_RANGES,Qt as BREAKPOINT_THRESHOLDS,fr as COMMON_TIER_CONFIGS,N as CONFIDENCE_LEVELS,Cr as CONSENT_CATEGORY,P as CONTEXTS,se as CRUD_OPERATORS,sn as CURRENCY_MAP,Er as CheckoutSessionMetadataSchema,hr as CreateCheckoutSessionRequestSchema,mr as CreateCheckoutSessionResponseSchema,Ir as CustomClaimsSchema,Xt as DEFAULT_ENTITY_ACCESS,ae as DEFAULT_ERROR_MESSAGES,Vd as DEFAULT_LAYOUT_PRESET,ur as DEFAULT_STATUS_OPTIONS,PE as DEFAULT_STATUS_VALUE,Qu as DEFAULT_SUBSCRIPTION,Ip as DENSITY,k as DoNotDevError,Fl as EDITABLE,ht as ENTITY_HOOK_ERRORS,oe as ENVIRONMENTS,Be as ERROR_CODES,ld as ERROR_SEVERITY,dd as ERROR_SOURCE,Tr as EntityHookError,Kt as FEATURES,Tp as FEATURE_CONSENT_MATRIX,Ve as FEATURE_STATUS,Hl as FIELD_TYPES,Jt as FIREBASE_ERROR_MAP,ft as FIRESTORE_ID_PATTERN,Sr as GITHUB_PERMISSION_LEVELS,kE as HIDDEN_STATUSES,Bd as LAYOUT_PRESET,Bl as LIST_SCHEMA_TYPE,Ed as OAUTH_EVENTS,en as OAUTH_PARTNERS,Vl as ORDER_DIRECTION,cp as PARTNER_ICONS,Id as PAYLOAD_EVENTS,zt as PERMISSIONS,S as PLATFORMS,Nl as PWA_ASSET_TYPES,Dl as PWA_DISPLAY_MODES,Eo as ProductDeclarationSchema,al as ProductDeclarationsSchema,Ll as ROUTE_SOURCES,Ol as STORAGE_SCOPES,xl as STORAGE_TYPES,Sd as STRIPE_EVENTS,pt as STRIPE_MODES,Xu as SUBSCRIPTION_DURATIONS,ve as SUBSCRIPTION_STATUS,Fe as SUBSCRIPTION_TIERS,Lr as ServerUtils,dn as SingletonManager,Io as StripeBackConfigSchema,bo as StripeFrontConfigSchema,vo as StripePaymentSchema,yo as StripeSubscriptionSchema,vr as SubscriptionClaimsSchema,gr as SubscriptionDataSchema,Nu as TECHNICAL_FIELD_NAMES,O as USER_ROLES,Yt as UserSubscriptionSchema,Ml as VISIBILITY,yr as WebhookEventSchema,qe as addMonths,fn as addYears,Su as addressSchema,Cu as arraySchema,w as baseFields,Ji as booleanSchema,Ls as calculateSubscriptionEndDate,rn as captureErrorToSentry,Qd as checkGitHubAccessSchema,_E as clearSchemaGenerators,bb as clearScopeProviders,He as commonErrorCodeMappings,an as compactToISOString,Ts as configureProviders,ws as createAsyncSingleton,Ju as createDefaultSubscriptionClaims,Al as createDefaultUserProfile,Jl as createEntitySchema,$ as createErrorHandler,Jo as createMetadata,Rs as createMethodProxy,Lu as createSchemas,We as createSingleton,_s as createSingletonWithParams,Le as dateSchema,db as defineEntity,ed as deleteEntitySchema,tn as detectErrorSource,tp as disconnectOAuthSchema,vu as emailSchema,$E as enhanceSchema,qo as ensureSpreadable,Zd as exchangeTokenSchema,Qi as fileSchema,Zi as filesSchema,Ds as filterVisibleFields,Zo as formatCurrency,Pr as formatDate,ss as formatRelativeTime,xu as gdprConsentSchema,xr as generateCodeChallenge,kr as generateCodeVerifier,ps as generateFirestoreRuleCondition,hs as generatePKCEPair,Tu as geopointSchema,So as getBreakpointFromWidth,Md as getBreakpointUtils,sb as getCollectionName,np as getConnectionsSchema,Rr as getCurrencyLocale,Qo as getCurrencySymbol,ns as getCurrentTimestamp,Ql as getEntitySchema,Ge as getListCardFieldNames,Ss as getProvider,CE as getRegisteredSchemaTypes,Eb as getRegisteredScopeProviders,bs as getRoleFromClaims,ut as getSchemaType,vb as getScopeValue,pn as getVisibleFields,os as getWeekFromISOString,Ao as githubPermissionSchema,Zt as githubRepoConfigSchema,Xd as grantGitHubAccessSchema,y as handleError,AE as hasCustomSchemaGenerator,Uu as hasMetadata,As as hasProvider,Ns as hasRestrictedVisibility,gt as hasRoleAccess,yb as hasScopeProvider,Is as hasTierAccess,Pu as ibanSchema,Oo as isAuthPartnerId,OE as isBackendGeneratedField,Ud as isBreakpoint,cn as isCompactDateString,Nr as isFieldVisible,xE as isFrameworkField,Do as isOAuthPartnerId,ms as isPKCESupported,es as isoToCompactString,Es as lazyImport,td as listEntitiesSchema,Au as mapSchema,ce as mapToDoNotDevError,fs as maybeTranslate,_u as multiselectSchema,eo as neverSchema,ts as normalizeToISOString,Ne as numberSchema,qu as overrideFeatures,Yu as overridePaymentModes,ju as overridePermissions,zu as overrideSubscriptionStatus,Gu as overrideSubscriptionTiers,Wu as overrideUserRoles,un as parseDate,cs as parseDateToNoonUTC,Us as parseISODate,Bs as parseServerCookie,yu as passwordSchema,bu as pictureSchema,Iu as picturesSchema,Ou as priceSchema,fb as rangeOptions,wu as referenceSchema,ep as refreshTokenSchema,v as registerSchemaGenerator,mb as registerScopeProvider,KE as registerUniqueConstraintValidator,Cs as resetProviders,Jd as revokeGitHubAccessSchema,Go as safeValidate,ar as selectSchema,Vo as showNotification,cr as stringSchema,ku as switchSchema,Ru as telSchema,Gt as textSchema,is as timestampToISOString,us as toDateOnly,rs as toISOString,Ko as translateArray,Yo as translateArrayRange,Xo as translateArrayWithIndices,zo as translateObjectArray,gb as unregisterScopeProvider,Zl as updateEntitySchema,Ps as updateMetadata,Eu as urlSchema,lp as validateAuthPartners,Il as validateAuthSchemas,yl as validateAuthUser,ll as validateBillingSchemas,sl as validateCheckoutSessionMetadata,vs as validateCodeChallenge,gs as validateCodeVerifier,tl as validateCreateCheckoutSessionRequest,nl as validateCreateCheckoutSessionResponse,bl as validateCustomClaims,qt as validateDates,JE as validateDocument,Vs as validateEnvVar,Fs as validateMetadata,dp as validateOAuthPartners,ul as validateStripeBackConfig,cl as validateStripeFrontConfig,il as validateSubscriptionClaims,rl as validateSubscriptionData,ao as validateUniqueFields,Ms as validateUrl,El as validateUserSubscription,ol as validateWebhookEvent,Wo as validateWithSchema,Fo as withErrorHandling,ys as withGracefulDegradation,$o as wrapAuthError,Bo as wrapCrudError,Ho as wrapStorageError};
1
+ var uo=Object.create;var jt=Object.defineProperty;var lo=Object.getOwnPropertyDescriptor;var po=Object.getOwnPropertyNames;var fo=Object.getPrototypeOf,ho=Object.prototype.hasOwnProperty;var dr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),mo=(t,e)=>{for(var n in e)jt(t,n,{get:e[n],enumerable:!0})},go=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of po(e))!ho.call(t,i)&&i!==n&&jt(t,i,{get:()=>e[i],enumerable:!(r=lo(e,i))||r.enumerable});return t};var pr=(t,e,n)=>(n=t!=null?uo(fo(t)):{},go(e||!t||!t.__esModule?jt(n,"default",{value:t,enumerable:!0}):n,t));var to=dr(b=>{"use strict";var nr=Symbol.for("react.transitional.element"),gu=Symbol.for("react.portal"),vu=Symbol.for("react.fragment"),yu=Symbol.for("react.strict_mode"),Eu=Symbol.for("react.profiler"),bu=Symbol.for("react.consumer"),Iu=Symbol.for("react.context"),Tu=Symbol.for("react.forward_ref"),Su=Symbol.for("react.suspense"),Au=Symbol.for("react.memo"),Yi=Symbol.for("react.lazy"),Cu=Symbol.for("react.activity"),qi=Symbol.iterator;function _u(t){return t===null||typeof t!="object"?null:(t=qi&&t[qi]||t["@@iterator"],typeof t=="function"?t:null)}var Xi={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ji=Object.assign,Qi={};function Le(t,e,n){this.props=t,this.context=e,this.refs=Qi,this.updater=n||Xi}Le.prototype.isReactComponent={};Le.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("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")};Le.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Zi(){}Zi.prototype=Le.prototype;function rr(t,e,n){this.props=t,this.context=e,this.refs=Qi,this.updater=n||Xi}var ir=rr.prototype=new Zi;ir.constructor=rr;Ji(ir,Le.prototype);ir.isPureReactComponent=!0;var ji=Array.isArray;function tr(){}var _={H:null,A:null,T:null,S:null},eo=Object.prototype.hasOwnProperty;function or(t,e,n){var r=n.ref;return{$$typeof:nr,type:t,key:e,ref:r!==void 0?r:null,props:n}}function wu(t,e){return or(t.type,e,t.props)}function sr(t){return typeof t=="object"&&t!==null&&t.$$typeof===nr}function Ru(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var Ki=/\/+/g;function er(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Ru(""+t.key):e.toString(36)}function Pu(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(tr,tr):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function Ne(t,e,n,r,i){var o=typeof t;(o==="undefined"||o==="boolean")&&(t=null);var s=!1;if(t===null)s=!0;else switch(o){case"bigint":case"string":case"number":s=!0;break;case"object":switch(t.$$typeof){case nr:case gu:s=!0;break;case Yi:return s=t._init,Ne(s(t._payload),e,n,r,i)}}if(s)return i=i(t),s=r===""?"."+er(t,0):r,ji(i)?(n="",s!=null&&(n=s.replace(Ki,"$&/")+"/"),Ne(i,e,n,"",function(p){return p})):i!=null&&(sr(i)&&(i=wu(i,n+(i.key==null||t&&t.key===i.key?"":(""+i.key).replace(Ki,"$&/")+"/")+s)),e.push(i)),1;s=0;var c=r===""?".":r+":";if(ji(t))for(var u=0;u<t.length;u++)r=t[u],o=c+er(r,u),s+=Ne(r,e,n,o,i);else if(u=_u(t),typeof u=="function")for(t=u.call(t),u=0;!(r=t.next()).done;)r=r.value,o=c+er(r,u++),s+=Ne(r,e,n,o,i);else if(o==="object"){if(typeof t.then=="function")return Ne(Pu(t),e,n,r,i);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return s}function Gt(t,e,n){if(t==null)return t;var r=[],i=0;return Ne(t,r,"","",function(o){return e.call(n,o,i++)}),r}function ku(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var zi=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}},xu={map:Gt,forEach:function(t,e,n){Gt(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return Gt(t,function(){e++}),e},toArray:function(t){return Gt(t,function(e){return e})||[]},only:function(t){if(!sr(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};b.Activity=Cu;b.Children=xu;b.Component=Le;b.Fragment=vu;b.Profiler=Eu;b.PureComponent=rr;b.StrictMode=yu;b.Suspense=Su;b.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=_;b.__COMPILER_RUNTIME={__proto__:null,c:function(t){return _.H.useMemoCache(t)}};b.cache=function(t){return function(){return t.apply(null,arguments)}};b.cacheSignal=function(){return null};b.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var r=Ji({},t.props),i=t.key;if(e!=null)for(o in e.key!==void 0&&(i=""+e.key),e)!eo.call(e,o)||o==="key"||o==="__self"||o==="__source"||o==="ref"&&e.ref===void 0||(r[o]=e[o]);var o=arguments.length-2;if(o===1)r.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];r.children=s}return or(t.type,i,r)};b.createContext=function(t){return t={$$typeof:Iu,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:bu,_context:t},t};b.createElement=function(t,e,n){var r,i={},o=null;if(e!=null)for(r in e.key!==void 0&&(o=""+e.key),e)eo.call(e,r)&&r!=="key"&&r!=="__self"&&r!=="__source"&&(i[r]=e[r]);var s=arguments.length-2;if(s===1)i.children=n;else if(1<s){for(var c=Array(s),u=0;u<s;u++)c[u]=arguments[u+2];i.children=c}if(t&&t.defaultProps)for(r in s=t.defaultProps,s)i[r]===void 0&&(i[r]=s[r]);return or(t,o,i)};b.createRef=function(){return{current:null}};b.forwardRef=function(t){return{$$typeof:Tu,render:t}};b.isValidElement=sr;b.lazy=function(t){return{$$typeof:Yi,_payload:{_status:-1,_result:t},_init:ku}};b.memo=function(t,e){return{$$typeof:Au,type:t,compare:e===void 0?null:e}};b.startTransition=function(t){var e=_.T,n={};_.T=n;try{var r=t(),i=_.S;i!==null&&i(n,r),typeof r=="object"&&r!==null&&typeof r.then=="function"&&r.then(tr,zi)}catch(o){zi(o)}finally{e!==null&&n.types!==null&&(e.types=n.types),_.T=e}};b.unstable_useCacheRefresh=function(){return _.H.useCacheRefresh()};b.use=function(t){return _.H.use(t)};b.useActionState=function(t,e,n){return _.H.useActionState(t,e,n)};b.useCallback=function(t,e){return _.H.useCallback(t,e)};b.useContext=function(t){return _.H.useContext(t)};b.useDebugValue=function(){};b.useDeferredValue=function(t,e){return _.H.useDeferredValue(t,e)};b.useEffect=function(t,e){return _.H.useEffect(t,e)};b.useEffectEvent=function(t){return _.H.useEffectEvent(t)};b.useId=function(){return _.H.useId()};b.useImperativeHandle=function(t,e,n){return _.H.useImperativeHandle(t,e,n)};b.useInsertionEffect=function(t,e){return _.H.useInsertionEffect(t,e)};b.useLayoutEffect=function(t,e){return _.H.useLayoutEffect(t,e)};b.useMemo=function(t,e){return _.H.useMemo(t,e)};b.useOptimistic=function(t,e){return _.H.useOptimistic(t,e)};b.useReducer=function(t,e,n){return _.H.useReducer(t,e,n)};b.useRef=function(t){return _.H.useRef(t)};b.useState=function(t){return _.H.useState(t)};b.useSyncExternalStore=function(t,e,n){return _.H.useSyncExternalStore(t,e,n)};b.useTransition=function(){return _.H.useTransition()};b.version="19.2.4"});var ar=dr((uy,no)=>{"use strict";no.exports=to()});var Lr={};mo(Lr,{AuthHardening:()=>yt,CURRENCY_MAP:()=>sn,DEFAULT_ERROR_MESSAGES:()=>ae,DoNotDevError:()=>w,SingletonManager:()=>dn,addMonths:()=>qe,addYears:()=>fn,calculateSubscriptionEndDate:()=>Ls,captureErrorToSentry:()=>rn,commonErrorCodeMappings:()=>He,compactToISOString:()=>an,configureProviders:()=>Ts,createAsyncSingleton:()=>ws,createErrorHandler:()=>$,createMetadata:()=>Jo,createMethodProxy:()=>Rs,createSingleton:()=>We,createSingletonWithParams:()=>_s,detectErrorSource:()=>tn,ensureSpreadable:()=>qo,filterVisibleFields:()=>Ds,formatCurrency:()=>Zo,formatDate:()=>Pr,formatRelativeTime:()=>ss,generateCodeChallenge:()=>xr,generateCodeVerifier:()=>kr,generateFirestoreRuleCondition:()=>ps,generatePKCEPair:()=>hs,getCurrencyLocale:()=>Rr,getCurrencySymbol:()=>Qo,getCurrentTimestamp:()=>ns,getListCardFieldNames:()=>Ge,getProvider:()=>Ss,getRoleFromClaims:()=>bs,getVisibleFields:()=>pn,getWeekFromISOString:()=>os,handleError:()=>y,hasProvider:()=>As,hasRestrictedVisibility:()=>Ns,hasRoleAccess:()=>gt,hasTierAccess:()=>Is,isCompactDateString:()=>cn,isFieldVisible:()=>Nr,isPKCESupported:()=>ms,isoToCompactString:()=>es,lazyImport:()=>Es,mapToDoNotDevError:()=>ce,maybeTranslate:()=>fs,normalizeToISOString:()=>ts,parseDate:()=>un,parseDateToNoonUTC:()=>cs,parseISODate:()=>Us,parseServerCookie:()=>Bs,resetProviders:()=>Cs,safeValidate:()=>Go,showNotification:()=>Vo,timestampToISOString:()=>is,toDateOnly:()=>us,toISOString:()=>rs,translateArray:()=>Ko,translateArrayRange:()=>Yo,translateArrayWithIndices:()=>Xo,translateObjectArray:()=>zo,updateMetadata:()=>Ps,validateCodeChallenge:()=>vs,validateCodeVerifier:()=>gs,validateEnvVar:()=>Vs,validateMetadata:()=>Fs,validateUrl:()=>Ms,validateWithSchema:()=>Wo,withErrorHandling:()=>Fo,withGracefulDegradation:()=>ys,wrapAuthError:()=>$o,wrapCrudError:()=>Bo,wrapStorageError:()=>Ho});var O={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function $u(t){Object.assign(O,t)}var Fe={FREE:"free",PRO:"pro",PREMIUM:"premium"};function Wu(t){Object.assign(Fe,t)}var Kt={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function Gu(t){Object.assign(Kt,t)}var zt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function qu(t){Object.assign(zt,t)}import*as l from"valibot";var ve={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function Ku(t){Object.assign(ve,t)}var pt={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function zu(t){Object.assign(pt,t)}var Yu={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function Xu(t){return{tier:"free",status:"active",subscriptionId:null,customerId:t,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var fr={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},Ju={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as a from"valibot";var hr=a.object({userId:a.optional(a.string()),productId:a.optional(a.string()),priceId:a.string(),successUrl:a.pipe(a.string(),a.url()),cancelUrl:a.pipe(a.string(),a.url()),customerEmail:a.optional(a.pipe(a.string(),a.email())),userEmail:a.optional(a.pipe(a.string(),a.email())),metadata:a.optional(a.record(a.string(),a.string())),allowPromotionCodes:a.optional(a.boolean()),mode:a.optional(a.picklist([pt.PAYMENT,pt.SUBSCRIPTION]))}),mr=a.object({sessionId:a.string(),sessionUrl:a.nullable(a.pipe(a.string(),a.url()))}),gr=a.object({userId:a.string(),tier:a.string(),status:a.picklist(Object.values(ve)),subscriptionId:a.nullable(a.string()),customerId:a.string(),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp())}),vr=a.object({tier:a.string(),subscriptionId:a.nullable(a.string()),customerId:a.string(),status:a.picklist(Object.values(ve)),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp()),isDefault:a.optional(a.boolean())}),yr=a.object({id:a.string(),type:a.string(),data:a.object({object:a.any()}),created:a.pipe(a.string(),a.isoTimestamp())}),Er=a.looseObject({userId:a.optional(a.string()),firebaseUid:a.optional(a.string()),productType:a.optional(a.string())});function el(t){return a.safeParse(hr,t)}function tl(t){return a.safeParse(mr,t)}function nl(t){return a.safeParse(gr,t)}function rl(t){return a.safeParse(vr,t)}function il(t){return a.safeParse(yr,t)}function ol(t){return a.safeParse(Er,t)}var vo=a.object({type:a.literal("StripePayment"),name:a.pipe(a.string(),a.minLength(1,"Product name is required")),description:a.optional(a.string()),price:a.string(),currency:a.optional(a.pipe(a.string(),a.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a.pipe(a.string(),a.minLength(1,"Stripe price ID is required")),tier:a.pipe(a.string(),a.minLength(1,"Tier is required")),duration:a.pipe(a.string(),a.minLength(1,"Duration is required")),allowPromotionCodes:a.optional(a.boolean()),metadata:a.optional(a.record(a.string(),a.string()))}),yo=a.object({type:a.literal("StripeSubscription"),name:a.pipe(a.string(),a.minLength(1,"Product name is required")),description:a.optional(a.string()),price:a.string(),currency:a.optional(a.pipe(a.string(),a.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a.pipe(a.string(),a.minLength(1,"Stripe price ID is required")),tier:a.pipe(a.string(),a.minLength(1,"Tier is required")),duration:a.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:a.optional(a.boolean()),metadata:a.optional(a.record(a.string(),a.string()))}),Eo=a.variant("type",[vo,yo]),sl=a.record(a.string(),Eo),bo=a.record(a.string(),a.object({name:a.string(),price:a.string(),currency:a.string(),description:a.optional(a.string()),features:a.optional(a.array(a.string())),priceId:a.string(),allowPromotionCodes:a.optional(a.boolean())})),Io=a.record(a.string(),a.object({type:a.picklist(["StripePayment","StripeSubscription"]),name:a.string(),price:a.number(),currency:a.string(),priceId:a.string(),tier:a.string(),duration:a.string(),description:a.optional(a.string()),metadata:a.optional(a.record(a.string(),a.string())),allowPromotionCodes:a.optional(a.boolean())}));function al(t){return a.parse(bo,t)}function cl(t){return a.parse(Io,t)}function ul(){let t={createCheckoutSessionRequest:a.safeParse(hr,{}),createCheckoutSessionResponse:a.safeParse(mr,{}),subscriptionData:a.safeParse(gr,{}),subscriptionClaims:a.safeParse(vr,{}),webhookEvent:a.safeParse(yr,{}),checkoutSessionMetadata:a.safeParse(Er,{})};return{success:Object.values(t).every(e=>e.success),results:t}}var br=l.object({id:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),emailVerified:l.optional(l.boolean()),lastLoginAt:l.optional(l.string()),providerData:l.optional(l.array(l.object({providerId:l.string(),uid:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),phoneNumber:l.optional(l.nullable(l.string()))}))),role:l.optional(l.picklist(Object.values(O))),customClaims:l.optional(l.record(l.string(),l.any()))}),Yt=l.object({userId:l.string(),tier:l.picklist(Object.values(Fe)),status:l.picklist(Object.values(ve)),isActive:l.optional(l.boolean()),features:l.optional(l.array(l.string())),subscriptionId:l.nullable(l.string()),customerId:l.string(),subscriptionEnd:l.nullable(l.pipe(l.string(),l.isoTimestamp())),cancelAtPeriodEnd:l.boolean(),updatedAt:l.pipe(l.string(),l.isoTimestamp())}),Ir=l.object({role:l.optional(l.picklist(Object.values(O))),subscription:l.optional(Yt),features:l.optional(l.array(l.picklist(Object.values(Kt)))),permissions:l.optional(l.array(l.picklist(Object.values(zt)))),githubAccess:l.optional(l.object({username:l.optional(l.string()),teamAccess:l.optional(l.array(l.string())),repoAccess:l.optional(l.array(l.string()))}))});function vl(t){return l.safeParse(br,t)}function yl(t){return l.safeParse(Yt,t)}function El(t){return l.safeParse(Ir,t)}function bl(){let t={authUser:l.safeParse(br,{}),userSubscription:l.safeParse(Yt,{}),customClaims:l.safeParse(Ir,{}),getUserAuthStatus:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1))}),{}),getCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.optional(l.array(l.string()))}),{}),setCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claims:l.record(l.string(),l.any()),merge:l.optional(l.boolean(),!1)}),{}),removeCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.pipe(l.array(l.string()),l.minLength(1))}),{})};return{success:Object.values(t).every(e=>e.success),results:t}}var Tl={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Sl(t){return{userId:t,role:"user",preferences:{},metadata:{}}}var S={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},oe={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},k={CLIENT:"client",SERVER:"server",BUILD:"build"},N={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},Ve={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},kl={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},xl={USER:"user",GLOBAL:"global",SESSION:"session"},Ol={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},Dl={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},Nl={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var Ul={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},Ml={TRUE:!0,FALSE:!1,ADMIN:"admin",CREATE_ONLY:"create-only"},Xt={create:"admin",read:"guest",update:"admin",delete:"admin"},se={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},Fl={ASC:"asc",DESC:"desc"},Vl={LIST:"list",LIST_CARD:"listCard"},Bl=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var Wl={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},Gl={EQ:se.EQ,NEQ:se.NEQ,LT:se.LT,LTE:se.LTE,GT:se.GT,GTE:se.GTE};import*as h from"valibot";var ft=/^[0-9a-zA-Z]+$/,Xl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),data:h.record(h.string(),h.unknown()),idempotencyKey:h.optional(h.string())}),Jl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),Ql=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required")),data:h.record(h.string(),h.unknown()),merge:h.optional(h.boolean(),!1)}),Zl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),ed=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),limit:h.optional(h.pipe(h.number(),h.minValue(1),h.maxValue(1e3)),50),offset:h.optional(h.pipe(h.number(),h.minValue(0)),0),orderBy:h.optional(h.string()),orderDirection:h.optional(h.picklist(["asc","desc"]),"desc"),where:h.optional(h.array(h.object({field:h.string(),operator:h.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:h.unknown()})))});var Be={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},ud={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},ht={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Jt={[Be.PERMISSION_DENIED]:{type:ht.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[Be.NOT_FOUND]:{type:ht.NOT_FOUND,message:"The requested resource was not found"},[Be.ALREADY_EXISTS]:{type:ht.ALREADY_EXISTS,message:"The resource already exists"},[Be.INVALID_ARGUMENT]:{type:ht.VALIDATION_ERROR,message:"Invalid argument provided"}},Tr=class extends Error{type;originalError;constructor(e,n,r){super(n),this.name="EntityHookError",this.type=e,this.originalError=r}},ld={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"},w=class t extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(e,n=Be.INTERNAL,r){super(e),Object.setPrototypeOf(this,t.prototype),this.code=n,this.details=r?.details,this.source=r?.source,this.originalError=r?.originalError,this.context=r?.context,this.displayable=r?.displayable??!0,this.userMessageProvided=r?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var hd={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var gd={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var yd={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var bd={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var Td={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var Qt={mobile:0,tablet:768,laptop:1024,desktop:1440},To={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function So(t){return t>=Qt.desktop?"desktop":t>=Qt.laptop?"laptop":t>=Qt.tablet?"tablet":"mobile"}function Ld(t,e){let n=To[e];return t>=n.min&&t<=n.max}function Ud(t,e){let n=So(t);return{current:n,width:t,height:e,isMobile:n==="mobile",isTablet:n==="tablet",isLaptop:n==="laptop",isDesktop:n==="desktop",isMobileOrTablet:n==="mobile"||n==="tablet",isLaptopOrDesktop:n==="laptop"||n==="desktop"}}var Fd="landing",Vd={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var Sr=["pull","push","admin","maintain","triage"];import"valibot";import*as f from"valibot";var Zt=f.object({owner:f.pipe(f.string(),f.minLength(1,"Repository owner is required")),repo:f.pipe(f.string(),f.minLength(1,"Repository name is required"))}),Ao=f.picklist([...Sr]),Yd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Zt,permission:f.optional(Ao,"push"),customClaims:f.optional(f.record(f.string(),f.any()))}),Xd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Zt}),Jd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Zt}),Qd=f.object({provider:f.string(),purpose:f.picklist(["authentication","api-access"]),code:f.pipe(f.string(),f.minLength(1,"Authorization code is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required")),codeVerifier:f.optional(f.string()),state:f.optional(f.string()),instance:f.optional(f.pipe(f.string(),f.url()))}),Zd=f.object({provider:f.string(),refreshToken:f.pipe(f.string(),f.minLength(1,"Refresh token is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required"))}),ep=f.object({provider:f.string()}),tp=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required"))});var ap={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as g from"valibot";var Ar=g.object({name:g.string(),color:g.string(),icon:g.string(),customParameters:g.optional(g.record(g.string(),g.string())),button:g.object({backgroundColor:g.string(),textColor:g.string(),borderColor:g.string(),hoverBackgroundColor:g.string(),focusOutlineColor:g.string(),fontWeight:g.optional(g.string(),"500"),textKey:g.optional(g.string())})}),Co=g.object({...Ar.entries,type:g.picklist(["auth","both"]),scopes:g.optional(g.array(g.string())),firebaseProviderId:g.optional(g.string())}),mt=g.union([g.literal(""),g.pipe(g.string(),g.url())]),_o=g.object({authUrl:mt,tokenUrl:mt,profileUrl:mt,revokeUrl:g.optional(mt)}),wo=g.object({authentication:g.optional(g.array(g.string())),"api-access":g.array(g.string())}),Ro=g.optional(g.object({pkce:g.optional(g.boolean(),!1),codeChallengeMethod:g.optional(g.picklist(["S256","plain"]),"S256")})),Po=g.object({...Ar.entries,type:g.picklist(["oauth","both"]),scopes:wo,endpoints:_o,capabilities:Ro}),ye={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},en={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},ko=g.record(g.string(),Co),xo=g.record(g.string(),Po);function up(){return g.safeParse(ko,ye)}function lp(){return g.safeParse(xo,en)}function Oo(t){return t in ye}function Do(t){return t in en}var Cr={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},bp={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Ip={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:Cr.ANALYTICS},marketing:{requiresConsent:Cr.MARKETING}};function tn(t){return t instanceof Error&&"source"in t&&typeof t.source=="string"?t.source:typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&t.code.startsWith("auth/")?"auth":typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&t.code.startsWith("oauth/")?"oauth":typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(t.code)?"firebase":typeof t=="object"&&t!==null&&"issues"in t&&Array.isArray(t.issues)&&"name"in t&&t.name==="ValiError"?"validation":t instanceof Error&&t.name==="EntityHookError"?"entity":typeof t=="object"&&t!==null&&("response"in t||"status"in t||"statusText"in t)?"api":typeof t=="object"&&t!==null&&"componentStack"in t?"ui":"unknown"}import*as wr from"valibot";function $(t){return(e,n)=>{if(e instanceof w)return e;if(typeof e!="object"||e===null){let c=typeof e=="string"?e:t.defaultErrorMessage;return new w(n||c,t.defaultErrorCode,{details:{originalError:e},source:t.errorSource})}let r;t.extractErrorCode?r=t.extractErrorCode(e):"code"in e&&typeof e.code=="string"&&(r=e.code);let i=t.defaultErrorCode;r&&t.errorCodeMapping&&r in t.errorCodeMapping&&(i=t.errorCodeMapping[r]);let o;t.extractErrorMessage?o=t.extractErrorMessage(e):("message"in e&&typeof e.message=="string"||e instanceof Error)&&(o=e.message),r&&t.friendlyMessageMapping&&r in t.friendlyMessageMapping&&(o=t.friendlyMessageMapping[r]),o||(o=t.defaultErrorMessage);let s;return t.processMetadata?s=t.processMetadata(e):(s={originalError:e},r&&(s.originalCode=r)),"originalError"in s||(s.originalError=e),new w(n||o,i,{details:s,source:t.errorSource})}}var He={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"};var ae={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},No={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},nn={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},Z={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...He},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...He},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(No).map(([t,e])=>[t,e])),friendlyMessageMapping:{},extractErrorCode:t=>{if(typeof t!="object"||t===null)return;let e;return"response"in t&&t.response&&"status"in t.response?e=t.response.status:"status"in t&&typeof t.status=="number"&&(e=t.status),e?.toString()},processMetadata:t=>{let e={originalError:t};return typeof t!="object"||t===null||("response"in t&&t.response?("status"in t.response&&(e.statusCode=t.response.status),"data"in t.response&&(e.responseData=t.response.data)):"status"in t&&(e.statusCode=t.status)),e}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:He,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ae.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:t=>{let e={originalError:t};return typeof t=="object"&&t!==null&&"componentStack"in t&&(e.componentStack=t.componentStack),e}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:ae["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ae.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:t=>{if(t instanceof Error)return t.name}}},Lo=t=>t instanceof wr.ValiError?new w(ae["validation-failed"],"validation-failed",{details:{validationErrors:t.issues.map(e=>({path:e.path.join("."),message:e.message})),originalError:t},source:"validation"}):$(Z.validation)(t),Uo=t=>{if(t instanceof Error&&"type"in t&&typeof t.type=="string"&&t.type in nn){let e=t,n=nn[e.type]||"unknown";return new w(e.message||ae[n],n,{details:{originalError:t},source:"entity"})}if(typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&Jt[t.code]){let e=t,n=Jt[e.code];if(n){let r=nn[n.type]||"unknown";return new w(n.message||ae[r],r,{details:{originalCode:e.code,originalError:t},source:"entity"})}}return $(Z.entity)(t)},_r={auth:$(Z.auth),oauth:$(Z.oauth),api:$(Z.api),firebase:$(Z.firebase),ui:$(Z.ui),validation:Lo,entity:Uo,unknown:$(Z.unknown)};function ce(t,e,n){return t instanceof w?t:(_r[e]||_r.unknown)(t,n)}function rn(t,e,n={}){let r=globalThis.Sentry;r&&r.withScope(i=>{i.setTag("errorSource",e),i.setTag("errorCode",t.code),t.details&&Object.entries(t.details).forEach(([o,s])=>{if(typeof s!="function"&&o!=="originalError")try{i.setExtra(o,s)}catch{i.setExtra(o,`[${typeof s}]`)}}),Object.entries(n).forEach(([o,s])=>{if(typeof s!="function")try{i.setExtra(`context.${o}`,s)}catch{i.setExtra(`context.${o}`,`[${typeof s}]`)}}),(t.details?.userId||n.userId)&&i.setUser({id:t.details?.userId||n.userId,email:t.details?.userEmail||n.userEmail}),r.captureException(t)})}function Mo(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!0}function y(t,e){let n=typeof e=="string"?{userMessage:e}:e||{},{userMessage:r,context:i={},log:o=!0,reportToSentry:s=!0,showNotification:c=!1,severity:u="error"}=n,p=tn(t),m=t instanceof w?t:ce(t,p,r);if(r&&!m.userMessageProvided&&(m.message.includes("Error")||m.message.includes("Failed")||m.message.length<10?m=new w(r,m.code,{details:{...m.details,originalMessage:m.message},source:p,userMessageProvided:!0}):m=new w(m.message,m.code,{details:{...m.details,userMessage:r},source:p,userMessageProvided:!0})),o){let T=Mo()||typeof window<"u"&&window.__DNDEV_DEBUG,x={code:m.code,message:m.message,source:p};switch(u){case"warning":break;case"info":break;case"success":break;default:}}return s&&rn(m,p,i),m}function Fo(t,e){return async(...n)=>{try{return await t(...n)}catch(r){throw y(r,e)}}}function Vo(t,e="info",n){let r=Date.now().toString();return r}function Bo(t,e,n,r,i){let o=`${e}.${n}(${r}${i?`, ${i}`:""})`;return ce(t,"api",`${o}: ${on(t)}`)}function Ho(t,e,n,r){let i=`${e}.${n}(${r})`;return ce(t,"api",`${i}: ${on(t)}`)}function $o(t,e,n,r){let i=r?` ${JSON.stringify(r)}`:"",o=`${e}.${n}(${i})`,s=ce(t,"auth",`${o}: ${on(t)}`);return typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&s.code==="unknown"&&t.code!=="unknown"?new w(s.message,s.code,{details:{...s.details,originalCode:t.code},source:s.source}):s}function on(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t)}import*as $e from"valibot";function Wo(t,e,n){try{return $e.parse(t,e)}catch(r){throw r instanceof $e.ValiError?new w(`Validation failed in ${n}: ${r.message}`,"validation-failed",{details:{issues:r.issues,input:e},source:"validation"}):new w(`Unexpected validation error in ${n}: ${jo(r)}`,"validation-failed",{originalError:r instanceof Error?r:new Error(String(r)),source:"validation"})}}function Go(t,e){try{return $e.parse(t,e)}catch{return null}}function qo(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{value:t}}function jo(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t)}function Ko(t,e,n,r={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=r;return Array.from({length:n},(c,u)=>{let p=`${e}.${u}`;return t(p)}).filter((c,u)=>{let p=`${e}.${u}`;return!(c===p||o&&c.trim()===""||c.length<i||s&&!s(c,u))})}function zo(t,e,n,r){return Array.from({length:n},(i,o)=>{let s=`${e}.${o}.${String(r[0])}`;if(t(s)===s)return null;let u={};for(let p of r){let m=`${e}.${o}.${String(p)}`;u[p]=t(m)}return u}).filter(i=>i!==null)}function Yo(t,e,n,r,i={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:c}=i;return Array.from({length:r-n},(u,p)=>{let m=n+p,T=`${e}.${m}`;return t(T)}).filter((u,p)=>{let m=n+p,T=`${e}.${m}`;return!(u===T||s&&u.trim()===""||u.length<o||c&&!c(u,m))})}function Xo(t,e,n,r={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=r;return Array.from({length:n},(c,u)=>{let p=`${e}.${u}`;return{item:t(p),originalIndex:u}}).filter(({item:c,originalIndex:u})=>{let p=`${e}.${u}`;return!(c===p||o&&c.trim()===""||c.length<i||s&&!s(c,u))})}function Jo(t){let e=new Date().toISOString();return{_createdAt:e,_updatedAt:e,_createdBy:t,_updatedBy:t}}var sn={AED:{locale:"ar-AE",symbol:"\u062F.\u0625"},ARS:{locale:"es-AR",symbol:"$"},AUD:{locale:"en-AU",symbol:"$"},BDT:{locale:"bn-BD",symbol:"\u09F3"},BGN:{locale:"bg-BG",symbol:"\u043B\u0432"},BHD:{locale:"ar-BH",symbol:"\u062F.\u0628"},BRL:{locale:"pt-BR",symbol:"R$"},CAD:{locale:"en-CA",symbol:"$"},CHF:{locale:"fr-CH",symbol:"CHF"},CLP:{locale:"es-CL",symbol:"$"},CNY:{locale:"zh-CN",symbol:"\xA5"},COP:{locale:"es-CO",symbol:"$"},CZK:{locale:"cs-CZ",symbol:"K\u010D"},DKK:{locale:"da-DK",symbol:"kr"},EGP:{locale:"ar-EG",symbol:"E\xA3"},EUR:{locale:"fr-FR",symbol:"\u20AC"},GBP:{locale:"en-GB",symbol:"\xA3"},HKD:{locale:"zh-HK",symbol:"$"},HUF:{locale:"hu-HU",symbol:"Ft"},IDR:{locale:"id-ID",symbol:"Rp"},ILS:{locale:"he-IL",symbol:"\u20AA"},INR:{locale:"en-IN",symbol:"\u20B9"},JOD:{locale:"ar-JO",symbol:"\u062F.\u0623"},JPY:{locale:"ja-JP",symbol:"\xA5"},KES:{locale:"sw-KE",symbol:"KSh"},KRW:{locale:"ko-KR",symbol:"\u20A9"},KWD:{locale:"ar-KW",symbol:"\u062F.\u0643"},LKR:{locale:"si-LK",symbol:"Rs"},MXN:{locale:"es-MX",symbol:"$"},MYR:{locale:"ms-MY",symbol:"RM"},NGN:{locale:"en-NG",symbol:"\u20A6"},NOK:{locale:"nb-NO",symbol:"kr"},NZD:{locale:"en-NZ",symbol:"$"},OMR:{locale:"ar-OM",symbol:"\u0631.\u0639."},PEN:{locale:"es-PE",symbol:"S/."},PHP:{locale:"en-PH",symbol:"\u20B1"},PKR:{locale:"ur-PK",symbol:"\u20A8"},PLN:{locale:"pl-PL",symbol:"z\u0142"},QAR:{locale:"ar-QA",symbol:"\u0631.\u0642"},RON:{locale:"ro-RO",symbol:"lei"},RUB:{locale:"ru-RU",symbol:"\u20BD"},SAR:{locale:"ar-SA",symbol:"\u0631.\u0633"},SEK:{locale:"sv-SE",symbol:"kr"},SGD:{locale:"en-SG",symbol:"$"},THB:{locale:"th-TH",symbol:"\u0E3F"},TRY:{locale:"tr-TR",symbol:"\u20BA"},TWD:{locale:"zh-TW",symbol:"$"},UAH:{locale:"uk-UA",symbol:"\u20B4"},USD:{locale:"en-US",symbol:"$"},UYU:{locale:"es-UY",symbol:"$"},VND:{locale:"vi-VN",symbol:"\u20AB"},ZAR:{locale:"en-ZA",symbol:"R"}};function Rr(t){return sn[t]?.locale??"en-US"}function Qo(t){return!t||typeof t!="string"?t??"":sn[t]?.symbol??t}function Zo(t,e,n={}){if(t==null||isNaN(t))return"";let r=Rr(e);return new Intl.NumberFormat(r,{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:0,currencyDisplay:"symbol",...n}).format(t)}function an(t){let e=t.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!e||e.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${t}`);let n=e[1],r=e[2],i=e[3],o=e[4],s=e[5],c=new Date(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(o,10),parseInt(s,10));if(isNaN(c.getTime()))throw new Error(`Invalid date values in compact format: ${t}`);return c.toISOString()}function es(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let n=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),s=String(e.getUTCMinutes()).padStart(2,"0");return`${n}${r}${i}:${o}${s}`}function cn(t){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(t)}function ts(t){if(!t)return new Date().toISOString();if(t instanceof Date){if(isNaN(t.getTime()))throw new Error("Invalid Date object");return t.toISOString()}if(typeof t=="string"){if(cn(t))return an(t);let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid date string: ${t}`);return e.toISOString()}if(typeof t=="number"){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid timestamp: ${t}`);return e.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t){let e=t;if(typeof e.toDate=="function")return e.toDate().toISOString()}throw new Error(`Unsupported date type: ${typeof t}`)}function ns(){return new Date().toISOString()}function rs(t){return t.toISOString()}function is(t){return new Date(t).toISOString()}function os(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let n=new Date(e.getFullYear(),0,1),r=Math.floor((e.getTime()-n.getTime())/(1440*60*1e3));return`Week ${Math.ceil((r+n.getDay()+1)/7)}, ${e.getFullYear()}`}var U={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function ss(t,e="en",n={}){if(!t)return"";let{style:r="long",numeric:i="auto",fallbackThreshold:o=U.WEEK}=n,s;if(t instanceof Date)s=t;else if(typeof t=="string")s=new Date(t);else if(typeof t=="number")s=new Date(t);else if(typeof t=="object"&&"toDate"in t)s=t.toDate();else return"";if(isNaN(s.getTime()))return"";let c=new Date,u=s.getTime()-c.getTime(),p=Math.round(u/1e3),m=Math.abs(p);if(m>o)return Pr(s.toISOString(),e);let T=new Intl.RelativeTimeFormat(e,{style:r,numeric:i});return m<U.MINUTE?T.format(p,"second"):m<U.HOUR?T.format(Math.round(p/U.MINUTE),"minute"):m<U.DAY?T.format(Math.round(p/U.HOUR),"hour"):m<U.WEEK?T.format(Math.round(p/U.DAY),"day"):m<U.MONTH?T.format(Math.round(p/U.WEEK),"week"):m<U.YEAR?T.format(Math.round(p/U.MONTH),"month"):T.format(Math.round(p/U.YEAR),"year")}function as(t){switch(t){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function Pr(t,e="en",n="long"){if(!t)return"";let r;if(t instanceof Date)r=t;else if(typeof t=="string")r=new Date(t);else if(typeof t=="number")r=new Date(t);else if(typeof t=="object"&&"toDate"in t)r=t.toDate();else return"";if(isNaN(r.getTime()))return"";let i=typeof n=="string"?as(n):n;return new Intl.DateTimeFormat(e,i).format(r)}function un(t){if(t!=null){if(t instanceof Date)return isNaN(t.getTime())?void 0:t.toISOString();if(typeof t=="string"){let e=t.trim();if(!e)return;if(cn(e))try{return an(e)}catch{return}let n=new Date(e);return isNaN(n.getTime())?void 0:n.toISOString()}if(typeof t=="number"){if(!Number.isFinite(t))return;let e=new Date(t);return isNaN(e.getTime())?void 0:e.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t){let e=t;if(typeof e.toDate=="function")try{let n=e.toDate();return isNaN(n.getTime())?void 0:n.toISOString()}catch{return}}if(typeof t=="object"&&t!==null&&"seconds"in t&&typeof t.seconds=="number"){let e=t,n=e.seconds*1e3+(e.nanoseconds||0)/1e6,r=new Date(n);return isNaN(r.getTime())?void 0:r.toISOString()}}}function cs(t){let e=un(t);if(!e)return;let n=new Date(e);return n.setUTCHours(12,0,0,0),n.toISOString()}function us(t){let e=un(t);return e&&e.split("T")[0]||""}function ls(t){return typeof t=="string"?`'${t.replace(/'/g,"\\'")}'`:typeof t=="boolean"?t?"true":"false":String(t)}function ds(t){let e=`resource.data.${t.field}`,n=ls(t.value);return`${e} ${t.op} ${n}`}function ps(t){let e=[];if(t.publicCondition&&t.publicCondition.length>0){let n=t.publicCondition.map(ds).join(" && ");e.push(`(${n})`)}for(let n of t.ownerFields)e.push(`request.auth.uid == resource.data.${n}`);return e.length===0?"false":e.join(" || ")}function fs(t,e){return e?!e.includes(".")&&!e.includes(":")?e:t(e):""}function kr(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Or(t)}async function xr(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Or(new Uint8Array(r))}async function hs(){let t=kr(),e=await xr(t);return{codeVerifier:t,codeChallenge:e}}function Or(t){return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ms(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function gs(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}function vs(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}async function ys(t,e,n){try{return await t()}catch{return e(),!1}}var ln=new Map;function Es(t,e){if(ln.has(e))return ln.get(e);let n=t();return ln.set(e,n),n}var Dr={[O.GUEST]:0,[O.USER]:1,[O.ADMIN]:2,[O.SUPER]:3};function gt(t,e){if(!t)return!1;let n=Dr[t]??-1,r=Dr[e]??1/0;return n>=r}function bs(t){return t?t.role===O.SUPER||t.isSuper===!0?O.SUPER:t.role===O.ADMIN||t.isAdmin===!0?O.ADMIN:t.role===O.USER?O.USER:t.role||O.USER:O.USER}function Is(t,e,n){if(!t)return!1;let r=n??fr,i=r[t]?.level??-1,o=r[e]?.level??1/0;return i>=o}var Ee=null;function Ts(t){Ee=t}function Ss(t){if(!Ee)throw new Error(`[dndev] Provider "${t}" not available. Call configureProviders() at app startup.`);let e=Ee[t];if(!e)throw new Error(`[dndev] Provider "${t}" not configured. Pass it to configureProviders().`);return e}function As(t){return!!Ee?.[t]}function Cs(){Ee=null}function We(t,...e){let n=null,r=!1;return function(){if(n!==null)return n;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof t=="function"&&t.prototype?n=new t(...e):n=t(),n}finally{r=!1}}}function _s(t){let e=null,n=!1;return function(...i){if(e!==null)return e;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof t=="function"&&t.prototype?e=new t(...i):e=t(...i),e}finally{n=!1}}}function ws(t){let e=null,n=!1,r=null;return async function(){if(e!==null)return e;if(n&&r)return r;if(n)throw new Error("Circular dependency detected in async singleton initialization");n=!0;try{return r=t(),e=await r,e}finally{n=!1,r=null}}}function Rs(t,e){return new Proxy({},{get(n,r){if(e.includes(r)){let o=t(),s=o[r];return typeof s=="function"?s.bind(o):s}return t()[r]}})}var dn=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(e,n,r={}){if(this.instances.has(e))return this.instances.get(e);if(this.initialized.has(e))return this.instances.get(e);if(this.initializing.has(e))throw new Error(`Circular dependency detected for singleton: ${e}`);if(r.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u",r.fallbackFactory){let i=r.fallbackFactory();return this.instances.set(e,i),this.initialized.add(e),i}throw new Error(`Singleton ${e} requires client-side environment`)}this.initializing.add(e);try{let i=await n();return this.instances.set(e,i),this.initialized.add(e),i}catch(i){if(typeof process<"u",r.cacheFailures&&this.initialized.add(e),r.fallbackFactory){let o=r.fallbackFactory();return this.instances.set(e,o),this.initialized.add(e),o}throw i}finally{this.initializing.delete(e)}}static isInitialized(e){return this.initialized.has(e)}static clear(e){this.instances.delete(e),this.initialized.delete(e),this.initializing.delete(e)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};function Ps(t){return{_updatedAt:new Date().toISOString(),_updatedBy:t}}import"valibot";import"valibot";function ks(t){return typeof t=="object"&&t!==null&&"visibility"in t&&typeof t.visibility=="string"}function xs(t){if(ks(t))return t.visibility}function Nr(t,e){let n=t??"guest";return n==="hidden"?!1:n==="technical"?gt(e,"admin"):n==="owner"?!1:gt(e,n)}function Os(t,e,n){for(let r of n.ownerFields)if(t[r]===e)return!0;return!1}function pn(t,e,n){let r=t;if(!r||typeof r!="object"||!r.entries)return[];let i=r.entries,o=[],{documentData:s,uid:c,ownership:u}=n??{},p=u&&c!=null&&s&&Os(s,c,u);for(let[m,T]of Object.entries(i)){let x=xs(T);if(x==="owner"){p&&o.push(m);continue}Nr(x,e)&&o.push(m)}return o}function Ds(t,e,n,r){if(!t)return{};let i=r?.uid!=null&&r?.ownership!=null?{documentData:r.documentData??t,uid:r.uid,ownership:r.ownership}:void 0,o=pn(e,n,i),s={};for(let c of o)Object.prototype.hasOwnProperty.call(t,c)&&(s[c]=t[c]);return s}function Ge(t){let e=t.listCardFields;if(e){if(Array.isArray(e))return e;let n=e,r=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(r)]}return t.listFields&&t.listFields.length>0?t.listFields:t.fields?Object.keys(t.fields):[]}import"valibot";function vt(t){if(!(!t||typeof t!="object")){if(t.entries&&typeof t.entries=="object")return t.entries;if(Array.isArray(t.pipe))for(let e of t.pipe){let n=vt(e);if(n)return n}if(t.wrapped)return vt(t.wrapped);if(Array.isArray(t.options))for(let e of t.options){let n=vt(e);if(n)return n}}}function Ns(t){let e=vt(t);if(!e)return!1;for(let n of Object.values(e)){let r=n?.visibility;if(r!==void 0&&r!=="guest")return!0}return!1}var yt=class{store=new Map;maxAttempts;lockoutMs;sessionTimeoutMs;constructor(e={}){this.maxAttempts=e.maxAttempts??5,this.lockoutMs=e.lockoutMs??900*1e3,this.sessionTimeoutMs=e.sessionTimeoutMs??480*60*1e3}checkLockout(e){let n=this.store.get(e);if(n?.lockedUntil){if(Date.now()<n.lockedUntil){let r=Math.ceil((n.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${r} minute${r===1?"":"s"}.`)}this.store.delete(e)}}recordFailure(e){let n=Date.now();!this.store.has(e)&&this.store.size>=1e4&&this._evictExpired(n);let r=this.store.get(e)??{attempts:0,lastAttempt:0,lockedUntil:null};return r.attempts+=1,r.lastAttempt=n,r.attempts>=this.maxAttempts&&(r.lockedUntil=n+this.lockoutMs),this.store.set(e,r),{attempts:r.attempts,locked:r.lockedUntil!==null&&Date.now()<r.lockedUntil,lockedUntil:r.lockedUntil}}_evictExpired(e){for(let[n,r]of this.store)r.lockedUntil!==null&&e>r.lockedUntil?this.store.delete(n):r.lockedUntil===null&&e-r.lastAttempt>this.lockoutMs&&this.store.delete(n)}recordSuccess(e){this.store.delete(e)}isSessionExpired(e){return Date.now()-e>this.sessionTimeoutMs}getEntry(e){return this.store.get(e)}};function qe(t,e){let n=new Date(t),r=n.getDate();return n.setMonth(n.getMonth()+e),n.getDate()!==r&&n.setDate(0),n}function fn(t,e){let n=new Date(t),r=n.getDate();return n.setFullYear(n.getFullYear()+e),n.getDate()!==r&&n.setDate(0),n}function Ls(t,e=new Date){if(t==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return t==="1month"?n=qe(e,1):t==="3months"?n=qe(e,3):t==="6months"?n=qe(e,6):t==="1year"?n=fn(e,1):t==="2years"?n=fn(e,2):n=qe(e,1),n.toISOString()}function Us(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);return e}function Ms(t,e="URL"){try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol))throw new Error(`Invalid protocol: ${n.protocol}`);return t}catch(n){throw new Error(`Invalid ${e}: ${t}. ${n instanceof Error?n.message:"Invalid URL format"}`)}}function Fs(t){let e={};for(let[n,r]of Object.entries(t)){if(typeof r!="string")throw new Error(`Metadata value for key '${n}' must be a string, got ${typeof r}`);let i=r.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(i.length>1e3)throw new Error(`Metadata value for key '${n}' is too long (max 1000 characters)`);if(n.length>100)throw new Error(`Metadata key '${n}' is too long (max 100 characters)`);e[n]=i}return e}function Vs(t,e=!0){let n=process.env[t];if(e&&!n)throw new Error(`Required environment variable '${t}' is not set`);return n||""}function Bs(t,e){if(!t)return null;let n=`${encodeURIComponent(e)}=`,r=t.split(";");for(let i=0;i<r.length;i++){let o=r[i];if(o){for(;o.charAt(0)===" ";)o=o.substring(1,o.length);if(o.indexOf(n)===0)return decodeURIComponent(o.substring(n.length,o.length))}}return null}import"valibot";function Oh(t,e){let n=t;return n.metadata=e,n}import*as d from"valibot";var je=new Map;function v(t,e){je.set(t,e)}function Lh(t){return je.has(t)}function Uh(){return Array.from(je.keys())}function Mh(){je.clear()}function A(t,e){return e?t:d.nullish(t)}var Et=t=>{let e=[];t.validation?.minLength!==void 0&&e.push(d.minLength(t.validation.minLength,`Must be at least ${t.validation.minLength} characters`)),t.validation?.maxLength!==void 0&&e.push(d.maxLength(t.validation.maxLength,`Must be at most ${t.validation.maxLength} characters`)),t.validation?.pattern&&e.push(d.regex(new RegExp(t.validation.pattern),"Invalid format"));let n=e.length>0?d.pipe(d.string(),...e):d.string();return A(n,t.validation?.required)},Hs=t=>{let e=d.pipe(d.string(),d.email("Invalid email address"));return A(e,t.validation?.required)},$s=t=>{let e=t.validation?.minLength!==void 0?d.pipe(d.string(),d.minLength(t.validation.minLength,`Must be at least ${t.validation.minLength} characters`)):d.string();return A(e,t.validation?.required)},Ws=t=>{let e=d.pipe(d.string(),d.url("Invalid URL"));return A(e,t.validation?.required)},be=t=>{let e=[];t.validation?.min!==void 0&&e.push(d.minValue(t.validation.min,`Must be at least ${t.validation.min}`)),t.validation?.max!==void 0&&e.push(d.maxValue(t.validation.max,`Must be at most ${t.validation.max}`));let n=e.length>0?d.pipe(d.number(),...e):d.number();return A(n,t.validation?.required)},Ur=t=>{let e=d.boolean();return A(e,t.validation?.required)},Ie=t=>{let e=d.pipe(d.string(),d.isoTimestamp("Invalid date format"));return A(e,t.validation?.required)},Br=d.object({url:d.string(),filename:d.string(),size:d.number(),mimeType:d.nullish(d.string()),uploadedAt:d.nullish(d.string())}),Mr=t=>{let e=d.nullable(Br);return A(e,t.validation?.required)},Fr=t=>{let e=d.array(Br);return A(e,t.validation?.required)},Hr=d.object({fullUrl:d.string(),thumbUrl:d.string()}),Gs=t=>A(Hr,t.validation?.required),qs=t=>{let e=d.array(Hr);return A(e,t.validation?.required)},js=t=>{let e=d.object({lat:d.number(),lng:d.number()});return A(e,t.validation?.required)},Ks=t=>{let e=d.object({formatted_address:d.string(),latitude:d.number(),longitude:d.number(),street_number:d.nullish(d.string()),route:d.nullish(d.string()),locality:d.nullish(d.string()),administrative_area_level_1:d.nullish(d.string()),administrative_area_level_2:d.nullish(d.string()),country:d.nullish(d.string()),postal_code:d.nullish(d.string())});return A(e,t.validation?.required)},zs=t=>{let e=d.record(d.string(),d.unknown());return A(e,t.validation?.required)},Ys=t=>{let e=d.array(d.unknown());return A(e,t.validation?.required)},hn=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let r=e.map(o=>o.value),i=d.picklist(r);return A(i,t.validation?.required)}let n=d.union([d.string(),d.number()]);return A(n,t.validation?.required)},Xs=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let r=e.map(o=>o.value),i=d.array(d.picklist(r));return A(i,t.validation?.required)}let n=d.array(d.string());return A(n,t.validation?.required)},Js=t=>{let e=d.pipe(d.string(),d.regex(ft,"Invalid ID format"));return A(e,t.validation?.required)},mn=t=>{let e=d.string();return A(e,t.validation?.required)},Qs=t=>{let e=d.string();return A(e,t.validation?.required)},Zs=t=>{let e=t.validation?.minLength??15,n=t.validation?.maxLength??34,r=t.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",i=[];if(e!==void 0&&i.push(d.minLength(e,`IBAN must be at least ${e} characters`)),n!==void 0&&i.push(d.maxLength(n,`IBAN must not exceed ${n} characters`)),r){let s=typeof r=="string"?new RegExp(r):r;i.push(d.regex(s,"Invalid IBAN format"))}let o=i.length>0?d.pipe(d.string(),...i):d.string();return A(o,t.validation?.required)},Vr=()=>d.never(),ea=t=>{let e=t.options?.fieldSpecific;if(e?.checkedValue&&e?.uncheckedValue){let r=[e.checkedValue,e.uncheckedValue],i=d.picklist(r);return A(i,t.validation?.required)}let n=d.boolean();return A(n,t.validation?.required)},ta=t=>d.custom(n=>t.validation?.required?typeof n=="object"&&n!==null?n.gdprConsent===!0:!1:n===!1||n===null||n===void 0?!0:typeof n=="object"&&n!==null?n.gdprConsent===!0:!1,"GDPR consent must be given"),na=t=>{let e=d.object({amount:d.number(),currency:d.optional(d.string()),vatIncluded:d.optional(d.boolean()),discountPercent:d.optional(d.pipe(d.number(),d.minValue(0),d.maxValue(100)))});return A(e,t.validation?.required)};function ra(){v("text",Et),v("textarea",Et),v("richtext",Et),v("color",Et),v("email",Hs),v("password",$s),v("url",Ws),v("tel",Qs),v("iban",Zs),v("number",be),v("currency",be),v("price",na),v("range",be),v("year",be),v("rating",be),v("duration",be),v("boolean",Ur),v("checkbox",Ur),v("gdprConsent",ta),v("date",Ie),v("datetime-local",Ie),v("time",Ie),v("week",Ie),v("month",Ie),v("timestamp",Ie),v("file",Mr),v("files",Fr),v("document",Mr),v("documents",Fr),v("image",Gs),v("images",qs),v("geopoint",js),v("address",Ks),v("map",zs),v("array",Ys),v("select",hn),v("multiselect",Xs),v("radio",hn),v("combobox",hn),v("switch",ea),v("reference",Js),v("hidden",mn),v("avatar",mn),v("badge",mn),v("submit",Vr),v("reset",Vr)}ra();function Ke(t){if(t.validation?.schema){let r=t.validation.schema;return A(r,t.validation?.required)}let e=je.get(t.type);if(e){let r=e(t);if(r!==null)return r}let n=d.unknown();return A(n,t.validation?.required)}var ia={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};var $r=function(t){let e=[],n=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023),e[n++]=i>>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},oa=function(t){let e=[],n=0,r=0;for(;n<t.length;){let i=t[n++];if(i<128)e[r++]=String.fromCharCode(i);else if(i>191&&i<224){let o=t[n++];e[r++]=String.fromCharCode((i&31)<<6|o&63)}else if(i>239&&i<365){let o=t[n++],s=t[n++],c=t[n++],u=((i&7)<<18|(o&63)<<12|(s&63)<<6|c&63)-65536;e[r++]=String.fromCharCode(55296+(u>>10)),e[r++]=String.fromCharCode(56320+(u&1023))}else{let o=t[n++],s=t[n++];e[r++]=String.fromCharCode((i&15)<<12|(o&63)<<6|s&63)}}return e.join("")},Wr={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_();let n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let i=0;i<t.length;i+=3){let o=t[i],s=i+1<t.length,c=s?t[i+1]:0,u=i+2<t.length,p=u?t[i+2]:0,m=o>>2,T=(o&3)<<4|c>>4,x=(c&15)<<2|p>>6,H=p&63;u||(H=64,s||(x=64)),r.push(n[m],n[T],n[x],n[H])}return r.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray($r(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):oa(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();let n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let i=0;i<t.length;){let o=n[t.charAt(i++)],c=i<t.length?n[t.charAt(i)]:0;++i;let p=i<t.length?n[t.charAt(i)]:64;++i;let T=i<t.length?n[t.charAt(i)]:64;if(++i,o==null||c==null||p==null||T==null)throw new vn;let x=o<<2|c>>4;if(r.push(x),p!==64){let H=c<<4&240|p>>2;if(r.push(H),T!==64){let ie=p<<6&192|T;r.push(ie)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}},vn=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},sa=function(t){let e=$r(t);return Wr.encodeByteArray(e,!0)},En=function(t){return sa(t).replace(/\./g,"")},bn=function(t){try{return Wr.decodeString(t,!0)}catch{}return null};function In(t){try{return(t.startsWith("http://")||t.startsWith("https://")?new URL(t).hostname:t).endsWith(".cloudworkstations.dev")}catch{return!1}}function V(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function Gr(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(V())}function qr(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function jr(){let t=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof t=="object"&&t.id!==void 0}function Kr(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function zr(){try{return typeof indexedDB=="object"}catch{return!1}}function Yr(){return new Promise((t,e)=>{try{let n=!0,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=()=>{e(i.error?.message||"")}}catch(n){e(n)}})}var aa="FirebaseError",W=class t extends Error{constructor(e,n,r){super(n),this.code=e,this.customData=r,this.name=aa,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,X.prototype.create)}},X=class{constructor(e,n,r){this.service=e,this.serviceName=n,this.errors=r}create(e,...n){let r=n[0]||{},i=`${this.service}/${e}`,o=this.errors[e],s=o?ca(o,r):"Error",c=`${this.serviceName}: ${s} (${i}).`;return new W(i,c,r)}};function ca(t,e){return t.replace(ua,(n,r)=>{let i=e[r];return i!=null?String(i):`<${r}?>`})}var ua=/\{\$([^}]+)}/g;function bt(t){let e=[];for(let[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("&"):""}function Te(t){let e={};return t.replace(/^\?/,"").split("&").forEach(r=>{if(r){let[i,o]=r.split("=");e[decodeURIComponent(i)]=decodeURIComponent(o)}}),e}function Se(t){let e=t.indexOf("?");if(!e)return"";let n=t.indexOf("#",e);return t.substring(e,n>0?n:void 0)}function Xr(t,e){let n=new yn(t,e);return n.subscribe.bind(n)}var yn=class{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.");la(e,["next","error","complete"])?i=e:i={next:e,error:n,complete:r},i.next===void 0&&(i.next=gn),i.error===void 0&&(i.error=gn),i.complete===void 0&&(i.complete=gn);let o=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),o}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<this.observers.length;n++)this.sendOne(n,e)}sendOne(e,n){this.task.then(()=>{if(this.observers!==void 0&&this.observers[e]!==void 0)try{n(this.observers[e])}catch{}})}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 la(t,e){if(typeof t!="object"||t===null)return!1;for(let n of e)if(n in t&&typeof t[n]=="function")return!0;return!1}function gn(){}var $h=14400*1e3;function ze(t){return t&&t._delegate?t._delegate:t}ia.NODE_CLIENT=!0;var J=class{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}};var da=[],C;(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"})(C||(C={}));var pa={debug:C.DEBUG,verbose:C.VERBOSE,info:C.INFO,warn:C.WARN,error:C.ERROR,silent:C.SILENT},fa=C.INFO,ha={[C.DEBUG]:"log",[C.VERBOSE]:"log",[C.INFO]:"info",[C.WARN]:"warn",[C.ERROR]:"error"},ma=(t,e,...n)=>{if(e<t.logLevel)return;let r=new Date().toISOString(),i=ha[e];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},Ae=class{constructor(e){this.name=e,this._logLevel=fa,this._logHandler=ma,this._userLogHandler=null,da.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in C))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?pa[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,C.DEBUG,...e),this._logHandler(this,C.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,C.VERBOSE,...e),this._logHandler(this,C.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,C.INFO,...e),this._logHandler(this,C.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,C.WARN,...e),this._logHandler(this,C.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,C.ERROR,...e),this._logHandler(this,C.ERROR,...e)}};var ga=(t,e)=>e.some(n=>t instanceof n),Jr,Qr;function va(){return Jr||(Jr=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ya(){return Qr||(Qr=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Zr=new WeakMap,Sn=new WeakMap,ei=new WeakMap,Tn=new WeakMap,Cn=new WeakMap;function Ea(t){let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("success",o),t.removeEventListener("error",s)},o=()=>{n(G(t.result)),i()},s=()=>{r(t.error),i()};t.addEventListener("success",o),t.addEventListener("error",s)});return e.then(n=>{n instanceof IDBCursor&&Zr.set(n,t)}).catch(()=>{}),Cn.set(e,t),e}function ba(t){if(Sn.has(t))return;let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("complete",o),t.removeEventListener("error",s),t.removeEventListener("abort",s)},o=()=>{n(),i()},s=()=>{r(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",o),t.addEventListener("error",s),t.addEventListener("abort",s)});Sn.set(t,e)}var An={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return Sn.get(t);if(e==="objectStoreNames")return t.objectStoreNames||ei.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return G(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 ti(t){An=t(An)}function Ia(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){let r=t.call(It(this),e,...n);return ei.set(r,e.sort?e.sort():[e]),G(r)}:ya().includes(t)?function(...e){return t.apply(It(this),e),G(Zr.get(this))}:function(...e){return G(t.apply(It(this),e))}}function Ta(t){return typeof t=="function"?Ia(t):(t instanceof IDBTransaction&&ba(t),ga(t,va())?new Proxy(t,An):t)}function G(t){if(t instanceof IDBRequest)return Ea(t);if(Tn.has(t))return Tn.get(t);let e=Ta(t);return e!==t&&(Tn.set(t,e),Cn.set(e,t)),e}var It=t=>Cn.get(t);function ri(t,e,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){let s=indexedDB.open(t,e),c=G(s);return r&&s.addEventListener("upgradeneeded",u=>{r(G(s.result),u.oldVersion,u.newVersion,G(s.transaction),u)}),n&&s.addEventListener("blocked",u=>n(u.oldVersion,u.newVersion,u)),c.then(u=>{o&&u.addEventListener("close",()=>o()),i&&u.addEventListener("versionchange",p=>i(p.oldVersion,p.newVersion,p))}).catch(()=>{}),c}var Sa=["get","getKey","getAll","getAllKeys","count"],Aa=["put","add","delete","clear"],_n=new Map;function ni(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(_n.get(e))return _n.get(e);let n=e.replace(/FromIndex$/,""),r=e!==n,i=Aa.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||Sa.includes(n)))return;let o=async function(s,...c){let u=this.transaction(s,i?"readwrite":"readonly"),p=u.store;return r&&(p=p.index(c.shift())),(await Promise.all([p[n](...c),i&&u.done]))[0]};return _n.set(e,o),o}ti(t=>({...t,get:(e,n,r)=>ni(e,n)||t.get(e,n,r),has:(e,n)=>!!ni(e,n)||t.has(e,n)}));var Rn=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(n=>{if(_a(n)){let r=n.getImmediate();return`${r.library}/${r.version}`}else return null}).filter(n=>n).join(" ")}};function _a(t){return t.getComponent()?.type==="VERSION"}var Pn="@firebase/app",ii="0.14.8";var Q=new Ae("@firebase/app"),wa="@firebase/app-compat",Ra="@firebase/analytics-compat",Pa="@firebase/analytics",ka="@firebase/app-check-compat",xa="@firebase/app-check",Oa="@firebase/auth",Da="@firebase/auth-compat",Na="@firebase/database",La="@firebase/data-connect",Ua="@firebase/database-compat",Ma="@firebase/functions",Fa="@firebase/functions-compat",Va="@firebase/installations",Ba="@firebase/installations-compat",Ha="@firebase/messaging",$a="@firebase/messaging-compat",Wa="@firebase/performance",Ga="@firebase/performance-compat",qa="@firebase/remote-config",ja="@firebase/remote-config-compat",Ka="@firebase/storage",za="@firebase/storage-compat",Ya="@firebase/firestore",Xa="@firebase/ai",Ja="@firebase/firestore-compat",Qa="firebase",Za="12.9.0";var ec={[Pn]:"fire-core",[wa]:"fire-core-compat",[Pa]:"fire-analytics",[Ra]:"fire-analytics-compat",[xa]:"fire-app-check",[ka]:"fire-app-check-compat",[Oa]:"fire-auth",[Da]:"fire-auth-compat",[Na]:"fire-rtdb",[La]:"fire-data-connect",[Ua]:"fire-rtdb-compat",[Ma]:"fire-fn",[Fa]:"fire-fn-compat",[Va]:"fire-iid",[Ba]:"fire-iid-compat",[Ha]:"fire-fcm",[$a]:"fire-fcm-compat",[Wa]:"fire-perf",[Ga]:"fire-perf-compat",[qa]:"fire-rc",[ja]:"fire-rc-compat",[Ka]:"fire-gcs",[za]:"fire-gcs-compat",[Ya]:"fire-fst",[Ja]:"fire-fst-compat",[Xa]:"fire-vertex","fire-js":"fire-js",[Qa]:"fire-js-all"};var tc=new Map,nc=new Map,oi=new Map;function si(t,e){try{t.container.addComponent(e)}catch(n){Q.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n)}}function _e(t){let e=t.name;if(oi.has(e))return Q.debug(`There were multiple attempts to register component ${e}.`),!1;oi.set(e,t);for(let n of tc.values())si(n,t);for(let n of nc.values())si(n,t);return!0}function ue(t){return t==null?!1:t.settings!==void 0}var rc={"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."},On=new X("app","Firebase",rc);var Tt=Za;function Ce(t,e,n){let r=ec[t]??t;n&&(r+=`-${n}`);let i=r.match(/\s|\//),o=e.match(/\s|\//);if(i||o){let s=[`Unable to register library "${r}" with version "${e}":`];i&&s.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&o&&s.push("and"),o&&s.push(`version name "${e}" contains illegal characters (whitespace or "/")`),Q.warn(s.join(" "));return}_e(new J(`${r}-version`,()=>({library:r,version:e}),"VERSION"))}var ic="firebase-heartbeat-database",oc=1,Ye="firebase-heartbeat-store",wn=null;function li(){return wn||(wn=ri(ic,oc,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(Ye)}catch{}}}}).catch(t=>{throw On.create("idb-open",{originalErrorMessage:t.message})})),wn}async function sc(t){try{let n=(await li()).transaction(Ye),r=await n.objectStore(Ye).get(di(t));return await n.done,r}catch(e){if(e instanceof W)Q.warn(e.message);else{let n=On.create("idb-get",{originalErrorMessage:e?.message});Q.warn(n.message)}}}async function ai(t,e){try{let r=(await li()).transaction(Ye,"readwrite");await r.objectStore(Ye).put(e,di(t)),await r.done}catch(n){if(n instanceof W)Q.warn(n.message);else{let r=On.create("idb-set",{originalErrorMessage:n?.message});Q.warn(r.message)}}}function di(t){return`${t.name}!${t.options.appId}`}var ac=1024,cc=30,kn=class{constructor(e){this.container=e,this._heartbeatsCache=null;let n=this.container.getProvider("app").getImmediate();this._storage=new xn(n),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r))}async triggerHeartbeat(){try{let n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=ci();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(i=>i.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:n}),this._heartbeatsCache.heartbeats.length>cc){let i=lc(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(i,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(e){Q.warn(e)}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return"";let e=ci(),{heartbeatsToSend:n,unsentEntries:r}=uc(this._heartbeatsCache.heartbeats),i=En(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return Q.warn(e),""}}};function ci(){return new Date().toISOString().substring(0,10)}function uc(t,e=ac){let n=[],r=t.slice();for(let i of t){let o=n.find(s=>s.agent===i.agent);if(o){if(o.dates.push(i.date),ui(n)>e){o.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),ui(n)>e){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}var xn=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return zr()?Yr().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let n=await sc(this.app);return n?.heartbeats?n:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return ai(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return ai(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}else return}};function ui(t){return En(JSON.stringify({version:2,heartbeats:t})).length}function lc(t){if(t.length===0)return-1;let e=0,n=t[0].date;for(let r=1;r<t.length;r++)t[r].date<n&&(n=t[r].date,e=r);return e}function dc(t){_e(new J("platform-logger",e=>new Rn(e),"PRIVATE")),_e(new J("heartbeat",e=>new kn(e),"PRIVATE")),Ce(Pn,ii,t),Ce(Pn,ii,"esm2020"),Ce("fire-js","")}dc("");function bi(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}var Ii=bi,Ti=new X("auth","Firebase",bi());var wt=new Ae("@firebase/auth");function pc(t,...e){wt.logLevel<=C.WARN&&wt.warn(`Auth (${Tt}): ${t}`,...e)}function Ct(t,...e){wt.logLevel<=C.ERROR&&wt.error(`Auth (${Tt}): ${t}`,...e)}function we(t,...e){throw Jn(t,...e)}function Xn(t,...e){return Jn(t,...e)}function Si(t,e,n){let r={...Ii(),[e]:n};return new X("auth","Firebase",r).create(e,{appName:t.name})}function _t(t){return Si(t,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Jn(t,...e){if(typeof t!="string"){let n=e[0],r=[...e.slice(1)];return r[0]&&(r[0].appName=t.name),t._errorFactory.create(n,...r)}return Ti.create(t,...e)}function I(t,e,...n){if(!t)throw Jn(e,...n)}function q(t){let e="INTERNAL ASSERTION FAILED: "+t;throw Ct(e),new Error(e)}function Rt(t,e){t||q(e)}function fc(){return pi()==="http:"||pi()==="https:"}function pi(){return typeof self<"u"&&self.location?.protocol||null}function hc(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(fc()||jr()||"connection"in navigator)?navigator.onLine:!0}function mc(){if(typeof navigator>"u")return null;let t=navigator;return t.languages&&t.languages[0]||t.language||null}var Un=class{constructor(e,n){this.shortDelay=e,this.longDelay=n,Rt(n>e,"Short delay should be less than long delay!"),this.isMobile=Gr()||Kr()}get(){return hc()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}};function gc(t,e){Rt(t.emulator,"Emulator should always be set here");let{url:n}=t.emulator;return e?`${n}${e.startsWith("/")?e.slice(1):e}`:n}var Ze=class{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;q("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;q("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;q("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}};var vc={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"};var yc=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],Ec=new Un(3e4,6e4);function j(t,e){return t.tenantId&&!e.tenantId?{...e,tenantId:t.tenantId}:e}async function K(t,e,n,r,i={}){return Ai(t,i,async()=>{let o={},s={};r&&(e==="GET"?s=r:o={body:JSON.stringify(r)});let c=bt({key:t.config.apiKey,...s}).slice(1),u=await t._getAdditionalHeaders();u["Content-Type"]="application/json",t.languageCode&&(u["X-Firebase-Locale"]=t.languageCode);let p={method:e,headers:u,...o};return qr()||(p.referrerPolicy="no-referrer"),t.emulatorConfig&&In(t.emulatorConfig.host)&&(p.credentials="include"),Ze.fetch()(await Ci(t,t.config.apiHost,n,c),p)})}async function Ai(t,e,n){t._canInitEmulator=!1;let r={...vc,...e};try{let i=new Mn(t),o=await Promise.race([n(),i.promise]);i.clearNetworkTimeout();let s=await o.json();if("needConfirmation"in s)throw St(t,"account-exists-with-different-credential",s);if(o.ok&&!("errorMessage"in s))return s;{let c=o.ok?s.errorMessage:s.error.message,[u,p]=c.split(" : ");if(u==="FEDERATED_USER_ID_ALREADY_LINKED")throw St(t,"credential-already-in-use",s);if(u==="EMAIL_EXISTS")throw St(t,"email-already-in-use",s);if(u==="USER_DISABLED")throw St(t,"user-disabled",s);let m=r[u]||u.toLowerCase().replace(/[_\s]+/g,"-");if(p)throw Si(t,m,p);we(t,m)}}catch(i){if(i instanceof W)throw i;we(t,"network-request-failed",{message:String(i)})}}async function Vt(t,e,n,r,i={}){let o=await K(t,e,n,r,i);return"mfaPendingCredential"in o&&we(t,"multi-factor-auth-required",{_serverResponse:o}),o}async function Ci(t,e,n,r){let i=`${e}${n}?${r}`,o=t,s=o.config.emulator?gc(t.config,i):`${t.config.apiScheme}://${i}`;return yc.includes(n)&&(await o._persistenceManagerAvailable,o._getPersistenceType()==="COOKIE")?o._getPersistence()._getFinalTarget(s).toString():s}function bc(t){switch(t){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}var Mn=class{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((n,r)=>{this.timer=setTimeout(()=>r(Xn(this.auth,"network-request-failed")),Ec.get())})}};function St(t,e,n){let r={appName:t.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);let i=Xn(t,e,r);return i.customData._tokenResponse=n,i}function fi(t){return t!==void 0&&t.enterprise!==void 0}var Fn=class{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],e.recaptchaKey===void 0)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0)return null;for(let n of this.recaptchaEnforcementState)if(n.provider&&n.provider===e)return bc(n.enforcementState);return null}isProviderEnabled(e){return this.getProviderEnforcementState(e)==="ENFORCE"||this.getProviderEnforcementState(e)==="AUDIT"}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}};async function Ic(t,e){return K(t,"GET","/v2/recaptchaConfig",j(t,e))}async function Tc(t,e){return K(t,"POST","/v1/accounts:delete",e)}async function Pt(t,e){return K(t,"POST","/v1/accounts:lookup",e)}function Je(t){if(t)try{let e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function _i(t,e=!1){let n=ze(t),r=await n.getIdToken(e),i=wi(r);I(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");let o=typeof i.firebase=="object"?i.firebase:void 0,s=o?.sign_in_provider;return{claims:i,token:r,authTime:Je(Dn(i.auth_time)),issuedAtTime:Je(Dn(i.iat)),expirationTime:Je(Dn(i.exp)),signInProvider:s||null,signInSecondFactor:o?.sign_in_second_factor||null}}function Dn(t){return Number(t)*1e3}function wi(t){let[e,n,r]=t.split(".");if(e===void 0||n===void 0||r===void 0)return Ct("JWT malformed, contained fewer than 3 sections"),null;try{let i=bn(n);return i?JSON.parse(i):(Ct("Failed to decode base64 JWT payload"),null)}catch(i){return Ct("Caught error parsing JWT payload as JSON",i?.toString()),null}}function hi(t){let e=wi(t);return I(e,"internal-error"),I(typeof e.exp<"u","internal-error"),I(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}async function Vn(t,e,n=!1){if(n)return e;try{return await e}catch(r){throw r instanceof W&&Sc(r)&&t.auth.currentUser===t&&await t.auth.signOut(),r}}function Sc({code:t}){return t==="auth/user-disabled"||t==="auth/user-token-expired"}var Bn=class{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){if(e){let n=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),n}else{this.errorBackoff=3e4;let r=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,r)}}schedule(e=!1){if(!this.isRunning)return;let n=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},n)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}};var et=class{constructor(e,n){this.createdAt=e,this.lastLoginAt=n,this._initializeTime()}_initializeTime(){this.lastSignInTime=Je(this.lastLoginAt),this.creationTime=Je(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}};async function kt(t){let e=t.auth,n=await t.getIdToken(),r=await Vn(t,Pt(e,{idToken:n}));I(r?.users.length,e,"internal-error");let i=r.users[0];t._notifyReloadListener(i);let o=i.providerUserInfo?.length?Pi(i.providerUserInfo):[],s=Ac(t.providerData,o),c=t.isAnonymous,u=!(t.email&&i.passwordHash)&&!s?.length,p=c?u:!1,m={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 et(i.createdAt,i.lastLoginAt),isAnonymous:p};Object.assign(t,m)}async function Ri(t){let e=ze(t);await kt(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function Ac(t,e){return[...t.filter(r=>!e.some(i=>i.providerId===r.providerId)),...e]}function Pi(t){return t.map(({providerId:e,...n})=>({providerId:e,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}))}async function Cc(t,e){let n=await Ai(t,{},async()=>{let r=bt({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:i,apiKey:o}=t.config,s=await Ci(t,i,"/v1/token",`key=${o}`),c=await t._getAdditionalHeaders();c["Content-Type"]="application/x-www-form-urlencoded";let u={method:"POST",headers:c,body:r};return t.emulatorConfig&&In(t.emulatorConfig.host)&&(u.credentials="include"),Ze.fetch()(s,u)});return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function _c(t,e){return K(t,"POST","/v2/accounts:revokeToken",j(t,e))}var Qe=class t{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){I(e.idToken,"internal-error"),I(typeof e.idToken<"u","internal-error"),I(typeof e.refreshToken<"u","internal-error");let n="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):hi(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}updateFromIdToken(e){I(e.length!==0,"internal-error");let n=hi(e);this.updateTokensAndExpiration(e,null,n)}async getToken(e,n=!1){return!n&&this.accessToken&&!this.isExpired?this.accessToken:(I(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){let{accessToken:r,refreshToken:i,expiresIn:o}=await Cc(e,n);this.updateTokensAndExpiration(r,i,Number(o))}updateTokensAndExpiration(e,n,r){this.refreshToken=n||null,this.accessToken=e||null,this.expirationTime=Date.now()+r*1e3}static fromJSON(e,n){let{refreshToken:r,accessToken:i,expirationTime:o}=n,s=new t;return r&&(I(typeof r=="string","internal-error",{appName:e}),s.refreshToken=r),i&&(I(typeof i=="string","internal-error",{appName:e}),s.accessToken=i),o&&(I(typeof o=="number","internal-error",{appName:e}),s.expirationTime=o),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new t,this.toJSON())}_performRefresh(){return q("not implemented")}};function ee(t,e){I(typeof t=="string"||typeof t>"u","internal-error",{appName:e})}var le=class t{constructor({uid:e,auth:n,stsTokenManager:r,...i}){this.providerId="firebase",this.proactiveRefresh=new Bn(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new et(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){let n=await Vn(this,this.stsTokenManager.getToken(this.auth,e));return I(n,this.auth,"internal-error"),this.accessToken!==n&&(this.accessToken=n,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),n}getIdTokenResult(e){return _i(this,e)}reload(){return Ri(this)}_assign(e){this!==e&&(I(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=>({...n})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let n=new t({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return n.metadata._copy(this.metadata),n}_onReload(e){I(!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 kt(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(ue(this.auth.app))return Promise.reject(_t(this.auth));let e=await this.getIdToken();return await Vn(this,Tc(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,n){let r=n.displayName??void 0,i=n.email??void 0,o=n.phoneNumber??void 0,s=n.photoURL??void 0,c=n.tenantId??void 0,u=n._redirectEventId??void 0,p=n.createdAt??void 0,m=n.lastLoginAt??void 0,{uid:T,emailVerified:x,isAnonymous:H,providerData:ie,stsTokenManager:dt}=n;I(T&&dt,e,"internal-error");let D=Qe.fromJSON(this.name,dt);I(typeof T=="string",e,"internal-error"),ee(r,e.name),ee(i,e.name),I(typeof x=="boolean",e,"internal-error"),I(typeof H=="boolean",e,"internal-error"),ee(o,e.name),ee(s,e.name),ee(c,e.name),ee(u,e.name),ee(p,e.name),ee(m,e.name);let P=new t({uid:T,auth:e,email:i,emailVerified:x,displayName:r,isAnonymous:H,photoURL:s,phoneNumber:o,tenantId:c,stsTokenManager:D,createdAt:p,lastLoginAt:m});return ie&&Array.isArray(ie)&&(P.providerData=ie.map(Y=>({...Y}))),u&&(P._redirectEventId=u),P}static async _fromIdTokenResponse(e,n,r=!1){let i=new Qe;i.updateFromServerResponse(n);let o=new t({uid:n.localId,auth:e,stsTokenManager:i,isAnonymous:r});return await kt(o),o}static async _fromGetAccountInfoResponse(e,n,r){let i=n.users[0];I(i.localId!==void 0,"internal-error");let o=i.providerUserInfo!==void 0?Pi(i.providerUserInfo):[],s=!(i.email&&i.passwordHash)&&!o?.length,c=new Qe;c.updateFromIdToken(r);let u=new t({uid:i.localId,auth:e,stsTokenManager:c,isAnonymous:s}),p={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:o,metadata:new et(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!o?.length};return Object.assign(u,p),u}};var mi=new Map;function de(t){Rt(t instanceof Function,"Expected a class definition");let e=mi.get(t);return e?(Rt(e instanceof t,"Instance stored in cache mismatched with class"),e):(e=new t,mi.set(t,e),e)}var xt=class{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,n){this.storage[e]=n}async _get(e){let n=this.storage[e];return n===void 0?null:n}async _remove(e){delete this.storage[e]}_addListener(e,n){}_removeListener(e,n){}};xt.type="NONE";var Hn=xt;function Nn(t,e,n){return`firebase:${t}:${e}:${n}`}var Ot=class t{constructor(e,n,r){this.persistence=e,this.auth=n,this.userKey=r;let{config:i,name:o}=this.auth;this.fullUserKey=Nn(this.userKey,i.apiKey,o),this.fullPersistenceKey=Nn("persistence",i.apiKey,o),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(){let e=await this.persistence._get(this.fullUserKey);if(!e)return null;if(typeof e=="string"){let n=await Pt(this.auth,{idToken:e}).catch(()=>{});return n?le._fromGetAccountInfoResponse(this.auth,n,e):null}return le._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;let 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 t(de(Hn),e,r);let i=(await Promise.all(n.map(async p=>{if(await p._isAvailable())return p}))).filter(p=>p),o=i[0]||de(Hn),s=Nn(r,e.config.apiKey,e.name),c=null;for(let p of n)try{let m=await p._get(s);if(m){let T;if(typeof m=="string"){let x=await Pt(e,{idToken:m}).catch(()=>{});if(!x)break;T=await le._fromGetAccountInfoResponse(e,x,m)}else T=le._fromJSON(e,m);p!==o&&(c=T),o=p;break}}catch{}let u=i.filter(p=>p._shouldAllowMigration);return!o._shouldAllowMigration||!u.length?new t(o,e,r):(o=u[0],c&&await o._set(s,c.toJSON()),await Promise.all(n.map(async p=>{if(p!==o)try{await p._remove(s)}catch{}})),new t(o,e,r))}};function gi(t){let e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(kc(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(wc(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(Oc(e))return"Blackberry";if(Dc(e))return"Webos";if(Rc(e))return"Safari";if((e.includes("chrome/")||Pc(e))&&!e.includes("edge/"))return"Chrome";if(xc(e))return"Android";{let n=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=t.match(n);if(r?.length===2)return r[1]}return"Other"}function wc(t=V()){return/firefox\//i.test(t)}function Rc(t=V()){let e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function Pc(t=V()){return/crios\//i.test(t)}function kc(t=V()){return/iemobile/i.test(t)}function xc(t=V()){return/android/i.test(t)}function Oc(t=V()){return/blackberry/i.test(t)}function Dc(t=V()){return/webos/i.test(t)}function ki(t,e=[]){let n;switch(t){case"Browser":n=gi(V());break;case"Worker":n=`${gi(V())}-${t}`;break;default:n=t}let r=e.length?e.join(","):"FirebaseCore-web";return`${n}/JsCore/${Tt}/${r}`}var $n=class{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,n){let r=o=>new Promise((s,c)=>{try{let u=e(o);s(u)}catch(u){c(u)}});r.onAbort=n,this.queue.push(r);let i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let n=[];try{for(let r of this.queue)await r(e),r.onAbort&&n.push(r.onAbort)}catch(r){n.reverse();for(let i of n)try{i()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:r?.message})}}};async function Nc(t,e={}){return K(t,"GET","/v2/passwordPolicy",j(t,e))}var Lc=6,Wn=class{constructor(e){let n=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=n.minPasswordLength??Lc,n.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=n.maxPasswordLength),n.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=n.containsLowercaseCharacter),n.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=n.containsUppercaseCharacter),n.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=n.containsNumericCharacter),n.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=n.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){let n={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,n),this.validatePasswordCharacterOptions(e,n),n.isValid&&(n.isValid=n.meetsMinPasswordLength??!0),n.isValid&&(n.isValid=n.meetsMaxPasswordLength??!0),n.isValid&&(n.isValid=n.containsLowercaseLetter??!0),n.isValid&&(n.isValid=n.containsUppercaseLetter??!0),n.isValid&&(n.isValid=n.containsNumericCharacter??!0),n.isValid&&(n.isValid=n.containsNonAlphanumericCharacter??!0),n}validatePasswordLengthOptions(e,n){let 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<e.length;i++)r=e.charAt(i),this.updatePasswordCharacterOptionsStatuses(n,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,n,r,i,o){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=o))}};var Dt=class{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 Nt(this),this.idTokenSubscription=new Nt(this),this.beforeStateQueue=new $n(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=Ti,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion,this._persistenceManagerAvailable=new Promise(o=>this._resolvePersistenceManagerAvailable=o)}_initializeWithPersistence(e,n){return n&&(this._popupRedirectResolver=de(n)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await Ot.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(n),this.lastNotifiedUid=this.currentUser?.uid||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;let 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{let n=await Pt(this,{idToken:e}),r=await le._fromGetAccountInfoResponse(this,n,e);await this.directlySetCurrentUser(r)}catch{await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(ue(this.app)){let o=this.app.settings.authIdToken;return o?new Promise(s=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(o).then(s,s))}):this.directlySetCurrentUser(null)}let n=await this.assertedPersistence.getCurrentUser(),r=n,i=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let o=this.redirectUser?._redirectEventId,s=r?._redirectEventId,c=await this.tryRedirectSignIn(e);(!o||o===s)&&c?.user&&(r=c.user,i=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(r)}catch(o){r=n,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(o))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return I(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}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 kt(e)}catch(n){if(n?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=mc()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(ue(this.app))return Promise.reject(_t(this));let n=e?ze(e):null;return n&&I(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&&I(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 ue(this.app)?Promise.reject(_t(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return ue(this.app)?Promise.reject(_t(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(de(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let 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(){let e=await Nc(this),n=new Wn(e);this.tenantId===null?this._projectPasswordPolicy=n:this._tenantPasswordPolicies[this.tenantId]=n}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new X("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{let r=this.onAuthStateChanged(()=>{r(),e()},n)}})}async revokeAccessToken(e){if(this.currentUser){let n=await this.currentUser.getIdToken(),r={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:n};this.tenantId!=null&&(r.tenantId=this.tenantId),await _c(this,r)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,n){let r=await this.getOrInitRedirectPersistenceManager(n);return e===null?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let n=e&&de(e)||this._popupRedirectResolver;I(n,this,"argument-error"),this.redirectPersistenceManager=await Ot.create(this,[de(n._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);let e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,n,r,i){if(this._deleted)return()=>{};let o=typeof n=="function"?n:n.next.bind(n),s=!1,c=this._isInitialized?Promise.resolve():this._initializationPromise;if(I(c,this,"internal-error"),c.then(()=>{s||o(this.currentUser)}),typeof n=="function"){let u=e.addObserver(n,r,i);return()=>{s=!0,u()}}else{let u=e.addObserver(n);return()=>{s=!0,u()}}}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 I(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=ki(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){let e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);let n=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();n&&(e["X-Firebase-Client"]=n);let r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(ue(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&pc(`Error while retrieving App Check token: ${e.error}`),e?.token}};function xi(t){return ze(t)}var Nt=class{constructor(e){this.auth=e,this.observer=null,this.addObserver=Xr(n=>this.observer=n)}get next(){return I(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}};var Oi={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function Uc(t){return Oi.loadJS(t)}function Mc(){return Oi.recaptchaEnterpriseScript}var Gn=class{constructor(){this.enterprise=new qn}ready(e){e()}execute(e,n){return Promise.resolve("token")}render(e,n){return""}},qn=class{ready(e){e()}execute(e,n){return Promise.resolve("token")}render(e,n){return""}},Fc="recaptcha-enterprise",Di="NO_RECAPTCHA",jn=class{constructor(e){this.type=Fc,this.auth=xi(e)}async verify(e="verify",n=!1){async function r(o){if(!n){if(o.tenantId==null&&o._agentRecaptchaConfig!=null)return o._agentRecaptchaConfig.siteKey;if(o.tenantId!=null&&o._tenantRecaptchaConfigs[o.tenantId]!==void 0)return o._tenantRecaptchaConfigs[o.tenantId].siteKey}return new Promise(async(s,c)=>{Ic(o,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(u=>{if(u.recaptchaKey===void 0)c(new Error("recaptcha Enterprise site key undefined"));else{let p=new Fn(u);return o.tenantId==null?o._agentRecaptchaConfig=p:o._tenantRecaptchaConfigs[o.tenantId]=p,s(p.siteKey)}}).catch(u=>{c(u)})})}function i(o,s,c){let u=window.grecaptcha;fi(u)?u.enterprise.ready(()=>{u.enterprise.execute(o,{action:e}).then(p=>{s(p)}).catch(()=>{s(Di)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new Gn().execute("siteKey",{action:"verify"}):new Promise((o,s)=>{r(this.auth).then(c=>{if(!n&&fi(window.grecaptcha))i(c,o,s);else{if(typeof window>"u"){s(new Error("RecaptchaVerifier is only supported in browser"));return}let u=Mc();u.length!==0&&(u+=c),Uc(u).then(()=>{i(c,o,s)}).catch(p=>{s(p)})}}).catch(c=>{s(c)})})}};async function Xe(t,e,n,r=!1,i=!1){let o=new jn(t),s;if(i)s=Di;else try{s=await o.verify(n)}catch{s=await o.verify(n,!0)}let c={...e};if(n==="mfaSmsEnrollment"||n==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in c){let u=c.phoneEnrollmentInfo.phoneNumber,p=c.phoneEnrollmentInfo.recaptchaToken;Object.assign(c,{phoneEnrollmentInfo:{phoneNumber:u,recaptchaToken:p,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in c){let u=c.phoneSignInInfo.recaptchaToken;Object.assign(c,{phoneSignInInfo:{recaptchaToken:u,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return c}return r?Object.assign(c,{captchaResp:s}):Object.assign(c,{captchaResponse:s}),Object.assign(c,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(c,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),c}async function vi(t,e,n,r,i){if(i==="EMAIL_PASSWORD_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){let o=await Xe(t,e,n,n==="getOobCode");return r(t,o)}else return r(t,e).catch(async o=>{if(o.code==="auth/missing-recaptcha-token"){let s=await Xe(t,e,n,n==="getOobCode");return r(t,s)}else return Promise.reject(o)});else if(i==="PHONE_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){let o=await Xe(t,e,n);return r(t,o).catch(async s=>{if(t._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")==="AUDIT"&&(s.code==="auth/missing-recaptcha-token"||s.code==="auth/invalid-app-credential")){let c=await Xe(t,e,n,!1,!0);return r(t,c)}return Promise.reject(s)})}else{let o=await Xe(t,e,n,!1,!0);return r(t,o)}else return Promise.reject(i+" provider is not supported.")}function Vc(t,e){let n=e?.persistence||[],r=(Array.isArray(n)?n:[n]).map(de);e?.errorMap&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(r,e?.popupRedirectResolver)}var tt=class{constructor(e,n){this.providerId=e,this.signInMethod=n}toJSON(){return q("not implemented")}_getIdTokenResponse(e){return q("not implemented")}_linkToIdToken(e,n){return q("not implemented")}_getReauthenticationResolver(e){return q("not implemented")}};async function Bc(t,e){return K(t,"POST","/v1/accounts:signUp",e)}async function Hc(t,e){return Vt(t,"POST","/v1/accounts:signInWithPassword",j(t,e))}async function $c(t,e){return Vt(t,"POST","/v1/accounts:signInWithEmailLink",j(t,e))}async function Wc(t,e){return Vt(t,"POST","/v1/accounts:signInWithEmailLink",j(t,e))}var nt=class t extends tt{constructor(e,n,r,i=null){super("password",r),this._email=e,this._password=n,this._tenantId=i}static _fromEmailAndPassword(e,n){return new t(e,n,"password")}static _fromEmailAndCode(e,n,r=null){return new t(e,n,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let n=typeof e=="string"?JSON.parse(e):e;if(n?.email&&n?.password){if(n.signInMethod==="password")return this._fromEmailAndPassword(n.email,n.password);if(n.signInMethod==="emailLink")return this._fromEmailAndCode(n.email,n.password,n.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":let n={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return vi(e,n,"signInWithPassword",Hc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return $c(e,{email:this._email,oobCode:this._password});default:we(e,"internal-error")}}async _linkToIdToken(e,n){switch(this.signInMethod){case"password":let r={idToken:n,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return vi(e,r,"signUpPassword",Bc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return Wc(e,{idToken:n,email:this._email,oobCode:this._password});default:we(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}};async function Ln(t,e){return Vt(t,"POST","/v1/accounts:signInWithIdp",j(t,e))}var Gc="http://localhost",pe=class t extends tt{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let n=new t(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):we("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){let n=typeof e=="string"?JSON.parse(e):e,{providerId:r,signInMethod:i,...o}=n;if(!r||!i)return null;let s=new t(r,i);return s.idToken=o.idToken||void 0,s.accessToken=o.accessToken||void 0,s.secret=o.secret,s.nonce=o.nonce,s.pendingToken=o.pendingToken||null,s}_getIdTokenResponse(e){let n=this.buildRequest();return Ln(e,n)}_linkToIdToken(e,n){let r=this.buildRequest();return r.idToken=n,Ln(e,r)}_getReauthenticationResolver(e){let n=this.buildRequest();return n.autoCreate=!1,Ln(e,n)}buildRequest(){let e={requestUri:Gc,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let 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=bt(n)}return e}};function qc(t){switch(t){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}function jc(t){let e=Te(Se(t)).link,n=e?Te(Se(e)).deep_link_id:null,r=Te(Se(t)).deep_link_id;return(r?Te(Se(r)).link:null)||r||n||e||t}var Lt=class t{constructor(e){let n=Te(Se(e)),r=n.apiKey??null,i=n.oobCode??null,o=qc(n.mode??null);I(r&&i&&o,"argument-error"),this.apiKey=r,this.operation=o,this.code=i,this.continueUrl=n.continueUrl??null,this.languageCode=n.lang??null,this.tenantId=n.tenantId??null}static parseLink(e){let n=jc(e);try{return new t(n)}catch{return null}}};var Re=class t{constructor(){this.providerId=t.PROVIDER_ID}static credential(e,n){return nt._fromEmailAndPassword(e,n)}static credentialWithLink(e,n){let r=Lt.parseLink(n);return I(r,"argument-error"),nt._fromEmailAndCode(e,r.code,r.tenantId)}};Re.PROVIDER_ID="password";Re.EMAIL_PASSWORD_SIGN_IN_METHOD="password";Re.EMAIL_LINK_SIGN_IN_METHOD="emailLink";var Kn=class{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}};var Pe=class extends Kn{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}};var ke=class t extends Pe{constructor(){super("facebook.com")}static credential(e){return pe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return t.credential(e.oauthAccessToken)}catch{return null}}};ke.FACEBOOK_SIGN_IN_METHOD="facebook.com";ke.PROVIDER_ID="facebook.com";var xe=class t extends Pe{constructor(){super("google.com"),this.addScope("profile")}static credential(e,n){return pe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:n})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthIdToken:n,oauthAccessToken:r}=e;if(!n&&!r)return null;try{return t.credential(n,r)}catch{return null}}};xe.GOOGLE_SIGN_IN_METHOD="google.com";xe.PROVIDER_ID="google.com";var Oe=class t extends Pe{constructor(){super("github.com")}static credential(e){return pe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return t.credential(e.oauthAccessToken)}catch{return null}}};Oe.GITHUB_SIGN_IN_METHOD="github.com";Oe.PROVIDER_ID="github.com";var De=class t extends Pe{constructor(){super("twitter.com")}static credential(e,n){return pe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:n})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthAccessToken:n,oauthTokenSecret:r}=e;if(!n||!r)return null;try{return t.credential(n,r)}catch{return null}}};De.TWITTER_SIGN_IN_METHOD="twitter.com";De.PROVIDER_ID="twitter.com";function Kc(t,e){return K(t,"POST","/v2/accounts/mfaEnrollment:start",j(t,e))}function zc(t,e){return K(t,"POST","/v2/accounts/mfaEnrollment:finalize",j(t,e))}var yi="@firebase/auth",Ei="1.12.0";var zn=class{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;let n=this.auth.onIdTokenChanged(r=>{e(r?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,n),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let n=this.internalListeners.get(e);n&&(this.internalListeners.delete(e),n(),this.updateProactiveRefresh())}assertAuthConfigured(){I(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}};function Yc(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 Xc(t){_e(new J("auth",(e,{options:n})=>{let r=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),o=e.getProvider("app-check-internal"),{apiKey:s,authDomain:c}=r.options;I(s&&!s.includes(":"),"invalid-api-key",{appName:r.name});let u={apiKey:s,authDomain:c,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:ki(t)},p=new Dt(r,i,o,u);return Vc(p,n),p},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,n,r)=>{e.getProvider("auth-internal").initialize()})),_e(new J("auth-internal",e=>{let n=xi(e.getProvider("auth").getImmediate());return(r=>new zn(r))(n)},"PRIVATE").setInstantiationMode("EXPLICIT")),Ce(yi,Ei,Yc(t)),Ce(yi,Ei,"esm2020")}Ze.initialize(fetch,Headers,Response);Xc("Node");var bm=Xn("operation-not-supported-in-this-environment");Dt.prototype.setPersistence=async()=>{};function Jc(t,e){return K(t,"POST","/v2/accounts/mfaSignIn:finalize",j(t,e))}var Yn=class{constructor(e){this.factorId=e}_process(e,n,r){switch(n.type){case"enroll":return this._finalizeEnroll(e,n.credential,r);case"signin":return this._finalizeSignIn(e,n.credential);default:return q("unexpected MultiFactorSessionType")}}},Ut=class{static assertionForEnrollment(e,n){return Mt._fromSecret(e,n)}static assertionForSignIn(e,n){return Mt._fromEnrollmentId(e,n)}static async generateSecret(e){let n=e;I(typeof n.user?.auth<"u","internal-error");let r=await Kc(n.user.auth,{idToken:n.credential,totpEnrollmentInfo:{}});return Ft._fromStartTotpMfaEnrollmentResponse(r,n.user.auth)}};Ut.FACTOR_ID="totp";var Mt=class t extends Yn{constructor(e,n,r){super("totp"),this.otp=e,this.enrollmentId=n,this.secret=r}static _fromSecret(e,n){return new t(n,void 0,e)}static _fromEnrollmentId(e,n){return new t(n,e)}async _finalizeEnroll(e,n,r){return I(typeof this.secret<"u",e,"argument-error"),zc(e,{idToken:n,displayName:r,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,n){I(this.enrollmentId!==void 0&&this.otp!==void 0,e,"argument-error");let r={verificationCode:this.otp};return Jc(e,{mfaPendingCredential:n,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:r})}},Ft=class t{constructor(e,n,r,i,o,s,c){this.sessionInfo=s,this.auth=c,this.secretKey=e,this.hashingAlgorithm=n,this.codeLength=r,this.codeIntervalSeconds=i,this.enrollmentCompletionDeadline=o}static _fromStartTotpMfaEnrollmentResponse(e,n){return new t(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,n)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,n){let r=!1;return(At(e)||At(n))&&(r=!0),r&&(At(e)&&(e=this.auth.currentUser?.email||"unknownuser"),At(n)&&(n=this.auth.name)),`otpauth://totp/${n}:${e}?secret=${this.secretKey}&issuer=${n}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}};function At(t){return typeof t>"u"||t?.length===0}import*as E from"valibot";function M(){return typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?globalThis._DNDEV_CONFIG_:null}var te=null;function ot(){return Li().platform}function Li(){if(te)return te;let t=M();if(t?.platform)return te={platform:t.platform,mode:t.mode,context:t.context,version:t.version,metadata:{detectedAt:t.timestamp}},te;let e=[];e.push(...Zc()),e.push(...eu()),e.push(...tu());let n=e.sort((r,i)=>i.confidence-r.confidence)[0];return!n||n.confidence<N.MINIMUM?(te={platform:S.UNKNOWN,mode:Ni(),context:nu(),metadata:{detectedAt:Date.now()}},te):(te={platform:n.platform,mode:Ni(),context:n.context,version:ru(n.platform),metadata:{...n.metadata,detectedAt:Date.now()}},te)}var rt=null,it=null;function Ui(){if(typeof globalThis<"u"&&globalThis.__NEXT_DATA__||typeof process<"u"&&process.env?.NEXT_RUNTIME)return it=!0,!0;if(it===!0)return!0;let t=M();if(t?.platform){let n=t.platform===S.NEXTJS;return n&&(it=!0),n}let e=ot()===S.NEXTJS;return e&&(it=!0),e}function Mi(){if(rt!==null)return rt;let t=M();if(t?.platform)return rt=t.platform===S.VITE,rt;let e=ot()===S.VITE;return rt=e,e}function F(){return typeof window<"u"&&typeof document<"u"}function Qn(){return typeof process<"u"&&!!process.versions?.node}function Zc(){let t=[];if(F()){globalThis.__vite_plugin_react_preamble_installed__&&t.push({platform:S.VITE,confidence:N.HIGH,context:k.CLIENT,metadata:{viteHmrPort:globalThis.__vite_hmr_port}});let e=M();e?.platform===S.VITE&&t.push({platform:S.VITE,confidence:N.HIGH,context:k.CLIENT}),e?.i18n?.mapping&&t.push({platform:S.VITE,confidence:N.MEDIUM,context:k.CLIENT}),typeof globalThis<"u"&&globalThis.import?.meta?.hot!==void 0&&t.push({platform:S.VITE,confidence:N.LOW,context:k.CLIENT})}return Qn()&&(process.env.VITE&&t.push({platform:S.VITE,confidence:N.MEDIUM,context:k.SERVER}),process.env.npm_lifecycle_event?.includes(S.VITE)&&t.push({platform:S.VITE,confidence:N.LOW,context:k.BUILD})),t}function eu(){let t=[];return Qn()&&(process.env.NEXT_RUNTIME&&t.push({platform:S.NEXTJS,confidence:N.HIGH,context:k.SERVER,metadata:{nextjsRuntime:process.env.NEXT_RUNTIME}}),process.env.__NEXT_PRIVATE_PREBUNDLED_REACT&&t.push({platform:S.NEXTJS,confidence:N.MEDIUM,context:k.SERVER}),process.env._DNDEV_CONFIG_&&t.push({platform:S.NEXTJS,confidence:N.LOW,context:k.SERVER})),F()&&(M()?.platform===S.NEXTJS&&t.push({platform:S.NEXTJS,confidence:N.HIGH,context:k.CLIENT}),globalThis.__NEXT_DATA__&&t.push({platform:S.NEXTJS,confidence:N.LOW,context:k.CLIENT})),t}function tu(){let t=[];try{typeof globalThis<"u"&&globalThis.expo?.Constants?.expoConfig&&t.push({platform:S.EXPO,confidence:N.HIGH,context:k.CLIENT})}catch{}try{typeof globalThis<"u"&&globalThis.Platform?.OS&&!F()&&t.push({platform:S.REACT_NATIVE,confidence:N.MEDIUM,context:k.CLIENT})}catch{}let e=M();return e?.platform===S.EXPO?t.push({platform:S.EXPO,confidence:N.HIGH,context:k.CLIENT}):e?.platform===S.REACT_NATIVE&&t.push({platform:S.REACT_NATIVE,confidence:N.HIGH,context:k.CLIENT}),t}function Ni(){let t;return typeof import.meta<"u"&&import.meta.env?.MODE?t=import.meta.env.MODE:typeof process<"u"&&(t="production"),t===oe.PRODUCTION?oe.PRODUCTION:t===oe.TEST?oe.TEST:oe.DEVELOPMENT}function nu(){return F()?k.CLIENT:Qn()?oe.PRODUCTION==="production"&&!process.env.NEXT_RUNTIME?k.BUILD:k.SERVER:k.CLIENT}function ru(t){if(!(typeof process>"u"))return t===S.VITE?process.env.VITE_APP_VERSION||process.env.VITE_VERSION||process.env.APP_VERSION:t===S.NEXTJS?process.env.NEXT_PUBLIC_APP_VERSION||process.env.NEXT_PUBLIC_VERSION||process.env.__NEXT_VERSION||process.env.APP_VERSION:process.env.APP_VERSION||process.env.VITE_APP_VERSION||process.env.NEXT_PUBLIC_APP_VERSION}function Fi(t){return t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function iu(t){let e,n=M();return n?.env&&typeof n.env=="object"&&(e=n.env[t]),e===void 0&&typeof import.meta<"u"&&import.meta.env&&(e=import.meta.env[t]),Fi(e)}function ou(t){let e=M(),n;return e?.env&&typeof e.env=="object"&&(n=e.env[t]),n===void 0&&typeof process<"u"&&process.env&&(n=process.env[t]),Fi(n)}function L(t,e){if(t==="NODE_ENV"||t==="VITE_NODE_ENV"||t==="NEXT_PUBLIC_NODE_ENV"||t==="MODE"||t==="DEV"||t==="PROD"){let s=M();if(s?.env?.MODE)return t==="DEV"?s.env.MODE==="development"?"true":"false":t==="PROD"?s.env.MODE==="production"?"true":"false":s.env.MODE;if(typeof import.meta<"u"&&import.meta.env){let c=import.meta.env;if(t==="MODE"&&c.MODE)return c.MODE;if(t==="DEV")return c.DEV?"true":"false";if(t==="PROD")return c.PROD?"true":"false"}if(typeof process<"u"){let c="production";return t==="DEV"?c==="development"?"true":"false":t==="PROD"?c==="production"?"true":"false":c}return t==="DEV"?"true":t==="PROD"?"false":"development"}let n=M()?.platform,r=e||n||(Mi()?"vite":Ui()?"nextjs":ot()),i=["MODE","DEV","PROD","SSR"],o;return r==="vite"?i.includes(t)||t.startsWith("VITE_")?o=t:o=`VITE_${t}`:r==="nextjs"?t.startsWith("NEXT_PUBLIC_")?o=t:o=`NEXT_PUBLIC_${t}`:o=t,r==="vite"?iu(o):r==="nextjs"?ou(o):void 0}function ne(){if(typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production"))return!0;let t=L("APP_ENV"),e=L("NODE_ENV");return(t||e||"development").toLowerCase()!=="production"}var Vi=E.object({name:E.string(),color:E.string(),icon:E.string(),button:E.object({backgroundColor:E.string(),textColor:E.string(),borderColor:E.string(),hoverBackgroundColor:E.string(),focusOutlineColor:E.string(),fontWeight:E.optional(E.string(),"500")})}),su=E.object({...Vi.entries,type:E.picklist(["auth","both"]),scopes:E.optional(E.array(E.string())),firebaseProviderId:E.optional(E.string())}),Bt=E.union([E.literal(""),E.pipe(E.string(),E.url())]),au=E.object({authUrl:Bt,tokenUrl:Bt,profileUrl:Bt,revokeUrl:E.optional(Bt)}),cu=E.object({authentication:E.optional(E.array(E.string())),"api-access":E.array(E.string())}),sv=E.object({...Vi.entries,type:E.picklist(["oauth","both"]),scopes:cu,endpoints:au}),st=null;function uu(){let t=[];for(let[e,n]of Object.entries(ye))E.safeParse(su,n).success?t.push(e):typeof window<"u"&&ne();return t}function Ht(){if(st!==null)return st;let t=L("AUTH_PARTNERS");if(!t)return st=[],st;let e=uu(),n=t.split(",").map(r=>r.trim().toLowerCase()).filter(r=>e.includes(r));return st=n,n}function at(t){return typeof t=="object"&&t!==null&&"currentUser"in t&&typeof t.currentUser=="object"&&t.currentUser!==null}var lu=12e4,Zn=class{refreshTimerId=null;refreshAttempts=0;refreshBuffer;maxRefreshAttempts;autoRefresh;authInstance;onTokenExpired;onFatalError;refreshCallback;tokenInfo={token:null,expiresAt:null,status:"not-initialized"};constructor(e=null,n={}){this.authInstance=e,this.refreshBuffer=n.refreshBufferMs??lu,this.maxRefreshAttempts=n.maxRefreshAttempts??3,this.autoRefresh=n.autoRefresh!==!1,this.onTokenExpired=n.onTokenExpired,this.onFatalError=n.onFatalError}initialize(e){this.clearRefreshTimer(),this.refreshAttempts=0;let n=this.calculateTokenStatus(e.expiresAt);this.tokenInfo={...e,status:n},this.autoRefresh&&e.expiresAt&&this.scheduleRefresh(e.expiresAt)}getTokenInfo(){return this.tokenInfo}reset(){this.clearRefreshTimer(),this.tokenInfo={token:null,expiresAt:null,status:"not-initialized"}}async forceRefresh(e){try{if(this.refreshCallback&&await this.refreshCallback()&&this.tokenInfo.token)return this.tokenInfo.token;if(e&&typeof e.getIdToken=="function"){let n=await e.getIdToken(!0),r=new Date(Date.now()+3600*1e3);return this.updateTokenInfo({token:n,expiresAt:r}),this.refreshAttempts=0,n}else if(e&&typeof e.getIdTokenResult=="function"){let n=await e.getIdTokenResult(!0),r=new Date(n.expirationTime);return this.updateTokenInfo({token:n.token,expiresAt:r}),this.refreshAttempts=0,n.token}if(at(this.authInstance)){let n=await this.authInstance.currentUser.getIdTokenResult(!0),r=new Date(n.expirationTime);return this.updateTokenInfo({token:n.token,expiresAt:r}),this.refreshAttempts=0,n.token}throw y(new Error("No valid refresh method available"),{userMessage:"Unable to refresh authentication token",severity:"warning",context:{component:"TokenManager"}})}catch(n){return this.handleError(n instanceof Error?n:new Error("Unknown error during token refresh")),null}}async getValidToken(){let{status:e,token:n}=this.tokenInfo;if(e==="valid")return n;if((e==="expiring-soon"||e==="expired")&&this.autoRefresh)try{if(this.refreshCallback&&await this.refreshCallback())return this.tokenInfo.token;if(at(this.authInstance))return await this.forceRefresh(this.authInstance.currentUser)}catch(r){this.handleError(r instanceof Error?r:new Error("Failed to refresh token"))}return e==="expired"||e==="not-initialized"||e==="error"?null:n}onRefreshNeeded(e){return this.refreshCallback=e,()=>{this.refreshCallback=void 0}}updateTokenInfo(e){let n={token:e.token??this.tokenInfo.token,expiresAt:e.expiresAt??this.tokenInfo.expiresAt,refreshToken:e.refreshToken??this.tokenInfo.refreshToken,idToken:e.idToken??this.tokenInfo.idToken},r=this.calculateTokenStatus(n.expiresAt);this.tokenInfo={...n,status:r},this.autoRefresh&&n.expiresAt&&this.scheduleRefresh(n.expiresAt)}calculateTokenStatus(e){if(!e)return this.tokenInfo.token?"valid":"not-initialized";let n=new Date;if(n>=e)return"expired";let r=new Date(e.getTime()-this.refreshBuffer);return n>=r?"expiring-soon":"valid"}scheduleRefresh(e){this.clearRefreshTimer();let n=new Date,r=e.getTime()-n.getTime()-this.refreshBuffer;if(r<=0){at(this.authInstance)&&this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)});return}this.refreshTimerId=setTimeout(()=>{at(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)}):this.refreshCallback&&this.refreshCallback().catch(i=>{this.handleRefreshError(i)})},r)}handleRefreshError(e){if(ne(),this.refreshAttempts++,this.refreshAttempts<=this.maxRefreshAttempts){let n=Math.min(1e3*Math.pow(2,this.refreshAttempts-1),3e4);ne(),setTimeout(()=>{at(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(r=>{this.handleRefreshError(r)}):this.refreshCallback&&this.refreshCallback().catch(r=>{this.handleRefreshError(r)})},n)}else this.tokenInfo={...this.tokenInfo,status:"error",error:e instanceof Error?e:new Error("Max token refresh attempts reached")},this.onTokenExpired&&this.onTokenExpired(),this.onFatalError&&this.onFatalError(e instanceof Error?e:new Error("Max token refresh attempts reached"))}handleError(e){ne(),this.tokenInfo={...this.tokenInfo,status:"error",error:e}}clearRefreshTimer(){this.refreshTimerId!==null&&(clearTimeout(this.refreshTimerId),this.refreshTimerId=null)}},Cv=We(Zn,null,{});var $t=class{buildKey(e,n,r,i=!1){let o="dndev";switch(n){case"user":if(!r){if(i)return null;throw y(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:e,scope:n}})}return`${o}:user:${r}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}};var fe=null,du="dndev-keys",ct="encryption-keys",Bi="main";async function Hi(){return new Promise((t,e)=>{let n=indexedDB.open(du,1);n.onupgradeneeded=()=>{n.result.createObjectStore(ct)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function pu(t){let e=await Hi();return new Promise((n,r)=>{let i=e.transaction(ct,"readwrite");i.objectStore(ct).put(t,Bi),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async function fu(){try{let t=await Hi();return new Promise((e,n)=>{let i=t.transaction(ct,"readonly").objectStore(ct).get(Bi);i.onsuccess=()=>e(i.result??null),i.onerror=()=>n(i.error)})}catch{return null}}async function hu(){try{return await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw y(t,{userMessage:"Failed to generate encryption key",context:{algorithm:"AES-GCM"}})}}async function $i(){if(fe)return fe;try{let t=await fu();return t?(fe=t,fe):(fe=await hu(),await pu(fe),fe)}catch(t){throw y(t,{userMessage:"Failed to get or create encryption key"})}}async function Wi(t){try{let e=await $i(),n=window.crypto.getRandomValues(new Uint8Array(12)),r=typeof t=="string"?t:JSON.stringify(t),o=new TextEncoder().encode(r),s=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,o),c=new Uint8Array(n.length+s.byteLength);return c.set(n,0),c.set(new Uint8Array(s),n.length),btoa(String.fromCharCode(...c))}catch(e){throw y(e,{userMessage:"Failed to encrypt data"})}}async function Gi(t){try{let e=await $i(),n=Uint8Array.from(atob(t),u=>u.charCodeAt(0)),r=n.slice(0,12),i=n.slice(12),o=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i),c=new TextDecoder().decode(o);try{return JSON.parse(c)}catch{return c}}catch(e){throw y(e,{userMessage:"Failed to decrypt data"})}}var re=class extends $t{userId=null;constructor(e=null){super(),this.userId=e}setUserId(e){this.userId=e}async get(e,n={}){let{scope:r="user",encryption:i=!1}=n,o=this.buildKey(e,r,this.userId,!0);if(!o)return null;try{if(!F())return null;let s=localStorage.getItem(o);if(!s)return null;let c=JSON.parse(s);if(c.expiresAt&&new Date(c.expiresAt)<new Date)return await this.remove(e),null;let u=c.value;return i&&typeof u=="string"&&(u=await Gi(u)),u}catch(s){throw y(s,{userMessage:"Failed to retrieve data from local storage",context:{key:e,options:n}})}}async set(e,n,r={}){let{scope:i="user",encryption:o=!1,expiry:s=0}=r,c=this.buildKey(e,i,this.userId,!0);if(c)try{let u=n;o&&(u=await Wi(n));let p=s>0?new Date(Date.now()+s*1e3).toISOString():null,m=JSON.stringify({value:u,expiresAt:p,createdAt:new Date().toISOString()});typeof window<"u"&&localStorage.setItem(c,m)}catch(u){let p=u?.name==="QuotaExceededError"||u?.code===22?"Storage quota exceeded. Please free up space or login to sync to cloud.":u?.name==="SecurityError"||u?.code===18?"Storage access denied. Please enable localStorage or login to sync to cloud.":"Failed to store data in local storage";throw y(u,{userMessage:p,context:{key:e,options:r}})}}async remove(e){let n=["user","global","session"];for(let r of n)try{let i=this.buildKey(e,r,this.userId,!0);if(!i)continue;typeof window<"u"&&localStorage.removeItem(i)}catch{}}async clear(e){if(!e){let s=(typeof window<"u"?Object.keys(localStorage):[]).filter(c=>c.startsWith("dndev:"));for(let c of s)typeof window<"u"&&localStorage.removeItem(c);return}let n=e==="user"&&this.userId?`dndev:user:${this.userId}:`:`dndev:${e}:`,i=(typeof window<"u"?Object.keys(localStorage):[]).filter(o=>o.startsWith(n));for(let o of i)typeof window<"u"&&localStorage.removeItem(o)}};var ut=class{localStrategy;userId;apiEndpoint;constructor(e,n="/api/storage"){if(!e)throw y("User ID is required for HybridStorageStrategy");this.userId=e,this.localStrategy=new re(e),this.apiEndpoint=n}async get(e,n={}){try{let r=await this.localStrategy.get(e,n);return r!==null?r:await this.getFromCloud(e,n)}catch(r){try{return await this.localStrategy.get(e,n)}catch(i){throw y(r,{userMessage:"Failed to retrieve data from storage",context:{key:e,options:n,fallbackError:i}})}}}async set(e,n,r={}){try{await this.localStrategy.set(e,n,r),this.setToCloud(e,n,r).catch(i=>{})}catch(i){throw y(i,{userMessage:"Failed to store data",context:{key:e,options:r}})}}async remove(e){try{await this.localStrategy.remove(e),this.removeFromCloud(e).catch(n=>{})}catch(n){throw y(n,{userMessage:"Failed to remove data",context:{key:e}})}}async clear(e){try{await this.localStrategy.clear(e),this.clearFromCloud(e).catch(n=>{})}catch(n){throw y(n,{userMessage:"Failed to clear storage",context:{scope:e}})}}buildKey(e,n,r,i=!1){let o="dndev";switch(n){case"user":if(!r){if(i)return null;throw y(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:e,scope:n}})}return`${o}:user:${r}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}async getFromCloud(e,n){try{let{scope:r="user"}=n,i=this.buildKey(e,r,this.userId,!0);if(!i)return null;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`);if(!o.ok){if(o.status===404)return null;throw y(new Error(`Cloud storage API error: ${o.status} ${o.statusText}`),{userMessage:"Failed to retrieve data from cloud storage",severity:"warning",context:{key:e,status:o.status}})}let s=await o.json();return s.expiresAt&&new Date(s.expiresAt)<new Date?(this.removeFromCloud(e).catch(console.warn),null):(this.localStrategy.set(e,s.value,n).catch(console.warn),s.value)}catch{return null}}async setToCloud(e,n,r){let{scope:i="user",expiry:o=0}=r,s=this.buildKey(e,i,this.userId,!0);if(!s)return;let c=o>0?new Date(Date.now()+o*1e3).toISOString():null,u={value:n,expiresAt:c,createdAt:new Date().toISOString()},p=await fetch(`${this.apiEndpoint}/${encodeURIComponent(s)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw y(new Error(`Cloud storage API error: ${p.status} ${p.statusText}`),{userMessage:"Failed to save data to cloud storage",severity:"error",context:{key:e,status:p.status}})}async removeFromCloud(e){let n=["user","global","session"];for(let r of n)try{let i=this.buildKey(e,r,this.userId,!0);if(!i)continue;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`,{method:"DELETE"});!o.ok&&o.status}catch{}}async clearFromCloud(e){try{let n=new URLSearchParams;e&&n.append("scope",e),e==="user"&&n.append("userId",this.userId);let r=n.toString(),i=r?`${this.apiEndpoint}/clear?${r}`:`${this.apiEndpoint}/clear`;(await fetch(i,{method:"DELETE"})).ok}catch{}}};var Wt=class{strategy;initialized=!1;userId=null;isPro=!1;constructor(e=new re){this.strategy=e}initialize(){if(!this.initialized)try{this.initialized=!0}catch{ne()}}setStrategy(e){this.initialize(),this.strategy=e}updateUser(e,n){this.initialize(),n&&e?this.strategy=new ut(e):this.strategy=new re(e)}updateStrategy(){this.isPro&&this.userId?this.strategy=new ut(this.userId):this.strategy=new re(this.userId)}async get(e,n={}){return this.initialize(),this.strategy.get(e,n)}async set(e,n,r={}){return this.initialize(),this.strategy.set(e,n,r)}async remove(e){return this.initialize(),this.strategy.remove(e)}async clear(e){return this.initialize(),this.strategy.clear(e)}async setSecure(e,n,r={}){return this.initialize(),this.set(e,n,{...r,encryption:!0})}async getSecure(e,n={}){return this.initialize(),this.get(e,{...n,encryption:!0})}},mu=We(Wt);var B={AUTH:"auth",OAUTH:"oauth",I18N:"i18n",BILLING:"billing",ROUTES:"routes",THEMES:"themes",COMPONENTS:"components",CRUD:"crud",FORMS:"forms",REALTIME:"realtime",STORAGE:"storage"};function he(t){return!!t&&t.trim()!==""}var oy={[B.AUTH]:()=>Ht().length>0,[B.OAUTH]:()=>["VITE_OAUTH_GOOGLE_CLIENT_ID","VITE_OAUTH_GITHUB_CLIENT_ID","VITE_OAUTH_FACEBOOK_CLIENT_ID","VITE_OAUTH_TWITTER_CLIENT_ID","VITE_OAUTH_LINKEDIN_CLIENT_ID","VITE_OAUTH_DISCORD_CLIENT_ID","VITE_OAUTH_SLACK_CLIENT_ID","VITE_OAUTH_MICROSOFT_CLIENT_ID","VITE_OAUTH_APPLE_CLIENT_ID"].some(e=>he(L(e))),[B.I18N]:()=>!0,[B.BILLING]:()=>!!(he(L("STRIPE_PUBLISHABLE_KEY"))||he(L("BILLING_ENABLED"))&&L("BILLING_ENABLED")==="true"),[B.ROUTES]:()=>!0,[B.THEMES]:()=>!0,[B.COMPONENTS]:()=>!0,[B.CRUD]:()=>!0,[B.FORMS]:()=>!0,[B.REALTIME]:()=>!!(he(L("REALTIME_ENABLED"))&&L("REALTIME_ENABLED")==="true"||he(L("FIREBASE_CONFIG"))),[B.STORAGE]:()=>!!(he(L("STORAGE_ENABLED"))&&L("STORAGE_ENABLED")==="true"||he(L("FIREBASE_CONFIG")))};var Ou=pr(ar(),1);var Du=pr(ar(),1);var cr=class{events=new Map;eventCache=new Map;maxListeners=10;cacheTTL=180*1e3;on(e,n,r){if(typeof n!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:n,once:!1,context:r};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,n)}}once(e,n,r){if(typeof n!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:n,once:!0,context:r};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,n)}}off(e,n){let r=this.events.get(e);if(!r||r.length===0)return!1;let i=r.findIndex(o=>o.handler===n);return i===-1?!1:(r.splice(i,1),r.length===0&&this.events.delete(e),!0)}emit(e,...n){this.cacheEvent(e,n);let r=this.events.get(e);if(!r||r.length===0)return!1;let i=[...r],o=[];for(let s of i)try{s.context?s.handler.apply(s.context,n):s.handler(...n),s.once&&o.push(s)}catch(c){y(c,{userMessage:`Error in event handler for ${e}`,context:{eventName:e,args:n},severity:"warning"})}if(o.length>0){let s=this.events.get(e);if(s){let c=s.filter(u=>!o.includes(u));c.length===0?this.events.delete(e):this.events.set(e,c)}}return!0}hasListeners(e){let n=this.events.get(e);return!!n&&n.length>0}listenerCount(e){return this.events.get(e)?.length||0}eventNames(){return Array.from(this.events.keys())}listeners(e){let n=this.events.get(e);return n?n.map(r=>r.handler):[]}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}setMaxListeners(e){return this.maxListeners=e>0?e:1/0,this}getMaxListeners(){return this.maxListeners}getListeners(e){let n=this.events.get(e);return n||(n=[],this.events.set(e,n)),n}checkListenerCount(e){let n=this.listenerCount(e);this.maxListeners!==1/0&&n>this.maxListeners}cacheEvent(e,n){let r=this.eventCache.get(e);r||(r=[],this.eventCache.set(e,r)),r.push({data:n,timestamp:Date.now()}),this.cleanupCache(e)}getCachedEvents(e){let n=this.eventCache.get(e);return!n||n.length===0?[]:(this.cleanupCache(e),(this.eventCache.get(e)||[]).map(i=>i.data))}clearCachedEvents(e){this.eventCache.delete(e)}clearAllCachedEvents(){this.eventCache.clear()}getCacheStats(){let e=0,n=null,r=null;for(let[o,s]of this.eventCache.entries()){e+=s.length;for(let c of s)(n===null||c.timestamp<n)&&(n=c.timestamp),(r===null||c.timestamp>r)&&(r=c.timestamp)}let i=`${Math.round(e*200/1024)}KB`;return{totalEvents:e,eventTypes:this.eventCache.size,oldestEvent:n,newestEvent:r,memoryEstimate:i}}cleanupCache(e){let n=Date.now()-this.cacheTTL;if(e){let r=this.eventCache.get(e);if(r){let i=r.filter(o=>o.timestamp>n);i.length===0?this.eventCache.delete(e):this.eventCache.set(e,i)}}else for(let[r,i]of this.eventCache.entries()){let o=i.filter(s=>s.timestamp>n);o.length===0?this.eventCache.delete(r):this.eventCache.set(r,o)}}},Wy=new cr;var Yy={user:null,userProfile:null,userSubscription:null,loading:!1,reauthenticateWithPassword:async()=>{},reauthenticateWithProvider:async()=>{},deleteAccount:async()=>{},error:null,emailVerification:{status:"pending"},getPartnerState:()=>"idle",setPartnerState:()=>{},partnerError:null,status:Ve.DEGRADED,hasRole:async()=>!1,hasTier:async()=>!1,hasFeature:async()=>!1,getCustomClaims:()=>({}),getCustomClaim:()=>null,signInWithEmail:async()=>null,createUserWithEmail:async()=>null,signInWithPartner:async()=>null,linkWithPartner:async()=>null,signInWithGoogleCredential:async()=>null,signOut:async()=>{},sendPasswordResetEmail:async()=>{},updatePassword:async()=>{},sendEmailVerification:async()=>{},getEmailVerificationStatus:async()=>({status:"pending"}),isEmailVerificationEnabled:async()=>!1,sendSignInLinkToEmail:async()=>{},signInWithEmailLink:async()=>null,isSignInWithEmailLink:()=>!1,getCurrentUser:async()=>null,isAuthenticated:!1,userRole:O.GUEST,userTier:Fe.FREE,can:{navigate:t=>t===!1||typeof t=="object"&&!t.required,view:()=>!1,edit:()=>!1,delete:()=>!1,create:()=>!1,perform:()=>!1,has:()=>!1},isAvailable:!1},Xy={status:Ve.DEGRADED,error:null,loading:!1,checkout:async()=>({sessionId:"",sessionUrl:null,success:!1,error:"Billing not available - consent required"}),cancelSubscription:async()=>({success:!1,endsAt:""}),changePlan:async()=>({success:!1}),refreshStatus:async()=>{},openCustomerPortal:async()=>{},clearError:()=>{},isAvailable:!1},Jy={status:Ve.DEGRADED,data:null,loading:!1,error:null,get:async()=>null,set:async()=>{},update:async()=>{},delete:async()=>{},add:async()=>"",query:async()=>[],subscribe:()=>()=>{},subscribeToCollection:()=>()=>{},invalidate:async()=>{},isAvailable:!1},Qy={status:Ve.DEGRADED,error:null,partners:{},connectedPartners:[],connect:async()=>{},disconnect:async()=>{},isConnected:()=>!1,getCredentials:()=>null,handleCallback:async()=>{},isAvailable:!1};var ro=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function io(t){return typeof t=="string"&&t.length>=19&&t.includes("-")&&t.includes(":")}function qt(t,e=""){if(Array.isArray(t))t.forEach((n,r)=>{let i=`${e}[${r}]`;if(typeof n=="string"&&io(n)){if(!ro.test(n))throw y(new Error(`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`),{userMessage:`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:i,value:n},severity:"error"})}else typeof n=="object"&&n!==null&&qt(n,i)});else if(typeof t=="object"&&t!==null)for(let[n,r]of Object.entries(t)){let i=e?`${e}.${n}`:n;if(typeof r=="string"&&io(r)){if(!ro.test(r))throw y(new Error(`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`),{userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:i,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&qt(r,i)}}import*as so from"valibot";var ur={};function OE(t){ur.uniqueConstraintValidator=t}async function oo(t,e,n){let{uniqueFields:r=[],collection:i}=t.metadata;r.length!==0&&ur.uniqueConstraintValidator&&await Promise.all(r.map(async({field:o,errorMessage:s})=>{let c=e[o];if(c==null)return;if(await ur.uniqueConstraintValidator.checkDuplicate(i,o,c,n))throw y(new Error(s||`${o} must be unique`),{userMessage:s||`${o} must be unique`,context:{field:o}})}))}async function UE(t,e,n,r){so.parse(t,e),qt(e),await oo(t,e,r),t.metadata.customValidate&&await t.metadata.customValidate(e,n)}function Nu(t){return t!=null&&typeof t=="object"&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null}function qE(t){if(!Nu(t)){let e=t,n=e&&typeof e=="object"&&"constructor"in e&&e.constructor&&e.constructor.name||"unknown";throw y(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:n}})}return t.metadata.collection}var lr=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],zE="available",YE=["draft","deleted"],Ue=["id","createdAt","updatedAt","createdById","updatedById"],Lu=[...Ue,"status"];function XE(t){return Lu.includes(t)}function JE(t){return Ue.includes(t)}var R={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...lr]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0,pattern:ft.source}},createdAt:{name:"_createdAt",type:"timestamp",visibility:"technical",label:"crud:fields._createdAt",validation:{required:!0}},updatedAt:{name:"_updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields._updatedAt",validation:{required:!0}},createdById:{name:"_createdById",type:"reference",visibility:"technical",label:"crud:fields._createdById",validation:{required:!0}},updatedById:{name:"_updatedById",type:"reference",visibility:"technical",label:"crud:fields._updatedById",validation:{required:!0}}};function Uu(t){let e=t.field.endsWith("Id")?t.field.slice(0,-2):t.field,n=t.collection||(e.endsWith("y")?e.slice(0,-1)+"ies":e+"s");return{name:t.field,label:`crud:fields.${t.field}`,type:"reference",visibility:"technical",editable:"create-only",validation:{required:!0,reference:n}}}function Mu(t,e){if(!e||e.length===0)return t.map(i=>({value:i.value,label:i.label}));let n=t.map(i=>({value:i.value,label:i.label})),r=new Set(t.map(i=>i.value));for(let i of e)r.has(i.value)||n.push(i);return n}function Fu(t,e){if(!(!t.uniqueKeys||t.uniqueKeys.length===0))for(let n=0;n<t.uniqueKeys.length;n++){let r=t.uniqueKeys[n];if(!r)continue;if(!r.fields||r.fields.length===0)throw y(new Error(`uniqueKeys[${n}] for entity '${t.name}' must have at least one field`),{userMessage:`uniqueKeys[${n}] for entity '${t.name}' must have at least one field`,context:{entityName:t.name,uniqueKeyIndex:n},severity:"error"});let i=r.fields.filter(o=>!e.has(o));if(i.length>0)throw y(new Error(`uniqueKeys[${n}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${n}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:t.name,uniqueKeyIndex:n,invalidFields:i},severity:"error"})}}function Vu(t){let{form:e,fields:n}=t,r=Object.keys(n);if(e){if(e.type==="multi-step"||e.type==="wizard"){if(!e.steps||e.steps.length===0)throw y(new Error(`Multi-step form for entity '${t.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${t.name}' must have at least one step`,context:{entityName:t.name,operation:"validateFormConfig"},severity:"error"});let i=e.steps.flatMap(u=>u.fields),o=i.filter(u=>!r.includes(u));if(o.length>0)throw y(new Error(`Multi-step form for entity '${t.name}' references non-existent fields: ${o.join(", ")}`),{userMessage:`Multi-step form for entity '${t.name}' references non-existent fields: ${o.join(", ")}`,context:{entityName:t.name,invalidFields:o,operation:"validateFormConfig"},severity:"error"});let s=new Set(i);r.filter(u=>!s.has(u)).length>0}e.rules&&e.rules.forEach((i,o)=>{let c=(Array.isArray(i.condition)?i.condition.map(m=>m.field):[i.condition.field]).filter(m=>!r.includes(m));if(c.length>0)throw y(new Error(`Dynamic form rule ${o} for entity '${t.name}' references non-existent condition fields: ${c.join(", ")}`),{userMessage:`Dynamic form rule ${o} for entity '${t.name}' references non-existent condition fields: ${c.join(", ")}`,context:{entityName:t.name,ruleIndex:o,invalidFields:c,operation:"validateFormConfig"},severity:"error"});let p=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(m=>!r.includes(m));if(p.length>0)throw y(new Error(`Dynamic form rule ${o} for entity '${t.name}' references non-existent affected fields: ${p.join(", ")}`),{userMessage:`Dynamic form rule ${o} for entity '${t.name}' references non-existent affected fields: ${p.join(", ")}`,context:{entityName:t.name,ruleIndex:o,invalidFields:p,operation:"validateFormConfig"},severity:"error"})}),Object.entries(n).forEach(([i,o])=>{if(o.dependsOn&&!r.includes(o.dependsOn.field))throw y(new Error(`Field '${i}' in entity '${t.name}' depends on non-existent field: ${o.dependsOn.field}`),{userMessage:`Field '${i}' in entity '${t.name}' depends on non-existent field: ${o.dependsOn.field}`,context:{entityName:t.name,fieldName:i,dependsOnField:o.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function Bu(t){return t.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...t.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function nb(t){try{Vu(t);let e=Bu(t),n={...t.fields,...R,...t.fields.createdAt&&{createdAt:{...R.createdAt,...t.fields.createdAt,type:R.createdAt.type,visibility:R.createdAt.visibility}},...t.fields.updatedAt&&{updatedAt:{...R.updatedAt,...t.fields.updatedAt,type:R.updatedAt.type,visibility:R.updatedAt.visibility}},...t.fields.createdById&&{createdById:{...R.createdById,...t.fields.createdById,type:R.createdById.type,visibility:R.createdById.visibility}},...t.fields.updatedById&&{updatedById:{...R.updatedById,...t.fields.updatedById,type:R.updatedById.type,visibility:R.updatedById.visibility}},...t.fields.status&&{status:{...R.status,...t.fields.status,type:R.status.type,visibility:R.status.visibility,editable:R.status.editable,validation:{...R.status.validation,required:!0,nullable:t.fields.status.validation?.nullable,options:Mu(lr,t.fields.status.validation?.options)}}},...t.scope&&{[t.scope.field]:Uu(t.scope)}};if(t.listFields){let o=new Set(Object.keys(n)),s=t.listFields.filter(c=>!o.has(c));if(s.length>0)throw y(new Error(`Entity '${t.name}' defines listFields that do not exist: ${s.join(", ")}`),{userMessage:`Entity '${t.name}' defines listFields that do not exist: ${s.join(", ")}`,context:{entityName:t.name,invalidFields:s,operation:"defineEntity"},severity:"error"})}if(t.listCardFields){let o=new Set(Object.keys(n)),c=Ge(t).filter(u=>!o.has(u));if(c.length>0)throw y(new Error(`Entity '${t.name}' defines listCardFields that do not exist: ${c.join(", ")}`),{userMessage:`Entity '${t.name}' defines listCardFields that do not exist: ${c.join(", ")}`,context:{entityName:t.name,invalidFields:c,operation:"defineEntity"},severity:"error"})}if(t.uniqueKeys){let o=new Set(Object.keys(n));Fu(t,o)}let r={...Xt,...t.access||{}},i=t.namespace||`entity-${t.name.toLowerCase()}`;return{...t,form:e,fields:n,access:r,namespace:i}}catch(e){throw y(e,{userMessage:`Failed to define entity '${t.name}'`,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}}import*as z from"valibot";function lt(t,e){return Object.assign(t,{visibility:e})}function me(t,e){let n=t;return n.metadata={collection:e.collection,entity:e.name,...e.uniqueKeys&&{uniqueKeys:e.uniqueKeys}},n}function ao(t){let e=Ke(t);return lt(e,t.visibility)}function co(t){let e=Ke({...t,validation:{...t.validation,required:!1}});return lt(e,t.visibility)}function cb(t){let e=t.fields,n={};for(let[D,P]of Object.entries(e))P.visibility!=="hidden"&&(n[D]=ao(P));let r=me(z.object(n),t),i={};for(let[D,P]of Object.entries(e))P.visibility!=="hidden"&&(Ue.includes(D)||(i[D]=ao(P)));let o=me(z.object(i),t),s={};for(let[D,P]of Object.entries(e))if(P.visibility!=="hidden"&&!Ue.includes(D))if(D==="status"){let Y=z.literal("draft");s[D]=lt(Y,P.visibility)}else s[D]=co(P);let c=me(z.object(s),t),u={};for(let[D,P]of Object.entries(e))P.visibility!=="hidden"&&(Ue.includes(D)||(u[D]=co(P)));u.id=lt(Ke(R.id),"technical");let p=me(z.object(u),t),m;if(t.listFields&&t.listFields.length>0){let D=["id","status"],P=[...new Set([...D,...t.listFields])];m={};for(let Y of P){let Me=n[Y];Me&&(m[Y]=Me)}}else m=n;let T=me(z.object(m),t),x,H=Ge(t);if(H.length>0){let D=["id","status"],P=[...new Set([...D,...H])];x={};for(let Y of P){let Me=n[Y];Me&&(x[Y]=Me)}}else x=n;let ie=me(z.object(x),t),dt=me(z.object({id:lt(Ke(R.id),"technical")}),t);return{create:o,draft:c,update:p,get:r,list:T,listCard:ie,delete:dt}}function lb(t,e,n=1,r=!1){let i=[];if(r)for(let o=e;o>=t;o-=n)i.push({value:String(o),label:String(o)});else for(let o=t;o<=e;o+=n)i.push({value:String(o),label:String(o)});return i}var ge=new Map;function pb(t,e){ge.has(t),ge.set(t,e)}function fb(t){ge.delete(t)}function hb(t){let e=ge.get(t);return e?e():null}function mb(t){return ge.has(t)}function gb(){return Array.from(ge.keys())}function vb(){ge.clear()}export{Gl as AGGREGATE_FILTER_OPERATORS,Wl as AGGREGATE_OPERATIONS,hd as AUTH_EVENTS,ye as AUTH_PARTNERS,Tl as AUTH_PARTNER_STATE,yt as AuthHardening,br as AuthUserSchema,Ue as BACKEND_GENERATED_FIELD_NAMES,gd as BILLING_EVENTS,To as BREAKPOINT_RANGES,Qt as BREAKPOINT_THRESHOLDS,fr as COMMON_TIER_CONFIGS,N as CONFIDENCE_LEVELS,Cr as CONSENT_CATEGORY,k as CONTEXTS,se as CRUD_OPERATORS,sn as CURRENCY_MAP,Er as CheckoutSessionMetadataSchema,hr as CreateCheckoutSessionRequestSchema,mr as CreateCheckoutSessionResponseSchema,Ir as CustomClaimsSchema,Xt as DEFAULT_ENTITY_ACCESS,ae as DEFAULT_ERROR_MESSAGES,Fd as DEFAULT_LAYOUT_PRESET,lr as DEFAULT_STATUS_OPTIONS,zE as DEFAULT_STATUS_VALUE,Ju as DEFAULT_SUBSCRIPTION,bp as DENSITY,w as DoNotDevError,Ml as EDITABLE,ht as ENTITY_HOOK_ERRORS,oe as ENVIRONMENTS,Be as ERROR_CODES,ud as ERROR_SEVERITY,ld as ERROR_SOURCE,Tr as EntityHookError,Kt as FEATURES,Ip as FEATURE_CONSENT_MATRIX,Ve as FEATURE_STATUS,Bl as FIELD_TYPES,Jt as FIREBASE_ERROR_MAP,ft as FIRESTORE_ID_PATTERN,Sr as GITHUB_PERMISSION_LEVELS,YE as HIDDEN_STATUSES,Vd as LAYOUT_PRESET,Vl as LIST_SCHEMA_TYPE,yd as OAUTH_EVENTS,en as OAUTH_PARTNERS,Fl as ORDER_DIRECTION,ap as PARTNER_ICONS,bd as PAYLOAD_EVENTS,zt as PERMISSIONS,S as PLATFORMS,Dl as PWA_ASSET_TYPES,Ol as PWA_DISPLAY_MODES,Eo as ProductDeclarationSchema,sl as ProductDeclarationsSchema,Nl as ROUTE_SOURCES,xl as STORAGE_SCOPES,kl as STORAGE_TYPES,Td as STRIPE_EVENTS,pt as STRIPE_MODES,Yu as SUBSCRIPTION_DURATIONS,ve as SUBSCRIPTION_STATUS,Fe as SUBSCRIPTION_TIERS,Lr as ServerUtils,dn as SingletonManager,Io as StripeBackConfigSchema,bo as StripeFrontConfigSchema,vo as StripePaymentSchema,yo as StripeSubscriptionSchema,vr as SubscriptionClaimsSchema,gr as SubscriptionDataSchema,Lu as TECHNICAL_FIELD_NAMES,O as USER_ROLES,Yt as UserSubscriptionSchema,Ul as VISIBILITY,yr as WebhookEventSchema,qe as addMonths,fn as addYears,Ks as addressSchema,Ys as arraySchema,R as baseFields,Ur as booleanSchema,Ls as calculateSubscriptionEndDate,rn as captureErrorToSentry,Jd as checkGitHubAccessSchema,Mh as clearSchemaGenerators,vb as clearScopeProviders,He as commonErrorCodeMappings,an as compactToISOString,Ts as configureProviders,ws as createAsyncSingleton,Xu as createDefaultSubscriptionClaims,Sl as createDefaultUserProfile,Xl as createEntitySchema,$ as createErrorHandler,Jo as createMetadata,Rs as createMethodProxy,cb as createSchemas,We as createSingleton,_s as createSingletonWithParams,Ie as dateSchema,nb as defineEntity,Zl as deleteEntitySchema,tn as detectErrorSource,ep as disconnectOAuthSchema,Hs as emailSchema,Oh as enhanceSchema,qo as ensureSpreadable,Qd as exchangeTokenSchema,Mr as fileSchema,Fr as filesSchema,Ds as filterVisibleFields,Zo as formatCurrency,Pr as formatDate,ss as formatRelativeTime,ta as gdprConsentSchema,xr as generateCodeChallenge,kr as generateCodeVerifier,ps as generateFirestoreRuleCondition,hs as generatePKCEPair,js as geopointSchema,So as getBreakpointFromWidth,Ud as getBreakpointUtils,qE as getCollectionName,tp as getConnectionsSchema,Rr as getCurrencyLocale,Qo as getCurrencySymbol,ns as getCurrentTimestamp,Jl as getEntitySchema,Ge as getListCardFieldNames,Ss as getProvider,Uh as getRegisteredSchemaTypes,gb as getRegisteredScopeProviders,bs as getRoleFromClaims,Ke as getSchemaType,hb as getScopeValue,pn as getVisibleFields,os as getWeekFromISOString,Ao as githubPermissionSchema,Zt as githubRepoConfigSchema,Yd as grantGitHubAccessSchema,y as handleError,Lh as hasCustomSchemaGenerator,Nu as hasMetadata,As as hasProvider,Ns as hasRestrictedVisibility,gt as hasRoleAccess,mb as hasScopeProvider,Is as hasTierAccess,Zs as ibanSchema,Oo as isAuthPartnerId,JE as isBackendGeneratedField,Ld as isBreakpoint,cn as isCompactDateString,Nr as isFieldVisible,XE as isFrameworkField,Do as isOAuthPartnerId,ms as isPKCESupported,es as isoToCompactString,Es as lazyImport,ed as listEntitiesSchema,zs as mapSchema,ce as mapToDoNotDevError,fs as maybeTranslate,Xs as multiselectSchema,Vr as neverSchema,ts as normalizeToISOString,be as numberSchema,Gu as overrideFeatures,zu as overridePaymentModes,qu as overridePermissions,Ku as overrideSubscriptionStatus,Wu as overrideSubscriptionTiers,$u as overrideUserRoles,un as parseDate,cs as parseDateToNoonUTC,Us as parseISODate,Bs as parseServerCookie,$s as passwordSchema,Gs as pictureSchema,qs as picturesSchema,na as priceSchema,lb as rangeOptions,Js as referenceSchema,Zd as refreshTokenSchema,v as registerSchemaGenerator,pb as registerScopeProvider,OE as registerUniqueConstraintValidator,Cs as resetProviders,Xd as revokeGitHubAccessSchema,Go as safeValidate,hn as selectSchema,Vo as showNotification,mn as stringSchema,ea as switchSchema,Qs as telSchema,Et as textSchema,is as timestampToISOString,us as toDateOnly,rs as toISOString,Ko as translateArray,Yo as translateArrayRange,Xo as translateArrayWithIndices,zo as translateObjectArray,fb as unregisterScopeProvider,Ql as updateEntitySchema,Ps as updateMetadata,Ws as urlSchema,up as validateAuthPartners,bl as validateAuthSchemas,vl as validateAuthUser,ul as validateBillingSchemas,ol as validateCheckoutSessionMetadata,vs as validateCodeChallenge,gs as validateCodeVerifier,el as validateCreateCheckoutSessionRequest,tl as validateCreateCheckoutSessionResponse,El as validateCustomClaims,qt as validateDates,UE as validateDocument,Vs as validateEnvVar,Fs as validateMetadata,lp as validateOAuthPartners,cl as validateStripeBackConfig,al as validateStripeFrontConfig,rl as validateSubscriptionClaims,nl as validateSubscriptionData,oo as validateUniqueFields,Ms as validateUrl,yl as validateUserSubscription,il as validateWebhookEvent,Wo as validateWithSchema,Fo as withErrorHandling,ys as withGracefulDegradation,$o as wrapAuthError,Bo as wrapCrudError,Ho as wrapStorageError};
2
2
  /*! Bundled license information:
3
3
 
4
4
  react/cjs/react.production.js: