(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[727],{67:e=>{"use strict";e.exports=require("node:async_hooks")},195:e=>{"use strict";e.exports=require("node:buffer")},206:(e,t,r)=>{"use strict";let s,i,n,a;r.r(t),r.d(t,{default:()=>iM});var o,l,c,u,h,d,p,f,g,m,b,y,w,v,_,k,S,T,E,R,O={};async function A(){let e="_ENTRIES"in globalThis&&_ENTRIES.middleware_instrumentation&&(await _ENTRIES.middleware_instrumentation).register;if(e)try{await e()}catch(e){throw e.message=`An error occurred while loading instrumentation hook: ${e.message}`,e}}r.r(O),r.d(O,{config:()=>i$,middleware:()=>iN,runtime:()=>ij});let P=null;function C(){return P||(P=A()),P}function x(e){return`The edge runtime does not support Node.js '${e}' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`}process!==r.g.process&&(process.env=r.g.process.env,r.g.process=process),Object.defineProperty(globalThis,"__import_unsupported",{value:function(e){let t=new Proxy(function(){},{get(t,r){if("then"===r)return{};throw Error(x(e))},construct(){throw Error(x(e))},apply(r,s,i){if("function"==typeof i[0])return i[0](t);throw Error(x(e))}});return new Proxy({},{get:()=>t})},enumerable:!1,configurable:!1}),C();class I extends Error{constructor({page:e}){super(`The middleware "${e}" accepts an async API directly with the form:
  
  export function middleware(request, event) {
    return NextResponse.redirect('/new-location')
  }
  
  Read more: https://nextjs.org/docs/messages/middleware-new-signature
  `)}}class j extends Error{constructor(){super(`The request.page has been deprecated in favour of \`URLPattern\`.
  Read more: https://nextjs.org/docs/messages/middleware-request-page
  `)}}class N extends Error{constructor(){super(`The request.ua has been removed in favour of \`userAgent\` function.
  Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent
  `)}}let $={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",api:"api",middleware:"middleware",instrument:"instrument",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",appMetadataRoute:"app-metadata-route",appRouteHandler:"app-route-handler"};function L(e){var t,r,s,i,n,a=[],o=0;function l(){for(;o<e.length&&/\s/.test(e.charAt(o));)o+=1;return o<e.length}for(;o<e.length;){for(t=o,n=!1;l();)if(","===(r=e.charAt(o))){for(s=o,o+=1,l(),i=o;o<e.length&&"="!==(r=e.charAt(o))&&";"!==r&&","!==r;)o+=1;o<e.length&&"="===e.charAt(o)?(n=!0,o=i,a.push(e.substring(t,s)),t=o):o=s+1}else o+=1;(!n||o>=e.length)&&a.push(e.substring(t,e.length))}return a}function D(e){let t={},r=[];if(e)for(let[s,i]of e.entries())"set-cookie"===s.toLowerCase()?(r.push(...L(i)),t[s]=1===r.length?r[0]:r):t[s]=i;return t}function U(e){try{return String(new URL(String(e)))}catch(t){throw Error(`URL is malformed "${String(e)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,{cause:t})}}({...$,GROUP:{serverOnly:[$.reactServerComponents,$.actionBrowser,$.appMetadataRoute,$.appRouteHandler,$.instrument],clientOnly:[$.serverSideRendering,$.appPagesBrowser],nonClientServerTarget:[$.middleware,$.api],app:[$.reactServerComponents,$.actionBrowser,$.appMetadataRoute,$.appRouteHandler,$.serverSideRendering,$.appPagesBrowser,$.shared,$.instrument]}});let M=Symbol("response"),B=Symbol("passThrough"),q=Symbol("waitUntil");class H{constructor(e){this[q]=[],this[B]=!1}respondWith(e){this[M]||(this[M]=Promise.resolve(e))}passThroughOnException(){this[B]=!0}waitUntil(e){this[q].push(e)}}class V extends H{constructor(e){super(e.request),this.sourcePage=e.page}get request(){throw new I({page:this.sourcePage})}respondWith(){throw new I({page:this.sourcePage})}}function W(e){return e.replace(/\/$/,"")||"/"}function G(e){let t=e.indexOf("#"),r=e.indexOf("?"),s=r>-1&&(t<0||r<t);return s||t>-1?{pathname:e.substring(0,s?r:t),query:s?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}function K(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:s,hash:i}=G(e);return""+t+r+s+i}function F(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:s,hash:i}=G(e);return""+r+t+s+i}function z(e,t){if("string"!=typeof e)return!1;let{pathname:r}=G(e);return r===t||r.startsWith(t+"/")}function J(e,t){let r;let s=e.split("/");return(t||[]).some(t=>!!s[1]&&s[1].toLowerCase()===t.toLowerCase()&&(r=t,s.splice(1,1),e=s.join("/")||"/",!0)),{pathname:e,detectedLocale:r}}let X=/(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)/;function Y(e,t){return new URL(String(e).replace(X,"localhost"),t&&String(t).replace(X,"localhost"))}let Q=Symbol("NextURLInternal");class Z{constructor(e,t,r){let s,i;"object"==typeof t&&"pathname"in t||"string"==typeof t?(s=t,i=r||{}):i=r||t||{},this[Q]={url:Y(e,s??i.base),options:i,basePath:""},this.analyze()}analyze(){var e,t,r,s,i;let n=function(e,t){var r,s;let{basePath:i,i18n:n,trailingSlash:a}=null!=(r=t.nextConfig)?r:{},o={pathname:e,trailingSlash:"/"!==e?e.endsWith("/"):a};i&&z(o.pathname,i)&&(o.pathname=function(e,t){if(!z(e,t))return e;let r=e.slice(t.length);return r.startsWith("/")?r:"/"+r}(o.pathname,i),o.basePath=i);let l=o.pathname;if(o.pathname.startsWith("/_next/data/")&&o.pathname.endsWith(".json")){let e=o.pathname.replace(/^\/_next\/data\//,"").replace(/\.json$/,"").split("/"),r=e[0];o.buildId=r,l="index"!==e[1]?"/"+e.slice(1).join("/"):"/",!0===t.parseData&&(o.pathname=l)}if(n){let e=t.i18nProvider?t.i18nProvider.analyze(o.pathname):J(o.pathname,n.locales);o.locale=e.detectedLocale,o.pathname=null!=(s=e.pathname)?s:o.pathname,!e.detectedLocale&&o.buildId&&(e=t.i18nProvider?t.i18nProvider.analyze(l):J(l,n.locales)).detectedLocale&&(o.locale=e.detectedLocale)}return o}(this[Q].url.pathname,{nextConfig:this[Q].options.nextConfig,parseData:!0,i18nProvider:this[Q].options.i18nProvider}),a=function(e,t){let r;if((null==t?void 0:t.host)&&!Array.isArray(t.host))r=t.host.toString().split(":",1)[0];else{if(!e.hostname)return;r=e.hostname}return r.toLowerCase()}(this[Q].url,this[Q].options.headers);this[Q].domainLocale=this[Q].options.i18nProvider?this[Q].options.i18nProvider.detectDomainLocale(a):function(e,t,r){if(e)for(let n of(r&&(r=r.toLowerCase()),e)){var s,i;if(t===(null==(s=n.domain)?void 0:s.split(":",1)[0].toLowerCase())||r===n.defaultLocale.toLowerCase()||(null==(i=n.locales)?void 0:i.some(e=>e.toLowerCase()===r)))return n}}(null==(t=this[Q].options.nextConfig)?void 0:null==(e=t.i18n)?void 0:e.domains,a);let o=(null==(r=this[Q].domainLocale)?void 0:r.defaultLocale)||(null==(i=this[Q].options.nextConfig)?void 0:null==(s=i.i18n)?void 0:s.defaultLocale);this[Q].url.pathname=n.pathname,this[Q].defaultLocale=o,this[Q].basePath=n.basePath??"",this[Q].buildId=n.buildId,this[Q].locale=n.locale??o,this[Q].trailingSlash=n.trailingSlash}formatPathname(){var e;let t;return t=function(e,t,r,s){if(!t||t===r)return e;let i=e.toLowerCase();return!s&&(z(i,"/api")||z(i,"/"+t.toLowerCase()))?e:K(e,"/"+t)}((e={basePath:this[Q].basePath,buildId:this[Q].buildId,defaultLocale:this[Q].options.forceLocale?void 0:this[Q].defaultLocale,locale:this[Q].locale,pathname:this[Q].url.pathname,trailingSlash:this[Q].trailingSlash}).pathname,e.locale,e.buildId?void 0:e.defaultLocale,e.ignorePrefix),(e.buildId||!e.trailingSlash)&&(t=W(t)),e.buildId&&(t=F(K(t,"/_next/data/"+e.buildId),"/"===e.pathname?"index.json":".json")),t=K(t,e.basePath),!e.buildId&&e.trailingSlash?t.endsWith("/")?t:F(t,"/"):W(t)}formatSearch(){return this[Q].url.search}get buildId(){return this[Q].buildId}set buildId(e){this[Q].buildId=e}get locale(){return this[Q].locale??""}set locale(e){var t,r;if(!this[Q].locale||!(null==(r=this[Q].options.nextConfig)?void 0:null==(t=r.i18n)?void 0:t.locales.includes(e)))throw TypeError(`The NextURL configuration includes no locale "${e}"`);this[Q].locale=e}get defaultLocale(){return this[Q].defaultLocale}get domainLocale(){return this[Q].domainLocale}get searchParams(){return this[Q].url.searchParams}get host(){return this[Q].url.host}set host(e){this[Q].url.host=e}get hostname(){return this[Q].url.hostname}set hostname(e){this[Q].url.hostname=e}get port(){return this[Q].url.port}set port(e){this[Q].url.port=e}get protocol(){return this[Q].url.protocol}set protocol(e){this[Q].url.protocol=e}get href(){let e=this.formatPathname(),t=this.formatSearch();return`${this.protocol}//${this.host}${e}${t}${this.hash}`}set href(e){this[Q].url=Y(e),this.analyze()}get origin(){return this[Q].url.origin}get pathname(){return this[Q].url.pathname}set pathname(e){this[Q].url.pathname=e}get hash(){return this[Q].url.hash}set hash(e){this[Q].url.hash=e}get search(){return this[Q].url.search}set search(e){this[Q].url.search=e}get password(){return this[Q].url.password}set password(e){this[Q].url.password=e}get username(){return this[Q].url.username}set username(e){this[Q].url.username=e}get basePath(){return this[Q].basePath}set basePath(e){this[Q].basePath=e.startsWith("/")?e:`/${e}`}toString(){return this.href}toJSON(){return this.href}[Symbol.for("edge-runtime.inspect.custom")](){return{href:this.href,origin:this.origin,protocol:this.protocol,username:this.username,password:this.password,host:this.host,hostname:this.hostname,port:this.port,pathname:this.pathname,search:this.search,searchParams:this.searchParams,hash:this.hash}}clone(){return new Z(String(this),this[Q].options)}}var ee=r(945);let et=Symbol("internal request");class er extends Request{constructor(e,t={}){let r="string"!=typeof e&&"url"in e?e.url:String(e);U(r),e instanceof Request?super(e,t):super(r,t);let s=new Z(r,{headers:D(this.headers),nextConfig:t.nextConfig});this[et]={cookies:new ee.RequestCookies(this.headers),geo:t.geo||{},ip:t.ip,nextUrl:s,url:s.toString()}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,geo:this.geo,ip:this.ip,nextUrl:this.nextUrl,url:this.url,bodyUsed:this.bodyUsed,cache:this.cache,credentials:this.credentials,destination:this.destination,headers:Object.fromEntries(this.headers),integrity:this.integrity,keepalive:this.keepalive,method:this.method,mode:this.mode,redirect:this.redirect,referrer:this.referrer,referrerPolicy:this.referrerPolicy,signal:this.signal}}get cookies(){return this[et].cookies}get geo(){return this[et].geo}get ip(){return this[et].ip}get nextUrl(){return this[et].nextUrl}get page(){throw new j}get ua(){throw new N}get url(){return this[et].url}}class es{static get(e,t,r){let s=Reflect.get(e,t,r);return"function"==typeof s?s.bind(e):s}static set(e,t,r,s){return Reflect.set(e,t,r,s)}static has(e,t){return Reflect.has(e,t)}static deleteProperty(e,t){return Reflect.deleteProperty(e,t)}}let ei=Symbol("internal response"),en=new Set([301,302,303,307,308]);function ea(e,t){var r;if(null==e?void 0:null==(r=e.request)?void 0:r.headers){if(!(e.request.headers instanceof Headers))throw Error("request.headers must be an instance of Headers");let r=[];for(let[s,i]of e.request.headers)t.set("x-middleware-request-"+s,i),r.push(s);t.set("x-middleware-override-headers",r.join(","))}}class eo extends Response{constructor(e,t={}){super(e,t);let r=this.headers,s=new Proxy(new ee.ResponseCookies(r),{get(e,s,i){switch(s){case"delete":case"set":return(...i)=>{let n=Reflect.apply(e[s],e,i),a=new Headers(r);return n instanceof ee.ResponseCookies&&r.set("x-middleware-set-cookie",n.getAll().map(e=>(0,ee.stringifyCookie)(e)).join(",")),ea(t,a),n};default:return es.get(e,s,i)}}});this[ei]={cookies:s,url:t.url?new Z(t.url,{headers:D(r),nextConfig:t.nextConfig}):void 0}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,url:this.url,body:this.body,bodyUsed:this.bodyUsed,headers:Object.fromEntries(this.headers),ok:this.ok,redirected:this.redirected,status:this.status,statusText:this.statusText,type:this.type}}get cookies(){return this[ei].cookies}static json(e,t){let r=Response.json(e,t);return new eo(r.body,r)}static redirect(e,t){let r="number"==typeof t?t:(null==t?void 0:t.status)??307;if(!en.has(r))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');let s="object"==typeof t?t:{},i=new Headers(null==s?void 0:s.headers);return i.set("Location",U(e)),new eo(null,{...s,headers:i,status:r})}static rewrite(e,t){let r=new Headers(null==t?void 0:t.headers);return r.set("x-middleware-rewrite",U(e)),ea(t,r),new eo(null,{...t,headers:r})}static next(e){let t=new Headers(null==e?void 0:e.headers);return t.set("x-middleware-next","1"),ea(e,t),new eo(null,{...e,headers:t})}}function el(e,t){let r="string"==typeof t?new URL(t):t,s=new URL(e,t),i=r.protocol+"//"+r.host;return s.protocol+"//"+s.host===i?s.toString().replace(i,""):s.toString()}let ec=[["RSC"],["Next-Router-State-Tree"],["Next-Router-Prefetch"]],eu=["__nextFallback","__nextLocale","__nextInferredLocaleFromDefault","__nextDefaultLocale","__nextIsNotFound","_rsc"],eh=["__nextDataReq"];class ed extends Error{constructor(){super("Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers")}static callable(){throw new ed}}class ep extends Headers{constructor(e){super(),this.headers=new Proxy(e,{get(t,r,s){if("symbol"==typeof r)return es.get(t,r,s);let i=r.toLowerCase(),n=Object.keys(e).find(e=>e.toLowerCase()===i);if(void 0!==n)return es.get(t,n,s)},set(t,r,s,i){if("symbol"==typeof r)return es.set(t,r,s,i);let n=r.toLowerCase(),a=Object.keys(e).find(e=>e.toLowerCase()===n);return es.set(t,a??r,s,i)},has(t,r){if("symbol"==typeof r)return es.has(t,r);let s=r.toLowerCase(),i=Object.keys(e).find(e=>e.toLowerCase()===s);return void 0!==i&&es.has(t,i)},deleteProperty(t,r){if("symbol"==typeof r)return es.deleteProperty(t,r);let s=r.toLowerCase(),i=Object.keys(e).find(e=>e.toLowerCase()===s);return void 0===i||es.deleteProperty(t,i)}})}static seal(e){return new Proxy(e,{get(e,t,r){switch(t){case"append":case"delete":case"set":return ed.callable;default:return es.get(e,t,r)}}})}merge(e){return Array.isArray(e)?e.join(", "):e}static from(e){return e instanceof Headers?e:new ep(e)}append(e,t){let r=this.headers[e];"string"==typeof r?this.headers[e]=[r,t]:Array.isArray(r)?r.push(t):this.headers[e]=t}delete(e){delete this.headers[e]}get(e){let t=this.headers[e];return void 0!==t?this.merge(t):null}has(e){return void 0!==this.headers[e]}set(e,t){this.headers[e]=t}forEach(e,t){for(let[r,s]of this.entries())e.call(t,s,r,this)}*entries(){for(let e of Object.keys(this.headers)){let t=e.toLowerCase(),r=this.get(t);yield[t,r]}}*keys(){for(let e of Object.keys(this.headers)){let t=e.toLowerCase();yield t}}*values(){for(let e of Object.keys(this.headers)){let t=this.get(e);yield t}}[Symbol.iterator](){return this.entries()}}let ef=Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available");class eg{disable(){throw ef}getStore(){}run(){throw ef}exit(){throw ef}enterWith(){throw ef}}let em=globalThis.AsyncLocalStorage;function eb(){return em?new em:new eg}let ey=eb();class ew extends Error{constructor(){super("Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options")}static callable(){throw new ew}}class ev{static seal(e){return new Proxy(e,{get(e,t,r){switch(t){case"clear":case"delete":case"set":return ew.callable;default:return es.get(e,t,r)}}})}}let e_=Symbol.for("next.mutated.cookies");class ek{static wrap(e,t){let r=new ee.ResponseCookies(new Headers);for(let t of e.getAll())r.set(t);let s=[],i=new Set,n=()=>{let e=ey.getStore();if(e&&(e.pathWasRevalidated=!0),s=r.getAll().filter(e=>i.has(e.name)),t){let e=[];for(let t of s){let r=new ee.ResponseCookies(new Headers);r.set(t),e.push(r.toString())}t(e)}};return new Proxy(r,{get(e,t,r){switch(t){case e_:return s;case"delete":return function(...t){i.add("string"==typeof t[0]?t[0]:t[0].name);try{e.delete(...t)}finally{n()}};case"set":return function(...t){i.add("string"==typeof t[0]?t[0]:t[0].name);try{return e.set(...t)}finally{n()}};default:return es.get(e,t,r)}}})}}!function(e){e.handleRequest="BaseServer.handleRequest",e.run="BaseServer.run",e.pipe="BaseServer.pipe",e.getStaticHTML="BaseServer.getStaticHTML",e.render="BaseServer.render",e.renderToResponseWithComponents="BaseServer.renderToResponseWithComponents",e.renderToResponse="BaseServer.renderToResponse",e.renderToHTML="BaseServer.renderToHTML",e.renderError="BaseServer.renderError",e.renderErrorToResponse="BaseServer.renderErrorToResponse",e.renderErrorToHTML="BaseServer.renderErrorToHTML",e.render404="BaseServer.render404"}(o||(o={})),function(e){e.loadDefaultErrorComponents="LoadComponents.loadDefaultErrorComponents",e.loadComponents="LoadComponents.loadComponents"}(l||(l={})),function(e){e.getRequestHandler="NextServer.getRequestHandler",e.getServer="NextServer.getServer",e.getServerRequestHandler="NextServer.getServerRequestHandler",e.createServer="createServer.createServer"}(c||(c={})),function(e){e.compression="NextNodeServer.compression",e.getBuildId="NextNodeServer.getBuildId",e.createComponentTree="NextNodeServer.createComponentTree",e.clientComponentLoading="NextNodeServer.clientComponentLoading",e.getLayoutOrPageModule="NextNodeServer.getLayoutOrPageModule",e.generateStaticRoutes="NextNodeServer.generateStaticRoutes",e.generateFsStaticRoutes="NextNodeServer.generateFsStaticRoutes",e.generatePublicRoutes="NextNodeServer.generatePublicRoutes",e.generateImageRoutes="NextNodeServer.generateImageRoutes.route",e.sendRenderResult="NextNodeServer.sendRenderResult",e.proxyRequest="NextNodeServer.proxyRequest",e.runApi="NextNodeServer.runApi",e.render="NextNodeServer.render",e.renderHTML="NextNodeServer.renderHTML",e.imageOptimizer="NextNodeServer.imageOptimizer",e.getPagePath="NextNodeServer.getPagePath",e.getRoutesManifest="NextNodeServer.getRoutesManifest",e.findPageComponents="NextNodeServer.findPageComponents",e.getFontManifest="NextNodeServer.getFontManifest",e.getServerComponentManifest="NextNodeServer.getServerComponentManifest",e.getRequestHandler="NextNodeServer.getRequestHandler",e.renderToHTML="NextNodeServer.renderToHTML",e.renderError="NextNodeServer.renderError",e.renderErrorToHTML="NextNodeServer.renderErrorToHTML",e.render404="NextNodeServer.render404",e.startResponse="NextNodeServer.startResponse",e.route="route",e.onProxyReq="onProxyReq",e.apiResolver="apiResolver",e.internalFetch="internalFetch"}(u||(u={})),(h||(h={})).startServer="startServer.startServer",function(e){e.getServerSideProps="Render.getServerSideProps",e.getStaticProps="Render.getStaticProps",e.renderToString="Render.renderToString",e.renderDocument="Render.renderDocument",e.createBodyResult="Render.createBodyResult"}(d||(d={})),function(e){e.renderToString="AppRender.renderToString",e.renderToReadableStream="AppRender.renderToReadableStream",e.getBodyResult="AppRender.getBodyResult",e.fetch="AppRender.fetch"}(p||(p={})),(f||(f={})).executeRoute="Router.executeRoute",(g||(g={})).runHandler="Node.runHandler",(m||(m={})).runHandler="AppRouteRouteHandlers.runHandler",function(e){e.generateMetadata="ResolveMetadata.generateMetadata",e.generateViewport="ResolveMetadata.generateViewport"}(b||(b={})),(y||(y={})).execute="Middleware.execute";let eS=["Middleware.execute","BaseServer.handleRequest","Render.getServerSideProps","Render.getStaticProps","AppRender.fetch","AppRender.getBodyResult","Render.renderDocument","Node.runHandler","AppRouteRouteHandlers.runHandler","ResolveMetadata.generateMetadata","ResolveMetadata.generateViewport","NextNodeServer.createComponentTree","NextNodeServer.findPageComponents","NextNodeServer.getLayoutOrPageModule","NextNodeServer.startResponse","NextNodeServer.clientComponentLoading"],eT=["NextNodeServer.findPageComponents","NextNodeServer.createComponentTree","NextNodeServer.clientComponentLoading"],{context:eE,propagation:eR,trace:eO,SpanStatusCode:eA,SpanKind:eP,ROOT_CONTEXT:eC}=s=r(439),ex=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then,eI=(e,t)=>{(null==t?void 0:t.bubble)===!0?e.setAttribute("next.bubble",!0):(t&&e.recordException(t),e.setStatus({code:eA.ERROR,message:null==t?void 0:t.message})),e.end()},ej=new Map,eN=s.createContextKey("next.rootSpanId"),e$=0,eL=()=>e$++;class eD{getTracerInstance(){return eO.getTracer("next.js","0.0.1")}getContext(){return eE}getActiveScopeSpan(){return eO.getSpan(null==eE?void 0:eE.active())}withPropagatedContext(e,t,r){let s=eE.active();if(eO.getSpanContext(s))return t();let i=eR.extract(s,e,r);return eE.with(i,t)}trace(...e){var t;let[r,s,i]=e,{fn:n,options:a}="function"==typeof s?{fn:s,options:{}}:{fn:i,options:{...s}},o=a.spanName??r;if(!eS.includes(r)&&"1"!==process.env.NEXT_OTEL_VERBOSE||a.hideSpan)return n();let l=this.getSpanContext((null==a?void 0:a.parentSpan)??this.getActiveScopeSpan()),c=!1;l?(null==(t=eO.getSpanContext(l))?void 0:t.isRemote)&&(c=!0):(l=(null==eE?void 0:eE.active())??eC,c=!0);let u=eL();return a.attributes={"next.span_name":o,"next.span_type":r,...a.attributes},eE.with(l.setValue(eN,u),()=>this.getTracerInstance().startActiveSpan(o,a,e=>{let t="performance"in globalThis?globalThis.performance.now():void 0,s=()=>{ej.delete(u),t&&process.env.NEXT_OTEL_PERFORMANCE_PREFIX&&eT.includes(r||"")&&performance.measure(`${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-${(r.split(".").pop()||"").replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}`,{start:t,end:performance.now()})};c&&ej.set(u,new Map(Object.entries(a.attributes??{})));try{if(n.length>1)return n(e,t=>eI(e,t));let t=n(e);if(ex(t))return t.then(t=>(e.end(),t)).catch(t=>{throw eI(e,t),t}).finally(s);return e.end(),s(),t}catch(t){throw eI(e,t),s(),t}}))}wrap(...e){let t=this,[r,s,i]=3===e.length?e:[e[0],{},e[1]];return eS.includes(r)||"1"===process.env.NEXT_OTEL_VERBOSE?function(){let e=s;"function"==typeof e&&"function"==typeof i&&(e=e.apply(this,arguments));let n=arguments.length-1,a=arguments[n];if("function"!=typeof a)return t.trace(r,e,()=>i.apply(this,arguments));{let s=t.getContext().bind(eE.active(),a);return t.trace(r,e,(e,t)=>(arguments[n]=function(e){return null==t||t(e),s.apply(this,arguments)},i.apply(this,arguments)))}}:i}startSpan(...e){let[t,r]=e,s=this.getSpanContext((null==r?void 0:r.parentSpan)??this.getActiveScopeSpan());return this.getTracerInstance().startSpan(t,r,s)}getSpanContext(e){return e?eO.setSpan(eE.active(),e):void 0}getRootSpanAttributes(){let e=eE.active().getValue(eN);return ej.get(e)}}let eU=(()=>{let e=new eD;return()=>e})(),eM="__prerender_bypass";Symbol("__next_preview_data"),Symbol(eM);class eB{constructor(e,t,r,s){var i;let n=e&&function(e,t){let r=ep.from(e.headers);return{isOnDemandRevalidate:r.get("x-prerender-revalidate")===t.previewModeId,revalidateOnlyGenerated:r.has("x-prerender-revalidate-if-generated")}}(t,e).isOnDemandRevalidate,a=null==(i=r.get(eM))?void 0:i.value;this.isEnabled=!!(!n&&a&&e&&a===e.previewModeId),this._previewModeId=null==e?void 0:e.previewModeId,this._mutableCookies=s}enable(){if(!this._previewModeId)throw Error("Invariant: previewProps missing previewModeId this should never happen");this._mutableCookies.set({name:eM,value:this._previewModeId,httpOnly:!0,sameSite:"none",secure:!0,path:"/"})}disable(){this._mutableCookies.set({name:eM,value:"",httpOnly:!0,sameSite:"none",secure:!0,path:"/",expires:new Date(0)})}}function eq(e,t){if("x-middleware-set-cookie"in e.headers&&"string"==typeof e.headers["x-middleware-set-cookie"]){let r=e.headers["x-middleware-set-cookie"],s=new Headers;for(let e of L(r))s.append("set-cookie",e);for(let e of new ee.ResponseCookies(s).getAll())t.set(e)}}let eH={wrap(e,{req:t,res:r,renderOpts:s},i){let n;function a(e){r&&r.setHeader("Set-Cookie",e)}s&&"previewProps"in s&&(n=s.previewProps);let o={},l={get headers(){return o.headers||(o.headers=function(e){let t=ep.from(e);for(let e of ec)t.delete(e.toString().toLowerCase());return ep.seal(t)}(t.headers)),o.headers},get cookies(){if(!o.cookies){let e=new ee.RequestCookies(ep.from(t.headers));eq(t,e),o.cookies=ev.seal(e)}return o.cookies},get mutableCookies(){if(!o.mutableCookies){let e=function(e,t){let r=new ee.RequestCookies(ep.from(e));return ek.wrap(r,t)}(t.headers,(null==s?void 0:s.onUpdateCookies)||(r?a:void 0));eq(t,e),o.mutableCookies=e}return o.mutableCookies},get draftMode(){return o.draftMode||(o.draftMode=new eB(n,t,this.cookies,this.mutableCookies)),o.draftMode},reactLoadableManifest:(null==s?void 0:s.reactLoadableManifest)||{},assetPrefix:(null==s?void 0:s.assetPrefix)||""};return e.run(l,i,l)}},eV=eb();function eW(){return{previewModeId:process.env.__NEXT_PREVIEW_MODE_ID,previewModeSigningKey:process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY||"",previewModeEncryptionKey:process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY||""}}class eG extends er{constructor(e){super(e.input,e.init),this.sourcePage=e.page}get request(){throw new I({page:this.sourcePage})}respondWith(){throw new I({page:this.sourcePage})}waitUntil(){throw new I({page:this.sourcePage})}}let eK={keys:e=>Array.from(e.keys()),get:(e,t)=>e.get(t)??void 0},eF=(e,t)=>eU().withPropagatedContext(e.headers,t,eK),ez=!1;async function eJ(e){let t,s;!function(){if(!ez&&(ez=!0,"true"===process.env.NEXT_PRIVATE_TEST_PROXY)){let{interceptTestApis:e,wrapRequestHandler:t}=r(177);e(),eF=t(eF)}}(),await C();let i=void 0!==self.__BUILD_MANIFEST;e.request.url=e.request.url.replace(/\.rsc($|\?)/,"$1");let n=new Z(e.request.url,{headers:e.request.headers,nextConfig:e.request.nextConfig});for(let e of[...n.searchParams.keys()]){let t=n.searchParams.getAll(e);!function(e,t){for(let r of["nxtP","nxtI"])e!==r&&e.startsWith(r)&&t(e.substring(r.length))}(e,r=>{for(let e of(n.searchParams.delete(r),t))n.searchParams.append(r,e);n.searchParams.delete(e)})}let a=n.buildId;n.buildId="";let o=e.request.headers["x-nextjs-data"];o&&"/index"===n.pathname&&(n.pathname="/");let l=function(e){let t=new Headers;for(let[r,s]of Object.entries(e))for(let e of Array.isArray(s)?s:[s])void 0!==e&&("number"==typeof e&&(e=e.toString()),t.append(r,e));return t}(e.request.headers),c=new Map;if(!i)for(let e of ec){let t=e.toString().toLowerCase();l.get(t)&&(c.set(t,l.get(t)),l.delete(t))}let u=new eG({page:e.page,input:(function(e,t){let r="string"==typeof e,s=r?new URL(e):e;for(let e of eu)s.searchParams.delete(e);if(t)for(let e of eh)s.searchParams.delete(e);return r?s.toString():s})(n,!0).toString(),init:{body:e.request.body,geo:e.request.geo,headers:l,ip:e.request.ip,method:e.request.method,nextConfig:e.request.nextConfig,signal:e.request.signal}});o&&Object.defineProperty(u,"__isData",{enumerable:!1,value:!0}),!globalThis.__incrementalCacheShared&&e.IncrementalCache&&(globalThis.__incrementalCache=new e.IncrementalCache({appDir:!0,fetchCache:!0,minimalMode:!0,fetchCacheKeyPrefix:"",dev:!1,requestHeaders:e.request.headers,requestProtocol:"https",getPrerenderManifest:()=>({version:-1,routes:{},dynamicRoutes:{},notFoundRoutes:[],preview:eW()})}));let h=new V({request:u,page:e.page});if((t=await eF(u,()=>"/middleware"===e.page||"/src/middleware"===e.page?eU().trace(y.execute,{spanName:`middleware ${u.method} ${u.nextUrl.pathname}`,attributes:{"http.target":u.nextUrl.pathname,"http.method":u.method}},()=>eH.wrap(eV,{req:u,renderOpts:{onUpdateCookies:e=>{s=e},previewProps:eW()}},()=>e.handler(u,h))):e.handler(u,h)))&&!(t instanceof Response))throw TypeError("Expected an instance of Response to be returned");t&&s&&t.headers.set("set-cookie",s);let d=null==t?void 0:t.headers.get("x-middleware-rewrite");if(t&&d&&!i){let r=new Z(d,{forceLocale:!0,headers:e.request.headers,nextConfig:e.request.nextConfig});r.host===u.nextUrl.host&&(r.buildId=a||r.buildId,t.headers.set("x-middleware-rewrite",String(r)));let s=el(String(r),String(n));o&&t.headers.set("x-nextjs-rewrite",s)}let p=null==t?void 0:t.headers.get("Location");if(t&&p&&!i){let r=new Z(p,{forceLocale:!1,headers:e.request.headers,nextConfig:e.request.nextConfig});t=new Response(t.body,t),r.host===u.nextUrl.host&&(r.buildId=a||r.buildId,t.headers.set("Location",String(r))),o&&(t.headers.delete("Location"),t.headers.set("x-nextjs-redirect",el(String(r),String(n))))}let f=t||eo.next(),g=f.headers.get("x-middleware-override-headers"),m=[];if(g){for(let[e,t]of c)f.headers.set(`x-middleware-request-${e}`,t),m.push(e);m.length>0&&f.headers.set("x-middleware-override-headers",g+","+m.join(","))}return{response:f,waitUntil:Promise.all(h[q]),fetchMetrics:u.fetchMetrics}}function eX(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&0>t.indexOf(s)&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,s=Object.getOwnPropertySymbols(e);i<s.length;i++)0>t.indexOf(s[i])&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(r[s[i]]=e[s[i]]);return r}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;let eY=e=>e?(...t)=>e(...t):(...e)=>fetch(...e);class eQ extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class eZ extends eQ{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class e0 extends eQ{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class e1 extends eQ{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(w||(w={}));class e2{constructor(e,{headers:t={},customFetch:r,region:s=w.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=eY(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){var t,r,s,i;return t=this,r=arguments,s=void 0,i=function*(e,t={}){var r;let s,i;try{let n;let{headers:a,method:o,body:l,signal:c,timeout:u}=t,h={},{region:d}=t;d||(d=this.region);let p=new URL(`${this.url}/${e}`);d&&"any"!==d&&(h["x-region"]=d,p.searchParams.set("forceFunctionRegion",d)),l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?"undefined"!=typeof Blob&&l instanceof Blob||l instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",n=l):"string"==typeof l?(h["Content-Type"]="text/plain",n=l):"undefined"!=typeof FormData&&l instanceof FormData?n=l:(h["Content-Type"]="application/json",n=JSON.stringify(l)):!l||"string"==typeof l||"undefined"!=typeof Blob&&l instanceof Blob||l instanceof ArrayBuffer||"undefined"!=typeof FormData&&l instanceof FormData?n=l:n=JSON.stringify(l);let f=c;u&&(i=new AbortController,s=setTimeout(()=>i.abort(),u),c?(f=i.signal,c.addEventListener("abort",()=>i.abort())):f=i.signal);let g=yield this.fetch(p.toString(),{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),a),body:n,signal:f}).catch(e=>{throw new eZ(e)}),m=g.headers.get("x-relay-error");if(m&&"true"===m)throw new e0(g);if(!g.ok)throw new e1(g);let b=(null!==(r=g.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return{data:"application/json"===b?yield g.json():"application/octet-stream"===b||"application/pdf"===b?yield g.blob():"text/event-stream"===b?g:"multipart/form-data"===b?yield g.formData():yield g.text(),error:null,response:g}}catch(e){return{data:null,error:e,response:e instanceof e1||e instanceof e0?e.context:void 0}}finally{s&&clearTimeout(s)}},new(s||(s=Promise))(function(e,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof s?r:new s(function(e){e(r)})).then(a,o)}l((i=i.apply(t,r||[])).next())})}}let e3=e=>Math.min(1e3*2**e,3e4),e4=[520,503],e6=["GET","HEAD","OPTIONS"];var e5=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function e8(e,t){return new Promise(r=>{if(null==t?void 0:t.aborted){r();return}let s=setTimeout(()=>{null==t||t.removeEventListener("abort",i),r()},e);function i(){clearTimeout(s),r()}null==t||t.addEventListener("abort",i)})}var e9=class{constructor(e){var t,r,s,i,n;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,this.shouldStripNulls=null!==(s=e.shouldStripNulls)&&void 0!==s&&s,this.urlLengthLimit=null!==(i=e.urlLengthLimit)&&void 0!==i?i:8e3,this.retryEnabled=null===(n=e.retry)||void 0===n||n,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if("text/csv"===this.headers.get("Accept"))throw Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var r=this;if(void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let e=this.headers.get("Accept");"application/vnd.pgrst.object+json"===e?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):e&&"application/json"!==e||this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let s=this.fetch,i=(async()=>{let e=0;for(;;){var t,i,n,a,o;let l;let c={};r.headers.forEach((e,t)=>{c[t]=e}),e>0&&(c["X-Retry-Count"]=String(e));try{l=await s(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body,(e,t)=>"bigint"==typeof t?t.toString():t),signal:r.signal})}catch(t){if((null==t?void 0:t.name)==="AbortError"||(null==t?void 0:t.code)==="ABORT_ERR"||!e6.includes(r.method))throw t;if(r.retryEnabled&&e<3){let t=e3(e);e++,await e8(t,r.signal);continue}throw t}if(t=r.method,i=l.status,n=e,r.retryEnabled&&!(n>=3)&&e6.includes(t)&&e4.includes(i)){let t=null!==(a=null===(o=l.headers)||void 0===o?void 0:o.get("Retry-After"))&&void 0!==a?a:null,s=null!==t?1e3*Math.max(0,parseInt(t,10)||0):e3(e);await l.text(),e++,await e8(s,r.signal);continue}return await r.processResponse(l)}})();return this.shouldThrowOnError||(i=i.catch(e=>{var t,r,s,i,n,a;let o="",l="",c="",u=null==e?void 0:e.cause;if(u){let t=null!==(r=null==u?void 0:u.message)&&void 0!==r?r:"",a=null!==(s=null==u?void 0:u.code)&&void 0!==s?s:"";o=`${null!==(i=null==e?void 0:e.name)&&void 0!==i?i:"FetchError"}: ${null==e?void 0:e.message}

Caused by: ${null!==(n=null==u?void 0:u.name)&&void 0!==n?n:"Error"}: ${t}`,a&&(o+=` (${a})`),(null==u?void 0:u.stack)&&(o+=`
${u.stack}`)}else o=null!==(a=null==e?void 0:e.stack)&&void 0!==a?a:"";let h=this.url.toString().length;return(null==e?void 0:e.name)==="AbortError"||(null==e?void 0:e.code)==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",h>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${h} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((null==u?void 0:u.name)==="HeadersOverflowError"||(null==u?void 0:u.code)==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",h>this.urlLengthLimit&&(l+=`. Your request URL is ${h} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:o,hint:l,code:c},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}async processResponse(e){var t,r,s;let i=null,n=null,a=null,o=e.status,l=e.statusText;if(e.ok){if("HEAD"!==this.method){let t=await e.text();if(""===t);else if("text/csv"===this.headers.get("Accept"))n=t;else if(this.headers.get("Accept")&&(null===(s=this.headers.get("Accept"))||void 0===s?void 0:s.includes("application/vnd.pgrst.plan+text")))n=t;else try{n=JSON.parse(t)}catch(e){if(i={message:t},n=null,this.shouldThrowOnError)throw new e5({message:t,details:"",hint:"",code:""})}}let c=null===(t=this.headers.get("Prefer"))||void 0===t?void 0:t.match(/count=(exact|planned|estimated)/),u=null===(r=e.headers.get("content-range"))||void 0===r?void 0:r.split("/");c&&u&&u.length>1&&(a=parseInt(u[1])),this.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(i={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,a=null,o=406,l="Not Acceptable"):n=1===n.length?n[0]:null)}else{let t=await e.text();try{i=JSON.parse(t),Array.isArray(i)&&404===e.status&&(n=[],i=null,o=200,l="OK")}catch(r){404===e.status&&""===t?(o=204,l="No Content"):i={message:t}}if(i&&this.shouldThrowOnError)throw new e5(i)}return{success:null===i,error:i,data:n,count:a,status:o,statusText:l}}returns(){return this}overrideTypes(){return this}},e7=class extends e9{select(e){let t=!1,r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){let i=void 0===s?"offset":`${s}.offset`,n=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){var a;let o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!==(a=this.headers.get("Accept"))&&void 0!==a?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};let te=RegExp("[,()]");var tt=class extends e7{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&te.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&te.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";"plain"===s?i="pl":"phrase"===s?i="ph":"websearch"===s&&(i="w");let n=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>void 0!==t).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},tr=class{constructor(e,{headers:t={},schema:r,fetch:s,urlLengthLimit:i=8e3,retry:n}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s,this.urlLengthLimit=i,this.retry=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:s}=null!=t?t:{},i=!1,n=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:a,headers:o}=this.cloneRequestState();return a.searchParams.set("select",n),s&&o.append("Prefer",`count=${s}`),new tt({method:r?"HEAD":"GET",url:a,headers:o,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:r=!0}={}){var s;let{url:i,headers:n}=this.cloneRequestState();if(t&&n.append("Prefer",`count=${t}`),r||n.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);i.searchParams.set("columns",e.join(","))}}return new tt({method:"POST",url:i,headers:n,schema:this.schema,body:e,fetch:null!==(s=this.fetch)&&void 0!==s?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var n;let{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&o.append("Prefer",`count=${s}`),i||o.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set("columns",e.join(","))}}return new tt({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){var r;let{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new tt({method:"PATCH",url:s,headers:i,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){var t;let{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new tt({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function ts(e){return(ts="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ti(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function tn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ti(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=ts(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=ts(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==ts(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ti(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var ta=class e{constructor(e,{headers:t={},schema:r,fetch:s,timeout:i,urlLengthLimit:n=8e3,retry:a}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.urlLengthLimit=n;let o=null!=s?s:globalThis.fetch;void 0!==i&&i>0?this.fetch=(e,t)=>{let r=new AbortController,s=setTimeout(()=>r.abort(),i),n=null==t?void 0:t.signal;if(n){if(n.aborted)return clearTimeout(s),o(e,t);let i=()=>{clearTimeout(s),r.abort()};return n.addEventListener("abort",i,{once:!0}),o(e,tn(tn({},t),{},{signal:r.signal})).finally(()=>{clearTimeout(s),n.removeEventListener("abort",i)})}return o(e,tn(tn({},t),{},{signal:r.signal})).finally(()=>clearTimeout(s))}:this.fetch=o,this.retry=a}from(e){if(!e||"string"!=typeof e||""===e.trim())throw Error("Invalid relation name: relation must be a non-empty string.");return new tr(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,t={},{head:r=!1,get:s=!1,count:i}={}){var n;let a,o;let l=new URL(`${this.url}/rpc/${e}`),c=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(c)),u=r&&Object.values(t).some(c);u?(a="POST",o=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{l.searchParams.append(e,t)})):(a="POST",o=t);let h=new Headers(this.headers);return u?h.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&h.set("Prefer",`count=${i}`),new tt({method:a,url:l,headers:h,schema:this.schemaName,body:o,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class to{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",wsConstructor:WebSocket};let t=globalThis;if("undefined"!=typeof globalThis&&void 0!==t.WebSocket)return{type:"native",wsConstructor:t.WebSocket};let s=void 0!==r.g?r.g:void 0;if(s&&void 0!==s.WebSocket)return{type:"native",wsConstructor:s.WebSocket};if("undefined"!=typeof globalThis&&void 0!==t.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&t.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let i=globalThis.process;if(i){let e=i.versions;if(e&&e.node){let t=parseInt(e.node.replace(/^v/,"").split(".")[0]);return t>=22?void 0!==globalThis.WebSocket?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${t} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${t} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`

Suggested solution: ${e.workaround}`),Error(t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}let tl="2.0.0",tc={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},tu={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},th={connecting:"connecting",closing:"closing",closed:"closed"};class td{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){return e.event!==this.BROADCAST_EVENT||e.payload instanceof ArrayBuffer||"string"!=typeof e.payload.event?t(JSON.stringify([e.join_ref,e.ref,e.topic,e.event,e.payload])):t(this._binaryEncodeUserBroadcastPush(e))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;let s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;let s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:{},i=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,t,r){let s=e.topic,i=null!==(p=e.ref)&&void 0!==p?p:"",n=null!==(f=e.join_ref)&&void 0!==f?f:"",a=e.payload.event,o=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},l=0===Object.keys(o).length?"":JSON.stringify(o);if(n.length>255)throw Error(`joinRef length ${n.length} exceeds maximum of 255`);if(i.length>255)throw Error(`ref length ${i.length} exceeds maximum of 255`);if(s.length>255)throw Error(`topic length ${s.length} exceeds maximum of 255`);if(a.length>255)throw Error(`userEvent length ${a.length} exceeds maximum of 255`);if(l.length>255)throw Error(`metadata length ${l.length} exceeds maximum of 255`);let c=this.USER_BROADCAST_PUSH_META_LENGTH+n.length+i.length+s.length+a.length+l.length,u=new ArrayBuffer(this.HEADER_LENGTH+c),h=new DataView(u),d=0;h.setUint8(d++,this.KINDS.userBroadcastPush),h.setUint8(d++,n.length),h.setUint8(d++,i.length),h.setUint8(d++,s.length),h.setUint8(d++,a.length),h.setUint8(d++,l.length),h.setUint8(d++,t),Array.from(n,e=>h.setUint8(d++,e.charCodeAt(0))),Array.from(i,e=>h.setUint8(d++,e.charCodeAt(0))),Array.from(s,e=>h.setUint8(d++,e.charCodeAt(0))),Array.from(a,e=>h.setUint8(d++,e.charCodeAt(0))),Array.from(l,e=>h.setUint8(d++,e.charCodeAt(0)));var p,f,g=new Uint8Array(u.byteLength+r.byteLength);return g.set(new Uint8Array(u),0),g.set(new Uint8Array(r),u.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if("string"==typeof e){let[r,s,i,n,a]=JSON.parse(e);return t({join_ref:r,ref:s,topic:i,event:n,payload:a})}return t({})}_binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s)}_decodeUserBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+4,l=r.decode(e.slice(o,o+s));o+=s;let c=r.decode(e.slice(o,o+i));o+=i;let u=r.decode(e.slice(o,o+n));o+=n;let h=e.slice(o,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(r.decode(h)):h,p={type:this.BROADCAST_EVENT,event:c,payload:d};return n>0&&(p.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(v||(v={}));let tp=(e,t,r={})=>{var s;let i=null!==(s=r.skipTypes)&&void 0!==s?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=tf(s,e,t,i),r),{}):{}},tf=(e,t,r,s)=>{let i=t.find(t=>t.name===e),n=null==i?void 0:i.type,a=r[e];return n&&!s.includes(n)?tg(n,a):tm(a)},tg=(e,t)=>{if("_"===e.charAt(0))return tv(t,e.slice(1,e.length));switch(e){case v.bool:return tb(t);case v.float4:case v.float8:case v.int2:case v.int4:case v.int8:case v.numeric:case v.oid:return ty(t);case v.json:case v.jsonb:return tw(t);case v.timestamp:return t_(t);case v.abstime:case v.date:case v.daterange:case v.int4range:case v.int8range:case v.money:case v.reltime:case v.text:case v.time:case v.timestamptz:case v.timetz:case v.tsrange:case v.tstzrange:default:return tm(t)}},tm=e=>e,tb=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},ty=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},tw=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},tv=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s;let i=e.slice(1,r);try{s=JSON.parse("["+i+"]")}catch(e){s=i?i.split(","):[]}return s.map(e=>tg(t,e))}return e},t_=e=>"string"==typeof e?e.replace(" ","T"):e,tk=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};var tS=e=>"function"==typeof e?e:function(){return e},tT="undefined"!=typeof window?window:null,tE=("undefined"!=typeof self?self:null)||tT||globalThis,tR={connecting:0,open:1,closing:2,closed:3},tO={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},tA={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},tP={longpoll:"longpoll",websocket:"websocket"},tC={complete:4},tx="base64url.bearer.phx.",tI=class{constructor(e,t,r,s){this.channel=e,this.event=t,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:r}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},tj=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},tN=class{constructor(e,t,r){this.state=tO.closed,this.topic=e,this.params=tS(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new tI(this,tA.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new tj(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=tO.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this.joinPush.receive("error",e=>{this.state=tO.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=tO.closed,this.socket.remove(this)}),this.onError(e=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=tO.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new tI(this,tA.leave,tS({}),this.timeout).send(),this.state=tO.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(tA.reply,(e,t)=>{this.trigger(this.replyEventName(t),e)})}join(e=this.timeout){if(!this.joinedOnce)return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush;throw Error("tried to join multiple times. 'join' can only be called a single time per channel instance")}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=tO.closed,this.bindings=[]}onClose(e){this.on(tA.close,e)}onError(e){return this.on(tA.error,t=>e(t))}on(e,t){let r=this.bindingRef++;return this.bindings.push({event:e,ref:r,callback:t}),r}off(e,t){this.bindings=this.bindings.filter(r=>!(r.event===e&&(void 0===t||t===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,r=this.timeout){if(t=t||{},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new tI(this,e,function(){return t},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=tO.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(tA.close,"leave")},r=new tI(this,tA.leave,tS({}),e);return r.receive("ok",()=>t()).receive("timeout",()=>t()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(e,t,r){return t}filterBindings(e,t,r){return!0}isMember(e,t,r,s){return this.topic===e&&(!s||s===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:r,joinRef:s}),!1))}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=tO.joining,this.joinPush.resend(e))}trigger(e,t,r,s){let i=this.onMessage(e,t,r,s);if(t&&!i)throw Error("channel onMessage callbacks must return the payload, modified or unmodified");let n=this.bindings.filter(s=>s.event===e&&this.filterBindings(s,t,r));for(let e=0;e<n.length;e++)n[e].callback(i,r,s||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===tO.closed}isErrored(){return this.state===tO.errored}isJoined(){return this.state===tO.joined}isJoining(){return this.state===tO.joining}isLeaving(){return this.state===tO.leaving}},t$=class{static request(e,t,r,s,i,n,a){if(tE.XDomainRequest){let r=new tE.XDomainRequest;return this.xdomainRequest(r,e,t,s,i,n,a)}if(tE.XMLHttpRequest){let o=new tE.XMLHttpRequest;return this.xhrRequest(o,e,t,r,s,i,n,a)}if(tE.fetch&&tE.AbortController)return this.fetchRequest(e,t,r,s,i,n,a);throw Error("No suitable XMLHttpRequest implementation found")}static fetchRequest(e,t,r,s,i,n,a){let o={method:e,headers:r,body:s},l=null;return i&&(l=new AbortController,setTimeout(()=>l.abort(),i),o.signal=l.signal),tE.fetch(t,o).then(e=>e.text()).then(e=>this.parseJSON(e)).then(e=>a&&a(e)).catch(e=>{"AbortError"===e.name&&n?n():a&&a(null)}),l}static xdomainRequest(e,t,r,s,i,n,a){return e.timeout=i,e.open(t,r),e.onload=()=>{let t=this.parseJSON(e.responseText);a&&a(t)},n&&(e.ontimeout=n),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,r,s,i,n,a,o){for(let[i,a]of(e.open(t,r,!0),e.timeout=n,Object.entries(s)))e.setRequestHeader(i,a);return e.onerror=()=>o&&o(null),e.onreadystatechange=()=>{e.readyState===tC.complete&&o&&o(this.parseJSON(e.responseText))},a&&(e.ontimeout=a),e.send(i),e}static parseJSON(e){if(!e||""===e)return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let r=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let i=t?`${t}[${s}]`:s,n=e[s];"object"==typeof n?r.push(this.serialize(n,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(n))}return r.join("&")}static appendParams(e,t){if(0===Object.keys(t).length)return e;let r=e.match(/\?/)?"&":"?";return`${e}${r}${this.serialize(t)}`}},tL=e=>{let t="",r=new Uint8Array(e),s=r.byteLength;for(let e=0;e<s;e++)t+=String.fromCharCode(r[e]);return btoa(t)},tD=class{constructor(e,t){t&&2===t.length&&t[1].startsWith(tx)&&(this.authToken=atob(t[1].slice(tx.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=tR.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(RegExp("(.*)/"+tP.websocket),"$1/"+tP.longpoll)}endpointURL(){return t$.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=tR.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===tR.open||this.readyState===tR.connecting}poll(){let e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:r,messages:s}=e;if(410===t&&null!==this.token){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=r}else t=0;switch(t){case 200:s.forEach(e=>{setTimeout(()=>this.onmessage({data:e}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=tR.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw Error(`unhandled poll status ${t}`)}})}send(e){"string"!=typeof e&&(e=tL(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join("\n"),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,e&&200===e.status?this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]):(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1))})}close(e,t,r){for(let e of this.reqs)e.abort();this.readyState=tR.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,"undefined"!=typeof CloseEvent?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,r,s,i){let n;n=t$.request(e,this.endpointURL(),t,r,this.timeout,()=>{this.reqs.delete(n),s()},e=>{this.reqs.delete(n),this.isActive()&&i(e)}),this.reqs.add(n)}},tU=class e{constructor(t,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,t=>{let{onJoin:r,onLeave:s,onSync:i}=this.caller;this.joinRef=this.channel.joinRef(),this.state=e.syncState(this.state,t,r,s),this.pendingDiffs.forEach(t=>{this.state=e.syncDiff(this.state,t,r,s)}),this.pendingDiffs=[],i()}),this.channel.on(s.diff,t=>{let{onJoin:r,onLeave:s,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,r,s),i())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(t){return e.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,t,r,s){let i=this.clone(e),n={},a={};return this.map(i,(e,r)=>{t[e]||(a[e]=r)}),this.map(t,(e,t)=>{let r=i[e];if(r){let s=t.metas.map(e=>e.phx_ref),i=r.metas.map(e=>e.phx_ref),o=t.metas.filter(e=>0>i.indexOf(e.phx_ref)),l=r.metas.filter(e=>0>s.indexOf(e.phx_ref));o.length>0&&(n[e]=t,n[e].metas=o),l.length>0&&(a[e]=this.clone(r),a[e].metas=l)}else n[e]=t}),this.syncDiff(i,{joins:n,leaves:a},r,s)}static syncDiff(e,t,r,s){let{joins:i,leaves:n}=this.clone(t);return r||(r=function(){}),s||(s=function(){}),this.map(i,(t,s)=>{let i=e[t];if(e[t]=this.clone(s),i){let r=e[t].metas.map(e=>e.phx_ref),s=i.metas.filter(e=>0>r.indexOf(e.phx_ref));e[t].metas.unshift(...s)}r(t,i,s)}),this.map(n,(t,r)=>{let i=e[t];if(!i)return;let n=r.metas.map(e=>e.phx_ref);i.metas=i.metas.filter(e=>0>n.indexOf(e.phx_ref)),s(t,i,r),0===i.metas.length&&delete e[t]}),e}static list(e,t){return t||(t=function(e,t){return t}),this.map(e,(e,r)=>t(e,r))}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static clone(e){return JSON.parse(JSON.stringify(e))}},tM={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){return e.payload.constructor===ArrayBuffer?t(this.binaryEncode(e)):t(JSON.stringify([e.join_ref,e.ref,e.topic,e.event,e.payload]))},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[r,s,i,n,a]=JSON.parse(e);return t({join_ref:r,ref:s,topic:i,event:n,payload:a})}},binaryEncode(e){let{join_ref:t,ref:r,event:s,topic:i,payload:n}=e,a=this.META_LENGTH+t.length+r.length+i.length+s.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),l=new DataView(o),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,t.length),l.setUint8(c++,r.length),l.setUint8(c++,i.length),l.setUint8(c++,s.length),Array.from(t,e=>l.setUint8(c++,e.charCodeAt(0))),Array.from(r,e=>l.setUint8(c++,e.charCodeAt(0))),Array.from(i,e=>l.setUint8(c++,e.charCodeAt(0))),Array.from(s,e=>l.setUint8(c++,e.charCodeAt(0)));var u=new Uint8Array(o.byteLength+n.byteLength);return u.set(new Uint8Array(o),0),u.set(new Uint8Array(n),o.byteLength),u.buffer},binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(e,t,s);case this.KINDS.reply:return this.decodeReply(e,t,s);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,s)}},decodePush(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=t.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(e.slice(a,a+s));a+=s;let l=r.decode(e.slice(a,a+i));a+=i;let c=r.decode(e.slice(a,a+n));return a+=n,{join_ref:o,ref:null,topic:l,event:c,payload:e.slice(a,e.byteLength)}},decodeReply(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(e.slice(o,o+s));o+=s;let c=r.decode(e.slice(o,o+i));o+=i;let u=r.decode(e.slice(o,o+n));o+=n;let h=r.decode(e.slice(o,o+a));o+=a;let d=e.slice(o,e.byteLength);return{join_ref:l,ref:c,topic:u,event:tA.reply,payload:{status:h,response:d}}},decodeBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=this.HEADER_LENGTH+2,a=r.decode(e.slice(n,n+s));n+=s;let o=r.decode(e.slice(n,n+i));return n+=i,{join_ref:null,ref:null,topic:a,event:o,payload:e.slice(n,e.byteLength)}}},tB=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||1e4,this.transport=t.transport||tE.WebSocket||tD,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=tE&&tE.sessionStorage}catch{}this.sessionStore=t.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=tM.encode.bind(tM),this.defaultDecoder=tM.decode.bind(tM),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==tD?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;tT&&tT.addEventListener&&(tT.addEventListener("pagehide",e=>{this.conn&&(this.disconnect(),s=this.connectClock)}),tT.addEventListener("pageshow",e=>{s===this.connectClock&&(s=null,this.connect())}),tT.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this.pageHidden=!0:(this.pageHidden=!1,this.isConnected()||this.closeWasClean||this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,r)=>{console.log(`${e}: ${t}`,r)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=tS(t.params||{}),this.endPoint=`${e}/${tP.websocket}`,this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new tj(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return tD}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=t$.appendParams(t$.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==e.charAt(0)?e:"/"===e.charAt(1)?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,r)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=tS(e)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==tD?this.connectWithFallback(tD,this.longPollFallbackMs):this.transportConnect())}log(e,t,r){this.logger&&this.logger(e,t,r)}hasLogger(){return null!==this.logger}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let s=this.onMessage(i=>{i.ref===t&&(this.off([s]),e(Date.now()-r))});return!0}transportName(e){return e===tD?"LongPoll":e.name}transportConnect(){let e;this.connectClock++,this.closeWasClean=!1,this.authToken&&(e=["phoenix",`${tx}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){let r,s;clearTimeout(this.fallbackTimer);let i=!1,n=!0,a=this.transportName(e),o=t=>{this.log("transport",`falling back to ${a}...`,t),this.off([r,s]),n=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,t),s=this.onError(e=>{this.log("transport","error",e),n&&!i&&(clearTimeout(this.fallbackTimer),o(e))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(i=!0,!n){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t}`,"true"),this.log("transport",`established ${t} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,t),this.ping(e=>{this.log("transport","connected to primary after",e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),1e3,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,r){if(!this.conn)return e&&e();let s=this.conn;this.waitForBufferDone(s,()=>{t?s.close(t,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,r=1){if(5===r||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,r+1)},150*r)}waitForSocketClosed(e,t,r=1){if(5===r||e.readyState===tR.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,r+1)},150*r)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport","error",e);let t=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",e,t,r),(t===this.transport||r>0)&&this.triggerChanError(e)}triggerChanError(e){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(tA.error,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case tR.connecting:return"connecting";case tR.open:return"open";case tR.closing:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([t])=>-1===e.indexOf(t))}channel(e,t={}){let r=new tN(e,t,this);return this.channels.push(r),r}push(e){if(this.hasLogger()){let{topic:t,event:r,payload:s,ref:i,join_ref:n}=e;this.log("push",`${t} ${r} (${n}, ${i})`,s)}this.isConnected()?this.encode(e,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(e,e=>this.conn.send(e)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:r,payload:s,ref:i,join_ref:n}=e;if(i&&i===this.pendingHeartbeatRef){let e=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback("ok"===s.status?"ok":"error",e)}catch(e){this.log("error","error in heartbeat callback",e)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${s.status||""} ${t} ${r} ${i&&"("+i+")"||""}`.trim(),s);for(let e=0;e<this.channels.length;e++){let a=this.channels[e];a.isMember(t,r,s,n)&&a.trigger(r,s,i,n)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([r,s])=>{try{s(...t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t.isJoined()||t.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};class tq{constructor(e,t){let r=function(e){return(null==e?void 0:e.events)&&{events:e.events}}(t);this.presence=new tU(e.getChannel(),r),this.presence.onJoin((t,r,s)=>{let i=tq.onJoinPayload(t,r,s);e.getChannel().trigger("presence",i)}),this.presence.onLeave((t,r,s)=>{let i=tq.onLeavePayload(t,r,s);e.getChannel().trigger("presence",i)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return tq.transformState(this.presence.state)}static transformState(e){return Object.getOwnPropertyNames(e=JSON.parse(JSON.stringify(e))).reduce((t,r)=>{let s=e[r];return t[r]=tH(s),t},{})}static onJoinPayload(e,t,r){return{event:"join",key:e,currentPresences:tV(t),newPresences:tH(r)}}static onLeavePayload(e,t,r){return{event:"leave",key:e,currentPresences:tV(t),leftPresences:tH(r)}}}function tH(e){return e.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function tV(e){return(null==e?void 0:e.metas)?tH(e):[]}!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(_||(_={}));class tW{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new tq(this.channel.channelAdapter,t)}}class tG{constructor(e,t,r){let s={config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config)};this.channel=e.getSocket().channel(t,s),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,t){return this.channel.on(e,t)}off(e,t){this.channel.off(e,t)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,t,r){let s;try{s=this.channel.push(e,t,r)}catch(t){throw Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>100){let e=this.channel.pushBuffer.shift();e.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload())}return s}updateJoinPayload(e){let t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===tc.joined}isJoined(){return this.state===tc.joined}isJoining(){return this.state===tc.joining}isClosed(){return this.state===tc.closed}isLeaving(){return this.state===tc.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(k||(k={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(S||(S={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(T||(T={}));class tK{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,t={config:{}},r){var s,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.channelAdapter=new tG(this.socket.socketAdapter,e,this.params),this.presence=new tW(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=tk(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(null===(i=null===(s=this.params.config)||void 0===s?void 0:s.broadcast)||void 0===i?void 0:i.replay))throw Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,t=this.timeout){var r,s,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:n,presence:a,private:o}}=this.params,l=null!==(s=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==s?s:[],c=!!this.bindings[S.PRESENCE]&&this.bindings[S.PRESENCE].length>0||(null===(i=this.params.config.presence)||void 0===i?void 0:i.enabled)===!0,u={},h={broadcast:n,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:l,private:o};this.socket.accessTokenValue&&(u.access_token=this.socket.accessTokenValue),this._onError(t=>{null==e||e(T.CHANNEL_ERROR,function(e){if(e instanceof Error)return e;if("string"==typeof e)return Error(e);if(e&&"object"==typeof e){if("number"==typeof e.code){let t="string"==typeof e.reason&&e.reason?` (${e.reason})`:"";return Error(`socket closed: ${e.code}${t}`,{cause:e})}return Error("channel error: transport failure",{cause:e})}return Error("channel error: connection lost")}(t))}),this._onClose(()=>null==e?void 0:e(T.CLOSED)),this.updateJoinPayload(Object.assign({config:h},u)),this._updateFilterMessage(),this.channelAdapter.subscribe(t).receive("ok",async({postgres_changes:t})=>{if(this.socket._isManualToken()||this.socket.setAuth(),void 0===t){null==e||e(T.SUBSCRIBED);return}this._updatePostgresBindings(t,e)}).receive("error",t=>{this.state=tc.errored;let r=Object.values(t).join(", ")||"error";null==e||e(T.CHANNEL_ERROR,Error(r,{cause:t}))}).receive("timeout",()=>{null==e||e(T.TIMED_OUT)})}return this}_updatePostgresBindings(e,t){var r;let s=this.bindings.postgres_changes,i=null!==(r=null==s?void 0:s.length)&&void 0!==r?r:0,n=[];for(let r=0;r<i;r++){let i=s[r],{filter:{event:a,schema:o,table:l,filter:c}}=i,u=e&&e[r];if(u&&u.event===a&&tK.isFilterValueEqual(u.schema,o)&&tK.isFilterValueEqual(u.table,l)&&tK.isFilterValueEqual(u.filter,c))n.push(Object.assign(Object.assign({},i),{id:u.id}));else{this.unsubscribe(),this.state=tc.errored,null==t||t(T.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=n,this.state!=tc.errored&&t&&t(T.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){let s=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===S.PRESENCE||e===S.POSTGRES_CHANGES;if(s&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,t,r)}async httpSend(e,t,r={}){var s;if(null==t)return Promise.reject(Error("Payload is required for httpSend()"));let i=t instanceof ArrayBuffer||ArrayBuffer.isView(t),n={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":i?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(n.Authorization=`Bearer ${this.socket.accessTokenValue}`);let a=new URL(this.broadcastEndpointURL);a.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`,this.private&&a.searchParams.set("private","true");let o={method:"POST",headers:n,body:i?t:JSON.stringify(t)},l=await this._fetchWithTimeout(a.toString(),o,null!==(s=r.timeout)&&void 0!==s?s:this.timeout);if(202===l.status)return{success:!0};let c=l.statusText;try{let e=await l.json();c=e.error||e.message||c}catch(e){}return Promise.reject(Error(c))}async send(e,t={}){var r,s;if(this.channelAdapter.canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,i,n;let a=this.channelAdapter.push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(n=null===(i=null===(s=this.params)||void 0===s?void 0:s.config)||void 0===i?void 0:i.broadcast)||void 0===n?void 0:n.ack)||r("ok"),a.receive("ok",()=>r("ok")),a.receive("error",()=>r("error")),a.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:n}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:n,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);return await (null===(s=e.body)||void 0===s?void 0:s.cancel()),e.ok?"ok":"error"}catch(e){if(e instanceof Error&&"AbortError"===e.name)return"timed out";return"error"}}}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(t=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>t("ok")).receive("timeout",()=>t("timed out")).receive("error",()=>t("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,t,r){let s=new AbortController,i=setTimeout(()=>s.abort(),r),n=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),n}_on(e,t,r){let s=e.toLocaleLowerCase(),i=this.channelAdapter.on(e,r),n={type:s,filter:t,callback:r,ref:i};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,t,r)=>{var s,i,n,a,o,l,c;let u=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(u,r))return!1;let h=null===(s=this.bindings[u])||void 0===s?void 0:s.find(t=>t.ref===e.ref);if(!h)return!0;if(!["broadcast","presence","postgres_changes"].includes(u))return h.type.toLocaleLowerCase()===u;if("id"in h){let e=h.id,r=null===(i=h.filter)||void 0===i?void 0:i.event;return e&&(null===(n=t.ids)||void 0===n?void 0:n.includes(e))&&("*"===r||(null==r?void 0:r.toLocaleLowerCase())===(null===(a=t.data)||void 0===a?void 0:a.type.toLocaleLowerCase()))}{let e=null===(l=null===(o=null==h?void 0:h.filter)||void 0===o?void 0:o.event)||void 0===l?void 0:l.toLocaleLowerCase();return"*"===e||e===(null===(c=null==t?void 0:t.event)||void 0===c?void 0:c.toLocaleLowerCase())}})}_notThisChannelEvent(e,t){let{close:r,error:s,leave:i,join:n}=tu;return t&&[r,s,i,n].includes(e)&&t!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,t,r)=>{if("object"==typeof t&&"ids"in t){let e=t.data,{schema:r,table:s,commit_timestamp:i,type:n,errors:a}=e;return Object.assign(Object.assign({},{schema:r,table:s,commit_timestamp:i,eventType:n,new:{},old:{},errors:a}),this._getPayloadRecords(e))}return t})}copyBindings(e){if(this.joinedOnce)throw Error("cannot copy bindings into joined channel");for(let t in e.bindings)for(let r of e.bindings[t])this._on(r.type,r.filter,r.callback)}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=tp(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=tp(e.columns,e.old_record)),t}}class tF{constructor(e,t){this.socket=new tB(e,t)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,t,r,s=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),s),this.socket.disconnect(()=>{e(),i("ok")},t,r)})}push(e){this.socket.push(e)}log(e,t,r){this.socket.log(e,t,r)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==th.connecting}isDisconnecting(){return this.socket.connectionState()==th.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}let tz={HEARTBEAT_INTERVAL:25e3},tJ=[1e3,2e3,5e3,1e4],tX=`
  addEventListener("message", (e) => {
    if (e.data.event === "start") {
      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
    }
  });`;class tY{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,t){var r;if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new td,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey;let s=this._initializeOptions(t);this.socketAdapter=new tF(e,s),this.httpEndpoint=tk(e),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(t){let e=t.message;if(e.includes("Node.js"))throw Error(`${e}

To use Realtime in Node.js, you need to provide a WebSocket implementation:

Option 1: Use Node.js 22+ which has native WebSocket support
Option 2: Install and provide the "ws" package:

  npm install ws

  import ws from "ws"
  const client = new RealtimeClient(url, {
    ...options,
    transport: ws
  })`);throw Error(`WebSocket not available: ${e}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){return(this._cancelPendingDisconnect(),this.isDisconnecting())?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,t)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return"ok"===t&&e.teardown(),t}async removeAllChannels(){let e=this.channels.map(async e=>{let t=await e.unsubscribe();return e.teardown(),t}),t=await Promise.all(e);return await this.disconnect(),t}log(e,t,r){this.socketAdapter.log(e,t,r)}connectionState(){return this.socketAdapter.connectionState()||th.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,t={config:{}}){let r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{let r=new tK(`realtime:${e}`,t,this);return this._cancelPendingDisconnect(),this.channels.push(r),r}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic),0===this.channels.length&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),0===this._disconnectOnEmptyChannelsAfterMs){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,0===this.channels.length&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){null!==this._pendingDisconnectTimer&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let t;let r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{let r={access_token:t,version:"realtime-js/2.108.0"};t&&e.updateJoinPayload(r),e.joinedOnce&&e.channelAdapter.isJoined()&&e.channelAdapter.push(tu.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(e=>{this.log("error","error waiting for auth on connect",e)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(t,r)=>{"sent"==t&&this._setAuthSafely(),e&&e(t,r)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([tX],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_initializeOptions(e){var t,r,s,i,n,a,o,l,c,u,h,d;let p,f;this.worker=null!==(t=null==e?void 0:e.worker)&&void 0!==t&&t,this.accessToken=null!==(r=null==e?void 0:e.accessToken)&&void 0!==r?r:null;let g={};g.timeout=null!==(s=null==e?void 0:e.timeout)&&void 0!==s?s:1e4,g.heartbeatIntervalMs=null!==(i=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==i?i:tz.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=null!==(n=null==e?void 0:e.disconnectOnEmptyChannelsAfterMs)&&void 0!==n?n:2*(null!==(a=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==a?a:tz.HEARTBEAT_INTERVAL),g.transport=null!==(o=null==e?void 0:e.transport)&&void 0!==o?o:to.getWebSocketConstructor(),g.params=null==e?void 0:e.params,g.logger=null==e?void 0:e.logger,g.heartbeatCallback=this._wrapHeartbeatCallback(null==e?void 0:e.heartbeatCallback),g.sessionStorage=null!==(l=null==e?void 0:e.sessionStorage)&&void 0!==l?l:function(){try{if("undefined"!=typeof globalThis&&globalThis.sessionStorage)return globalThis.sessionStorage}catch(e){}return function(){let e=new Map;return{get length(){return e.size},clear(){e.clear()},getItem:t=>e.has(t)?e.get(t):null,key(t){var r;return null!==(r=Array.from(e.keys())[t])&&void 0!==r?r:null},removeItem(t){e.delete(t)},setItem(t,r){e.set(t,String(r))}}}()}(),g.reconnectAfterMs=null!==(c=null==e?void 0:e.reconnectAfterMs)&&void 0!==c?c:e=>tJ[e-1]||1e4;let m=null!==(u=null==e?void 0:e.vsn)&&void 0!==u?u:tl;switch(m){case"1.0.0":p=(e,t)=>t(JSON.stringify(e)),f=(e,t)=>t(JSON.parse(e));break;case tl:p=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${g.vsn}`)}if(g.vsn=m,g.encode=null!==(h=null==e?void 0:e.encode)&&void 0!==h?h:p,g.decode=null!==(d=null==e?void 0:e.decode)&&void 0!==d?d:f,g.beforeReconnect=this._reconnectAuth.bind(this),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,g.params=Object.assign(Object.assign({},g.params),{log_level:this.logLevel})),this.worker){if("undefined"!=typeof window&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl,g.autoSendHeartbeat=!this.worker}return g}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var tQ=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&t.icebergType?.includes("CommitState")===!0}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};async function tZ(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}function t0(e){return e.join("\x1f")}var t1=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:t0(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){let r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${t0(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${t0(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${t0(e.namespace)}`}),!0}catch(e){if(e instanceof tQ&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof tQ&&409===e.status)return;throw e}}};function t2(e){return e.join("\x1f")}var t3=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${t2(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${t2(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${t2(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${t2(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${t2(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${t2(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof tQ&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof tQ&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},t4=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);let r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=function(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:i,body:n,headers:a}){let o=function(e,t,r){let s=new URL(t,e);if(r)for(let[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,s,i),l=await tZ(e.auth),c=await t(o,{method:r,headers:{...n?{"Content-Type":"application/json"}:{},...l,...a},body:n?JSON.stringify(n):void 0}),u=await c.text(),h=(c.headers.get("content-type")||"").includes("application/json"),d=h&&u?JSON.parse(u):u;if(!c.ok){let e=h?d:void 0,t=e?.error;throw new tQ(t?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:c.status,headers:c.headers,data:d}}}}({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new t1(this.client,t),this.tableOps=new t3(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},t6=r(195).Buffer;function t5(e){return(t5="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function t8(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function t9(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?t8(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=t5(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=t5(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==t5(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):t8(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var t7=class extends Error{constructor(e,t="storage",r,s){super(e),this.__isStorageError=!0,this.namespace=t,this.name="vectors"===t?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function re(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var rt=class extends t7{constructor(e,t,r,s="storage"){super(e,s,t,r),this.name="vectors"===s?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=r}toJSON(){return t9({},super.toJSON())}},rr=class extends t7{constructor(e,t,r="storage"){super(e,r),this.name="vectors"===r?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};function rs(e,t,r){let s=t9({},e),i=t.toLowerCase();for(let e of Object.keys(s))e.toLowerCase()===i&&delete s[e];return s[i]=r,s}let ri=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),rn=e=>{if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},ra=e=>{if(Array.isArray(e))return e.map(e=>ra(e));if("function"==typeof e||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([e,r])=>{t[e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""))]=ra(r)}),t},ro=e=>!(!e||"string"!=typeof e||0===e.length||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\"))&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e),rl=e=>{if("object"==typeof e&&null!==e){if("string"==typeof e.msg)return e.msg;if("string"==typeof e.message)return e.message;if("string"==typeof e.error_description)return e.error_description;if("string"==typeof e.error)return e.error;if("object"==typeof e.error&&null!==e.error){let t=e.error;if("string"==typeof t.message)return t.message}}return JSON.stringify(e)},rc=async(e,t,r,s)=>{if(null!==e&&"object"==typeof e&&"json"in e&&"function"==typeof e.json){let r=parseInt(String(e.status),10);Number.isFinite(r)||(r=500),e.json().then(e=>{let i=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new rt(rl(e),r,i,s))}).catch(()=>{let i=r+"";t(new rt(e.statusText||`HTTP ${r} error`,r,i,s))})}else t(new rr(rl(e),e,s))},ru=(e,t,r,s)=>{let i={method:e,headers:(null==t?void 0:t.headers)||{}};if("GET"===e||"HEAD"===e||!s)return t9(t9({},i),r);if(rn(s)){var n;let e;let r=(null==t?void 0:t.headers)||{};for(let[t,s]of Object.entries(r))"content-type"===t.toLowerCase()&&(e=s);i.headers=rs(r,"Content-Type",null!==(n=e)&&void 0!==n?n:"application/json"),i.body=JSON.stringify(s)}else i.body=s;return(null==t?void 0:t.duplex)&&(i.duplex=t.duplex),t9(t9({},i),r)};async function rh(e,t,r,s,i,n,a){return new Promise((o,l)=>{e(r,ru(t,s,i,n)).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;if("vectors"===a){let t=e.headers.get("content-type");if("0"===e.headers.get("content-length")||204===e.status||!t||!t.includes("application/json"))return{}}return e.json()}).then(e=>o(e)).catch(e=>rc(e,l,s,a))})}function rd(e="storage"){return{get:async(t,r,s,i)=>rh(t,"GET",r,s,i,void 0,e),post:async(t,r,s,i,n)=>rh(t,"POST",r,i,n,s,e),put:async(t,r,s,i,n)=>rh(t,"PUT",r,i,n,s,e),head:async(t,r,s,i)=>rh(t,"HEAD",r,t9(t9({},s),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,r,s,i,n)=>rh(t,"DELETE",r,i,n,s,e)}}let{get:rp,post:rf,put:rg,head:rm,remove:rb}=rd("storage"),ry=rd("vectors");var rw=class{constructor(e,t={},r,s="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=function(e){let t={};for(let[r,s]of Object.entries(e))t[r.toLowerCase()]=s;return t}(t),this.fetch=ri(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=rs(this.headers,e,t),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(re(e))return{data:null,error:e};throw e}}};i=Symbol.toStringTag;var rv=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[i]="StreamDownloadBuilder",this.promise=null}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(re(e))return{data:null,error:e};throw e}}};n=Symbol.toStringTag;var r_=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[n]="BlobDownloadBuilder",this.promise=null}asStream(){return new rv(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await (await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(re(e))return{data:null,error:e};throw e}}};let rk={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},rS={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var rT=class extends rw{constructor(e,t={},r,s){super(e,t,s,"storage"),this.bucketId=r}async uploadOrUpdate(e,t,r,s){var i=this;return i.handleOperation(async()=>{let n;let a=t9(t9({},rS),s),o=t9(t9({},i.headers),"POST"===e&&{"x-upsert":String(a.upsert)}),l=a.metadata;if("undefined"!=typeof Blob&&r instanceof Blob?((n=new FormData).append("cacheControl",a.cacheControl),l&&n.append("metadata",i.encodeMetadata(l)),n.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?((n=r).has("cacheControl")||n.append("cacheControl",a.cacheControl),l&&!n.has("metadata")&&n.append("metadata",i.encodeMetadata(l))):(n=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=i.toBase64(i.encodeMetadata(l))),("undefined"!=typeof ReadableStream&&n instanceof ReadableStream||n&&"object"==typeof n&&"pipe"in n&&"function"==typeof n.pipe)&&!a.duplex&&(a.duplex="half")),null==s?void 0:s.headers)for(let[e,t]of Object.entries(s.headers))o=rs(o,e,t);let c=i._removeEmptyFolders(t),u=i._getFinalPath(c),h=await ("PUT"==e?rg:rf)(i.fetch,`${i.url}/object/${u}`,n,t9({headers:o},(null==a?void 0:a.duplex)?{duplex:a.duplex}:{}));return{path:c,id:h.Id,fullPath:h.Key}})}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var i=this;let n=i._removeEmptyFolders(e),a=i._getFinalPath(n),o=new URL(i.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",t),i.handleOperation(async()=>{let e;let t=t9(t9({},rS),s),a=t9(t9({},i.headers),{"x-upsert":String(t.upsert)}),l=t.metadata;if("undefined"!=typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),l&&e.append("metadata",i.encodeMetadata(l)),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?((e=r).has("cacheControl")||e.append("cacheControl",t.cacheControl),l&&!e.has("metadata")&&e.append("metadata",i.encodeMetadata(l))):(e=r,a["cache-control"]=`max-age=${t.cacheControl}`,a["content-type"]=t.contentType,l&&(a["x-metadata"]=i.toBase64(i.encodeMetadata(l))),("undefined"!=typeof ReadableStream&&e instanceof ReadableStream||e&&"object"==typeof e&&"pipe"in e&&"function"==typeof e.pipe)&&!t.duplex&&(t.duplex="half")),null==s?void 0:s.headers)for(let[e,t]of Object.entries(s.headers))a=rs(a,e,t);return{path:n,fullPath:(await rg(i.fetch,o.toString(),e,t9({headers:a},(null==t?void 0:t.duplex)?{duplex:t.duplex}:{}))).Key}})}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(e),i=t9({},r.headers);(null==t?void 0:t.upsert)&&(i["x-upsert"]="true");let n=await rf(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:i}),a=new URL(r.url+n.url),o=a.searchParams.get("token");if(!o)throw new t7("No token returned by API");return{signedUrl:a.toString(),path:e,token:o}})}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;return s.handleOperation(async()=>await rf(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers}))}async copy(e,t,r){var s=this;return s.handleOperation(async()=>({path:(await rf(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(e,t,r){var s=this;return s.handleOperation(async()=>{let i=s._getFinalPath(e),n="object"==typeof(null==r?void 0:r.transform)&&null!==r.transform&&Object.keys(r.transform).length>0,a=await rf(s.fetch,`${s.url}/object/sign/${i}`,t9({expiresIn:t},n?{transform:r.transform}:{}),{headers:s.headers}),o=new URLSearchParams;(null==r?void 0:r.download)&&o.set("download",!0===r.download?"":r.download),(null==r?void 0:r.cacheNonce)!=null&&o.set("cacheNonce",String(r.cacheNonce));let l=o.toString();return{signedUrl:encodeURI(`${s.url}${a.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(e,t,r){var s=this;return s.handleOperation(async()=>{let i=await rf(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),n=new URLSearchParams;(null==r?void 0:r.download)&&n.set("download",!0===r.download?"":r.download),(null==r?void 0:r.cacheNonce)!=null&&n.set("cacheNonce",String(r.cacheNonce));let a=n.toString();return i.map(e=>t9(t9({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${a?`&${a}`:""}`):null}))})}download(e,t,r){let s="object"==typeof(null==t?void 0:t.transform)&&null!==t.transform&&Object.keys(t.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;(null==t?void 0:t.transform)&&this.applyTransformOptsToQuery(i,t.transform),(null==t?void 0:t.cacheNonce)!=null&&i.set("cacheNonce",String(t.cacheNonce));let n=i.toString(),a=this._getFinalPath(e);return new r_(()=>rp(this.fetch,`${this.url}/${s}/${a}${n?`?${n}`:""}`,{headers:this.headers,noResolveJson:!0},r),this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);return t.handleOperation(async()=>ra(await rp(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})))}async exists(e){var t;let r=this._getFinalPath(e);try{return await rm(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(re(e)){let r=e instanceof rt?e.status:e instanceof rr?null===(t=e.originalError)||void 0===t?void 0:t.status:void 0;if(void 0!==r&&[400,404].includes(r))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let r=this._getFinalPath(e),s=new URLSearchParams;(null==t?void 0:t.download)&&s.set("download",!0===t.download?"":t.download),(null==t?void 0:t.transform)&&this.applyTransformOptsToQuery(s,t.transform),(null==t?void 0:t.cacheNonce)!=null&&s.set("cacheNonce",String(t.cacheNonce));let i=s.toString(),n="object"==typeof(null==t?void 0:t.transform)&&null!==t.transform&&Object.keys(t.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${r}`)+(i?`?${i}`:"")}}}async remove(e){var t=this;return t.handleOperation(async()=>await rb(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,r){var s=this;return s.handleOperation(async()=>{let i=t9(t9(t9({},rk),t),{},{prefix:e||""});return await rf(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(e,t){var r=this;return r.handleOperation(async()=>{let s=t9({},e);return await rf(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return void 0!==t6?t6.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(e,t){return t.width&&e.set("width",t.width.toString()),t.height&&e.set("height",t.height.toString()),t.resize&&e.set("resize",t.resize),t.format&&e.set("format",t.format),t.quality&&e.set("quality",t.quality.toString()),e}};let rE={"X-Client-Info":"storage-js/2.108.0"};var rR=class extends rw{constructor(e,t={},r,s){let i=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),super(i.href.replace(/\/$/,""),t9(t9({},rE),t),r,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await rp(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await rp(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation(async()=>await rf(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async updateBucket(e,t){var r=this;return r.handleOperation(async()=>await rg(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await rf(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await rb(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},rO=class extends rw{constructor(e,t={},r){super(e.replace(/\/$/,""),t9(t9({},rE),t),r,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await rf(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=new URLSearchParams;(null==e?void 0:e.limit)!==void 0&&r.set("limit",e.limit.toString()),(null==e?void 0:e.offset)!==void 0&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);let s=r.toString(),i=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return await rp(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await rb(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!ro(e))throw new t7("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new t4({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){let r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}}})}},rA=class extends rw{constructor(e,t={},r){super(e.replace(/\/$/,""),t9(t9({},rE),{},{"Content-Type":"application/json"},t),r,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await ry.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await ry.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}},rP=class extends rw{constructor(e,t={},r){super(e.replace(/\/$/,""),t9(t9({},rE),{},{"Content-Type":"application/json"},t),r,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},rC=class extends rw{constructor(e,t={},r){super(e.replace(/\/$/,""),t9(t9({},rE),{},{"Content-Type":"application/json"},t),r,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ry.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},rx=class extends rC{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new rI(this.url,this.headers,e,this.fetch)}async createBucket(e){return super.createBucket.call(this,e)}async getBucket(e){return super.getBucket.call(this,e)}async listBuckets(e={}){return super.listBuckets.call(this,e)}async deleteBucket(e){return super.deleteBucket.call(this,e)}},rI=class extends rA{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return super.createIndex.call(this,t9(t9({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return super.listIndexes.call(this,t9(t9({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return super.getIndex.call(this,this.vectorBucketName,e)}async deleteIndex(e){return super.deleteIndex.call(this,this.vectorBucketName,e)}index(e){return new rj(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},rj=class extends rP{constructor(e,t,r,s,i){super(e,t,i),this.vectorBucketName=r,this.indexName=s}async putVectors(e){return super.putVectors.call(this,t9(t9({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async getVectors(e){return super.getVectors.call(this,t9(t9({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async listVectors(e={}){return super.listVectors.call(this,t9(t9({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async queryVectors(e){return super.queryVectors.call(this,t9(t9({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async deleteVectors(e){return super.deleteVectors.call(this,t9(t9({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}},rN=class extends rR{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new rT(this.url,this.headers,e,this.fetch)}get vectors(){return new rx(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new rO(this.url+"/iceberg",this.headers,this.fetch)}};let r$="2.108.0",rL={"X-Client-Info":`gotrue-js/${r$}`},rD="X-Supabase-Api-Version",rU={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},rM=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class rB extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function rq(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class rH extends rB{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class rV extends rB{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class rW extends rB{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class rG extends rW{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function rK(e){return rq(e)&&"AuthSessionMissingError"===e.name}class rF extends rW{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class rz extends rW{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class rJ extends rW{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class rX extends rW{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class rY extends rW{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class rQ extends rW{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function rZ(e){return rq(e)&&"AuthRetryableFetchError"===e.name}class r0 extends rW{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}}class r1 extends rW{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class r2 extends rW{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}let r3="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),r4=" 	\n\r=".split(""),r6=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<r4.length;t+=1)e[r4[t].charCodeAt(0)]=-2;for(let t=0;t<r3.length;t+=1)e[r3[t].charCodeAt(0)]=t;return e})();function r5(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)r(r3[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)r(r3[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function r8(e,t,r){let s=r6[e];if(s>-1)for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(-2===s)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function r9(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127){r(e);return}for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t<e.length;t+=1)r8(e.charCodeAt(t),i,n);return t.join("")}function r7(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)r8(e.charCodeAt(t),r,s);return new Uint8Array(t)}function se(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>r5(e,r,s)),r5(null,r,s),t.join("")}let st=()=>"undefined"!=typeof window&&"undefined"!=typeof document,sr={tested:!1,writable:!1},ss=()=>{if(!st())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(sr.tested)return sr.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),sr.tested=!0,sr.writable=!0}catch(e){sr.tested=!0,sr.writable=!1}return sr.writable},si=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),sn=e=>"object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json,sa=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},so=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return null}},sl=async(e,t)=>{await e.removeItem(t)};class sc{constructor(){this.promise=new sc.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function su(e){let t=e.split(".");if(3!==t.length)throw new r2("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!rM.test(t[e]))throw new r2("JWT not in base64url format");return{header:JSON.parse(r9(t[0])),payload:JSON.parse(r9(t[1])),signature:r7(t[2]),raw:{header:t[0],payload:t[1]}}}async function sh(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function sd(e){return("0"+e.toString(16)).substr(-2)}async function sp(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>String.fromCharCode(e)).join("")}async function sf(e){return"undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder?btoa(await sp(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):(console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e)}async function sg(e,t,r=!1){let s=function(){let e=new Uint32Array(56);if("undefined"==typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,sd).join("")}(),i=s;r&&(i+="/recovery"),await sa(e,`${t}-code-verifier`,i);let n=await sf(s),a=s===n?"plain":"s256";return[n,a]}sc.promiseConstructor=Promise;let sm=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,sb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function sy(e){if(!sb.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function sw(e){if(!e.passkey)throw Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function sv(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){let e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function s_(e){return JSON.parse(JSON.stringify(e))}let sk=e=>{if("object"==typeof e&&null!==e){if("string"==typeof e.msg)return e.msg;if("string"==typeof e.message)return e.message;if("string"==typeof e.error_description)return e.error_description;if("string"==typeof e.error)return e.error}return JSON.stringify(e)},sS=[502,503,504,520,521,522,523,524,530];async function sT(e){var t;let r,s;if(!sn(e))throw new rQ(sk(e),0);if(sS.includes(e.status))throw new rQ(sk(e),e.status);try{r=await e.json()}catch(e){throw new rV(sk(e),e)}let i=function(e){let t=e.headers.get(rD);if(!t||!t.match(sm))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=rU["2024-01-01"].timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?s=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(s=r.error_code),s){if("weak_password"===s)throw new r1(sk(r),e.status,(null===(t=r.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===s)throw new rG}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new r1(sk(r),e.status,r.weak_password.reasons);throw new rH(sk(r),e.status||500,s)}let sE=(e,t,r,s)=>{let i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))};async function sR(e,t,r,s){var i;let n=Object.assign({},null==s?void 0:s.headers);n[rD]||(n[rD]=rU["2024-01-01"].name),(null==s?void 0:s.jwt)&&(n.Authorization=`Bearer ${s.jwt}`);let a=null!==(i=null==s?void 0:s.query)&&void 0!==i?i:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);let o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await sO(e,t,r+o,{headers:n,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(l):{data:Object.assign({},l),error:null}}async function sO(e,t,r,s,i,n){let a;let o=sE(t,s,i,n);try{a=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new rQ(sk(e),0)}if(a.ok||await sT(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await sT(e)}}function sA(e){var t,r;let s=null;return e.access_token&&e.refresh_token&&e.expires_in&&(s=Object.assign({},e),!e.expires_at)&&(s.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)),{data:{session:s,user:null!==(t=e.user)&&void 0!==t?t:"string"==typeof(null==e?void 0:e.id)?e:null},error:null}}function sP(e){let t=sA(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function sC(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function sx(e){return{data:e,error:null}}function sI(e){let{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n}=e;return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n},user:Object.assign({},eX(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function sj(e){return e}let sN=["global","local","others"];class s${constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=si(r),this.experimental=null!=s?s:{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=sN[0]){if(0>sN.indexOf(t))throw Error(`@supabase/auth-js: Parameter scope must be one of ${sN.join(", ")}`);try{return await sR(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(rq(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await sR(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:sC})}catch(e){if(rq(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=eX(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await sR(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:sI,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(rq(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await sR(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:sC})}catch(e){if(rq(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},c=await sR(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(i=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==i?i:""},xform:sj});if(c.error)throw c.error;let u=await c.json(),h=null!==(n=c.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(o=null===(a=c.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(e){if(rq(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){sy(e);try{return await sR(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:sC})}catch(e){if(rq(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){sy(e);try{return await sR(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:sC})}catch(e){if(rq(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){sy(e);try{return await sR(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:sC})}catch(e){if(rq(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){sy(e.userId);try{let{data:t,error:r}=await sR(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _deleteFactor(e){sy(e.userId),sy(e.id);try{return{data:await sR(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},c=await sR(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(i=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==i?i:""},xform:sj});if(c.error)throw c.error;let u=await c.json(),h=null!==(n=c.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(o=null===(a=c.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(e){if(rq(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await sR(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await sR(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await sR(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await sR(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await sR(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return(null==e?void 0:e.type)&&(t.type=e.type),await sR(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>{var t;return{data:{providers:null!==(t=null==e?void 0:e.providers)&&void 0!==t?t:[]},error:null}}})}catch(e){if(rq(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await sR(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await sR(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await sR(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await sR(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _adminListPasskeys(e){sw(this.experimental),sy(e.userId);try{return await sR(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(rq(e))return{data:null,error:e};throw e}}async _adminDeletePasskey(e){sw(this.experimental),sy(e.userId),sy(e.passkeyId);try{return await sR(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(rq(e))return{data:null,error:e};throw e}}}function sL(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}globalThis&&ss()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class sD extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}function sU(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}class sM extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!==(i=null!=s?s:r instanceof Error?r.name:void 0)&&void 0!==i?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class sB extends sM{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}class sq{createNewAbortSignal(){if(this.controller){let e=Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}let sH=new sq;function sV(e){if(!e)throw Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:s}=e,i=eX(e,["challenge","user","excludeCredentials"]),n=r7(t).buffer,a=Object.assign(Object.assign({},r),{id:r7(r.id).buffer}),o=Object.assign(Object.assign({},i),{challenge:n,user:a});if(s&&s.length>0){o.excludeCredentials=Array(s.length);for(let e=0;e<s.length;e++){let t=s[e];o.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:r7(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function sW(e){if(!e)throw Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,s=eX(e,["challenge","allowCredentials"]),i=r7(t).buffer,n=Object.assign(Object.assign({},s),{challenge:i});if(r&&r.length>0){n.allowCredentials=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e];n.allowCredentials[e]=Object.assign(Object.assign({},t),{id:r7(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return n}function sG(e){var t;return"toJSON"in e&&"function"==typeof e.toJSON?e.toJSON():{id:e.id,rawId:e.id,response:{attestationObject:se(new Uint8Array(e.response.attestationObject)),clientDataJSON:se(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=e.authenticatorAttachment)&&void 0!==t?t:void 0}}function sK(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();let r=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:se(new Uint8Array(s.authenticatorData)),clientDataJSON:se(new Uint8Array(s.clientDataJSON)),signature:se(new Uint8Array(s.signature)),userHandle:s.userHandle?se(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!==(t=e.authenticatorAttachment)&&void 0!==t?t:void 0}}function sF(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function sz(){var e,t;return!!(st()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null==navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null==navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}async function sJ(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new sB("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new sB("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function({error:e,options:t}){var r,s,i;let{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new sM({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if((null===(r=n.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey)===!0)return new sM({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&(null===(s=n.authenticatorSelection)||void 0===s?void 0:s.userVerification)==="required")return new sM({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if((null===(i=n.authenticatorSelection)||void 0===i?void 0:i.userVerification)==="required")return new sM({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else if("InvalidStateError"===e.name)return new sM({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});else if("NotAllowedError"===e.name)return new sM({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if("NotSupportedError"===e.name)return new sM(0===n.pubKeyCredParams.filter(e=>"public-key"===e.type).length?{message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}:{message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});else if("SecurityError"===e.name){let t=window.location.hostname;if(!sF(t))return new sM({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new sM({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new sM({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new sM({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new sM({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}({error:t,options:e})}}}async function sX(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new sB("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new sB("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new sM({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("NotAllowedError"===e.name)return new sM({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if("SecurityError"===e.name){let t=window.location.hostname;if(!sF(t))return new sM({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new sM({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new sM({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new sM({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}({error:t,options:e})}}}let sY={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},sQ={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function sZ(...e){let t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(let i of e)if(i)for(let e in i){let n=i[e];if(void 0!==n){if(Array.isArray(n))s[e]=n;else if(r(n))s[e]=n;else if(t(n)){let r=s[e];t(r)?s[e]=sZ(r,n):s[e]=sZ(n)}else s[e]=n}}return s}class s0{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var n,a,o,l,c;try{let{data:u,error:h}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!u)return{data:null,error:h};let d=null!=s?s:sH.createNewAbortSignal();if("create"===u.webauthn.type){let{user:e}=u.webauthn.credential_options.publicKey;if(!e.name){if(r)e.name=`${e.id}:${r}`;else{let t=(await this.client.getUser()).data.user,r=(null===(n=null==t?void 0:t.user_metadata)||void 0===n?void 0:n.name)||(null==t?void 0:t.email)||(null==t?void 0:t.id)||"User";e.name=`${e.id}:${r}`}}e.displayName||(e.displayName=e.name)}switch(u.webauthn.type){case"create":{let t=(a=u.webauthn.credential_options.publicKey,o=null==i?void 0:i.create,sZ(sY,a,o||{})),{data:r,error:s}=await sJ({publicKey:t,signal:d});if(r)return{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:r}},error:null};return{data:null,error:s}}case"request":{let t=(l=u.webauthn.credential_options.publicKey,c=null==i?void 0:i.request,sZ(sQ,l,c||{})),{data:r,error:s}=await sX(Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:t,signal:d}));if(r)return{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:r}},error:null};return{data:null,error:s}}}}catch(e){if(rq(e))return{data:null,error:e};return{data:null,error:new rV("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t="undefined"!=typeof window?window.location.hostname:void 0,rpOrigins:r="undefined"!=typeof window?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new rB("rpId is required for WebAuthn authentication")};try{if(!sz())return{data:null,error:new rV("Browser does not support WebAuthn",null)};let{data:n,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!n)return{data:null,error:a};let{webauthn:o}=n;return this._verify({factorId:e,challengeId:n.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:r,credential_response:o.credential_response}})}catch(e){if(rq(e))return{data:null,error:e};return{data:null,error:new rV("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t="undefined"!=typeof window?window.location.hostname:void 0,rpOrigins:r="undefined"!=typeof window?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new rB("rpId is required for WebAuthn registration")};try{if(!sz())return{data:null,error:new rV("Browser does not support WebAuthn",null)};let{data:n,error:a}=await this._enroll({friendlyName:e});if(!n)return await this.client.mfa.listFactors().then(t=>{var r;return null===(r=t.data)||void 0===r?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};let{data:o,error:l}=await this._challenge({factorId:n.id,friendlyName:n.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});if(!o)return{data:null,error:l};return this._verify({factorId:n.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}})}catch(e){if(rq(e))return{data:null,error:e};return{data:null,error:new rV("Unexpected error in register",e)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();let s1={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:rL,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},s2={};class s3{get jwks(){var e,t;return null!==(t=null===(e=s2[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){s2[this.storageKey]=Object.assign(Object.assign({},s2[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=s2[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){s2[this.storageKey]=Object.assign(Object.assign({},s2[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},s1),e);if(this.storageKey=i.storageKey,this.instanceID=null!==(t=s3.nextInstanceID[this.storageKey])&&void 0!==t?t:0,s3.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,"function"==typeof i.debug&&(this.logger=i.debug),this.instanceID>0&&st()){let e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=null!==(r=i.experimental)&&void 0!==r?r:{},this.admin=new s$({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=si(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,null!=i.lock&&(this.lock=i.lock),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new s0(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:ss()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=sL(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=sL(this.memoryStorage)),st()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(s=this.broadcastChannel)||void 0===s||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug("#broadcastChannel","error",e)}})}i.skipAutoInitialize||this.initialize().catch(e=>{this._debug("#initialize()","error",e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${r$}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(st()&&(t=function(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),st()&&this.detectSessionInUrl&&"none"!==r){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i)return this._debug("#_initialize()","error detecting session from URL",i),rq(i)&&"AuthImplicitGrantRedirectError"===i.name&&(null===(e=i.details)||void 0===e||e.code),{error:i};let{session:n,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",n,"redirect type",a),await this._saveSession(n),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){if(rq(e))return this._returnResult({error:e});return this._returnResult({error:new rV("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let{data:i,error:n}=await sR(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==r?r:{},gotrue_meta_security:{captcha_token:null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken}},xform:sA});if(n||!i)return this._returnResult({data:{user:null,session:null},error:n});let a=i.session,o=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:o,session:a},error:null})}catch(e){if(rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,s;try{let i;if("email"in e){let{email:r,password:s,options:n}=e,a=null,o=null;"pkce"===this.flowType&&([a,o]=await sg(this.storage,this.storageKey)),i=await sR(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==n?void 0:n.emailRedirectTo,body:{email:r,password:s,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:a,code_challenge_method:o},xform:sA})}else if("phone"in e){let{phone:t,password:n,options:a}=e;i=await sR(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!==(r=null==a?void 0:a.data)&&void 0!==r?r:{},channel:null!==(s=null==a?void 0:a.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:sA})}else throw new rz("You must provide either an email or phone number and a password");let{data:n,error:a}=i;if(a||!n)return await sl(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let o=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(e){if(await sl(this.storage,`${this.storageKey}-code-verifier`),rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){let{email:r,password:s,options:i}=e;t=await sR(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:sP})}else if("phone"in e){let{phone:r,password:s,options:i}=e;t=await sR(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:sP})}else throw new rz("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let e=new rF;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return(await this.initializePromise,null!=this.lock)?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e)):this._exchangeCodeForSession(e)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,n,a,o,l,c,u,h,d;let p,f;if("message"in e)p=e.message,f=e.signature;else{let u;let{chain:h,wallet:g,statement:m,options:b}=e;if(st()){if("object"==typeof g)u=g;else{let e=window;if("ethereum"in e&&"object"==typeof e.ethereum&&"request"in e.ethereum&&"function"==typeof e.ethereum.request)u=e.ethereum;else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}}else{if("object"!=typeof g||!(null==b?void 0:b.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");u=g}let y=new URL(null!==(t=null==b?void 0:b.url)&&void 0!==t?t:window.location.href),w=await u.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!w||0===w.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let v=sU(w[0]),_=null===(r=null==b?void 0:b.signInWithEthereum)||void 0===r?void 0:r.chainId;_||(_=parseInt(await u.request({method:"eth_chainId"}),16)),p=function(e){var t;let{chainId:r,domain:s,expirationTime:i,issuedAt:n=new Date,nonce:a,notBefore:o,requestId:l,resources:c,scheme:u,uri:h,version:d}=e;if(!Number.isInteger(r))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!h)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let p=sU(e.address),f=u?`${u}://${s}`:s,g=e.statement?`${e.statement}
`:"",m=`${f} wants you to sign in with your Ethereum account:
${p}

${g}`,b=`URI: ${h}
Version: ${d}
Chain ID: ${r}${a?`
Nonce: ${a}`:""}
Issued At: ${n.toISOString()}`;if(i&&(b+=`
Expiration Time: ${i.toISOString()}`),o&&(b+=`
Not Before: ${o.toISOString()}`),l&&(b+=`
Request ID: ${l}`),c){let e="\nResources:";for(let t of c){if(!t||"string"!=typeof t)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`
- ${t}`}b+=e}return`${m}
${b}`}({domain:y.host,address:v,statement:m,uri:y.href,version:"1",chainId:_,nonce:null===(s=null==b?void 0:b.signInWithEthereum)||void 0===s?void 0:s.nonce,issuedAt:null!==(n=null===(i=null==b?void 0:b.signInWithEthereum)||void 0===i?void 0:i.issuedAt)&&void 0!==n?n:new Date,expirationTime:null===(a=null==b?void 0:b.signInWithEthereum)||void 0===a?void 0:a.expirationTime,notBefore:null===(o=null==b?void 0:b.signInWithEthereum)||void 0===o?void 0:o.notBefore,requestId:null===(l=null==b?void 0:b.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(c=null==b?void 0:b.signInWithEthereum)||void 0===c?void 0:c.resources}),f=await u.request({method:"personal_sign",params:[(d=p,"0x"+Array.from(new TextEncoder().encode(d),e=>e.toString(16).padStart(2,"0")).join("")),v]})}try{let{data:t,error:r}=await sR(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:f},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(h=e.options)||void 0===h?void 0:h.captchaToken}}:null),xform:sA});if(r)throw r;if(!t||!t.session||!t.user){let e=new rF;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,s,i,n,a,o,l,c,u,h,d;let p,f;if("message"in e)p=e.message,f=e.signature;else{let h;let{chain:d,wallet:g,statement:m,options:b}=e;if(st()){if("object"==typeof g)h=g;else{let e=window;if("solana"in e&&"object"==typeof e.solana&&("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))h=e.solana;else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}}else{if("object"!=typeof g||!(null==b?void 0:b.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");h=g}let y=new URL(null!==(t=null==b?void 0:b.url)&&void 0!==t?t:window.location.href);if("signIn"in h&&h.signIn){let e;let t=await h.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},null==b?void 0:b.signInWithSolana),{version:"1",domain:y.host,uri:y.href}),m?{statement:m}:null));if(Array.isArray(t)&&t[0]&&"object"==typeof t[0])e=t[0];else if(t&&"object"==typeof t&&"signedMessage"in t&&"signature"in t)e=t;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in e&&"signature"in e&&("string"==typeof e.signedMessage||e.signedMessage instanceof Uint8Array)&&e.signature instanceof Uint8Array)p="string"==typeof e.signedMessage?e.signedMessage:new TextDecoder().decode(e.signedMessage),f=e.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in h)||"function"!=typeof h.signMessage||!("publicKey"in h)||"object"!=typeof h||!h.publicKey||!("toBase58"in h.publicKey)||"function"!=typeof h.publicKey.toBase58)throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${y.host} wants you to sign in with your Solana account:`,h.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${y.href}`,`Issued At: ${null!==(s=null===(r=null==b?void 0:b.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==s?s:new Date().toISOString()}`,...(null===(i=null==b?void 0:b.signInWithSolana)||void 0===i?void 0:i.notBefore)?[`Not Before: ${b.signInWithSolana.notBefore}`]:[],...(null===(n=null==b?void 0:b.signInWithSolana)||void 0===n?void 0:n.expirationTime)?[`Expiration Time: ${b.signInWithSolana.expirationTime}`]:[],...(null===(a=null==b?void 0:b.signInWithSolana)||void 0===a?void 0:a.chainId)?[`Chain ID: ${b.signInWithSolana.chainId}`]:[],...(null===(o=null==b?void 0:b.signInWithSolana)||void 0===o?void 0:o.nonce)?[`Nonce: ${b.signInWithSolana.nonce}`]:[],...(null===(l=null==b?void 0:b.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${b.signInWithSolana.requestId}`]:[],...(null===(u=null===(c=null==b?void 0:b.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===u?void 0:u.length)?["Resources",...b.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");let e=await h.signMessage(new TextEncoder().encode(p),"utf8");if(!e||!(e instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");f=e}}try{let{data:t,error:r}=await sR(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:se(f)},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:sA});if(r)throw r;if(!t||!t.session||!t.user){let e=new rF;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let t=await so(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new rY;let{data:t,error:i}=await sR(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:sA});if(await sl(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!t||!t.session||!t.user){let e=new rF;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("recovery"===s?"PASSWORD_RECOVERY":"SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=s?s:null}),error:i})}catch(e){if(await sl(this.storage,`${this.storageKey}-code-verifier`),rq(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:n}=e,{data:a,error:o}=await sR(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:n,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:sA});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!a||!a.session||!a.user){let e=new rF;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:o})}catch(e){if(rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,s,i,n;try{if("email"in e){let{email:s,options:i}=e,n=null,a=null;"pkce"===this.flowType&&([n,a]=await sg(this.storage,this.storageKey));let{error:o}=await sR(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},create_user:null===(r=null==i?void 0:i.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:a},redirectTo:null==i?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){let{phone:t,options:r}=e,{data:a,error:o}=await sR(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(s=null==r?void 0:r.data)&&void 0!==s?s:{},create_user:null===(i=null==r?void 0:r.shouldCreateUser)||void 0===i||i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(n=null==r?void 0:r.channel)&&void 0!==n?n:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new rz("You must provide either an email or phone number.")}catch(e){if(await sl(this.storage,`${this.storageKey}-code-verifier`),rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo,i=null===(r=e.options)||void 0===r?void 0:r.captchaToken);let{data:n,error:a}=await sR(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:sA});if(a)throw a;if(!n)throw Error("An error occurred on token verification.");let o=n.session,l=n.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(e){if(rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,s,i,n;try{let a=null,o=null;"pkce"===this.flowType&&([a,o]=await sg(this.storage,this.storageKey));let l=await sR(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:o}),headers:this.headers,xform:sx});return(null===(i=l.data)||void 0===i?void 0:i.url)&&st()&&!(null===(n=e.options)||void 0===n?void 0:n.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await sl(this.storage,`${this.storageKey}-code-verifier`),rq(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new rG;let{error:s}=await sR(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:s,options:i}=e,n=null,a=null;"pkce"===this.flowType&&([n,a]=await sg(this.storage,this.storageKey));let{error:o}=await sR(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:a},redirectTo:null==i?void 0:i.emailRedirectTo});return o&&await sl(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){let{phone:r,type:s,options:i}=e,{data:n,error:a}=await sR(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:a})}throw new rz("You must provide either an email or phone number and a type")}catch(e){if(await sl(this.storage,`${this.storageKey}-code-verifier`),rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),null==this.lock||this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let t=null,r=await so(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),null!==r&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};let s=!!t.expires_at&&1e3*t.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",t.expires_at),!s){if(this.userStorage){let e=await so(this.userStorage,this.storageKey+"-user");(null==e?void 0:e.user)?t.user=e.user:t.user=sv()}if(this.storage.isServer&&t.user&&!t.user.__isUserNotAvailableProxy){var e;let r={value:this.suppressGetSessionWarning};t.user=(e=t.user,new Proxy(e,{get:(e,t,s)=>{if("__isInsecureUserWarningProxy"===t)return!0;if("symbol"==typeof t){let r=t.toString();if("Symbol(Symbol.toPrimitive)"===r||"Symbol(Symbol.toStringTag)"===r||"Symbol(util.inspect.custom)"===r||"Symbol(nodejs.util.inspect.custom)"===r)return Reflect.get(e,t,s)}return r.value||"string"!=typeof t||(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),r.value=!0),Reflect.get(e,t,s)}})),r.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:t},error:null}}let{data:i,error:n}=await this._callRefreshToken(t.refresh_token);if(n)return this._returnResult({data:{session:null},error:n});return this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){let t;return e?await this._getUser(e):(await this.initializePromise,(t=null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):await this._getUser()).data.user&&(this.suppressGetSessionWarning=!0),t)}async _getUser(e){try{if(e)return await sR(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:sC});return await this._useSession(async e=>{var t,r,s;let{data:i,error:n}=e;if(n)throw n;return(null===(t=i.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await sR(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(s=null===(r=i.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0,xform:sC}):{data:{user:null},error:new rG}})}catch(e){if(rq(e))return rK(e)&&(await this._removeSession(),await sl(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new rG;let n=s.session,a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await sg(this.storage,this.storageKey));let{data:l,error:c}=await sR(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:n.access_token,xform:sC});if(c)throw c;return n.user=l.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),this._returnResult({data:{user:n.user},error:null})})}catch(e){if(await sl(this.storage,`${this.storageKey}-code-verifier`),rq(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new rG;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:n}=su(e.access_token);if(n.exp&&(s=(r=n.exp)<=t),s){let{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:s,error:n}=await this._getUser(e.access_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});i={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(rq(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:s,error:i}=t;if(i)throw i;e=null!==(r=s.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new rG;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){var r;try{if(!st())throw new rJ("No browser detected.");if(e.error||e.error_description||e.error_code)throw new rJ(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new rX("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new rJ("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new rX("No code detected.");let{data:t,error:s}=await this._exchangeCodeForSession(e.code);if(s)throw s;let i=new URL(window.location.href);return i.searchParams.delete("code"),window.history.replaceState(window.history.state,"",i.toString()),{data:{session:t.session,redirectType:null!==(r=t.redirectType)&&void 0!==r?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:a,expires_in:o,expires_at:l,token_type:c}=e;if(!n||!o||!a||!c)throw new rJ("No session defined in URL");let u=Math.round(Date.now()/1e3),h=parseInt(o),d=u+h;l&&(d=parseInt(l));let p=d-u;1e3*p<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);let f=d-h;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,d,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,d,u);let{data:g,error:m}=await this._getUser(n);if(m)throw m;let b={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:h,expires_at:d,refresh_token:a,token_type:c,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(e){if(rq(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){let t=await so(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i&&!rK(i))return this._returnResult({error:i});let n=null===(r=s.session)||void 0===r?void 0:r.access_token;if(n){let{error:t}=await this.admin.signOut(n,e);if(t&&!(rq(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status||403===t.status)||rK(t)))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await sl(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=Symbol("auth-callback"),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:s},error:i}=t;if(i)throw i;await (null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await (null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),rK(t)?console.warn(t):console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await sg(this.storage,this.storageKey,!0));try{return await sR(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await sl(this.storage,`${this.storageKey}-code-verifier`),rq(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:r,error:s}=await this._useSession(async t=>{var r,s,i,n,a;let{data:o,error:l}=t;if(l)throw l;let c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(r=e.options)||void 0===r?void 0:r.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(i=e.options)||void 0===i?void 0:i.queryParams,skipBrowserRedirect:!0});return await sR(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(a=null===(n=o.session)||void 0===n?void 0:n.access_token)&&void 0!==a?a:void 0})});if(s)throw s;return!st()||(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)||window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(rq(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:n,provider:a,token:o,access_token:l,nonce:c}=e,{data:u,error:h}=await sR(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(r=null==i?void 0:i.access_token)&&void 0!==r?r:void 0,body:{provider:a,id_token:o,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:sA});if(h)return this._returnResult({data:{user:null,session:null},error:h});if(!u||!u.session||!u.user)return this._returnResult({data:{user:null,session:null},error:new rF});return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:h})}catch(e){if(await sl(this.storage,`${this.storageKey}-code-verifier`),rq(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)throw n;return await sR(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(s=null===(r=i.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0})})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{var r,s;let i=Date.now();return await (r=async r=>(r>0&&await sh(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await sR(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:sA})),s=(e,t)=>t&&rZ(t)&&Date.now()+200*Math.pow(2,e)-i<3e4,new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{let t=await r(i);if(!s(i,null,t)){e(t);return}}catch(e){if(!s(i,e)){t(e);return}}})()}))}catch(e){if(this._debug(t,"error",e),rq(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),st()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;let r="#_recoverAndRefresh()";this._debug(r,"begin");try{let s=await so(this.storage,this.storageKey);if(s&&this.userStorage){let t=await so(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!t&&(t={user:s.user},await sa(this.userStorage,this.storageKey+"-user",t)),s.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:sv()}else if(s&&!s.user&&!s.user){let e=await so(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await sl(this.storage,this.storageKey+"-user"),await sa(this.storage,this.storageKey,s)):s.user=sv()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),null!==s&&await this._removeSession();return}let i=(null!==(t=s.expires_at)&&void 0!==t?t:1/0)*1e3-Date.now()<9e4;if(this._debug(r,`session has${i?"":" not"} expired with margin of 90000s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:e}=await this._callRefreshToken(s.refresh_token);e&&(rq(e)&&"AuthRefreshDiscardedError"===e.name?this._debug(r,"refresh discarded by commit guard",e):(this._debug(r,"refresh failed",e),rZ(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession())))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{let{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){this._debug(r,"error",e),console.error(e);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new rG;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s="#_callRefreshToken()";this._debug(s,"begin");try{this.refreshingDeferred=new sc;let t=await so(this.storage,this.storageKey),{data:r,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!r.session)throw new rG;let n=await so(this.storage,this.storageKey);if(null!==t&&(null===n||n.refresh_token!==t.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:n?"replaced":"cleared"});let e={data:null,error:new r0};return this.refreshingDeferred.resolve(e),e}let a=this._sessionRemovalEpoch;if(await this._saveSession(r.session),this._sessionRemovalEpoch!==a){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await sl(this.storage,this.storageKey),this.userStorage&&await sl(this.userStorage,this.storageKey+"-user");let e={data:null,error:new r0};return this.refreshingDeferred.resolve(e),e}await this._notifyAllSubscribers("TOKEN_REFRESHED",r.session);let o={data:r.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(e){if(this._debug(s,"error",e),rq(e)){let r={data:null,error:e};return rZ(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(i),s.length>0){for(let e=0;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await sl(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await sa(this.userStorage,this.storageKey+"-user",{user:t.user});let e=Object.assign({},t);delete e.user;let s=s_(e);await sa(this.storage,this.storageKey,s)}else{let e=s_(t);await sa(this.storage,this.storageKey,e)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await sl(this.storage,this.storageKey),await sl(this.storage,this.storageKey+"-code-verifier"),await sl(this.storage,this.storageKey+"-user"),this.userStorage&&await sl(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&st()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),null===(e=this.broadcastChannel)||void 0===e||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),null!=this.lock){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof sD)this._debug("auto refresh token tick lock not available");else throw e}return}if(null!==this.refreshingDeferred){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!st()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState){if(this.autoRefreshToken&&this._startAutoRefresh(),!e){if(await this.initializePromise,null!=this.lock)await this._acquireLock(this.lockAcquireTimeout,async()=>{if("visible"!==document.visibilityState){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if("visible"!==document.visibilityState){this._debug(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}}else"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){let[e,t]=await sg(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(null==r?void 0:r.queryParams){let e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await sR(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)return this._returnResult({data:null,error:n});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:l}=await sR(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:null===(r=null==i?void 0:i.session)||void 0===r?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===o.type&&(null===(s=null==o?void 0:o.totp)||void 0===s?void 0:s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){let t=async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let n=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?sG(e.webauthn.credential_response):sK(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await sR(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:n,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:o}))})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let n=await sR(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});if(n.error)return n;let{data:a}=n;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:sV(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:sW(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[]};for(let r of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])s.all.push(r),"verified"===r.status&&s[r.factor_type].push(r);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:s}=su(e),i=null;s.aal&&(i=s.aal);let n=i,{data:{user:a},error:o}=await this.getUser(e);if(o)return this._returnResult({data:null,error:o});(null!==(r=null===(t=null==a?void 0:a.factors)||void 0===t?void 0:t.filter(e=>"verified"===e.status))&&void 0!==r?r:[]).length>0&&(n="aal2");let l=s.amr||[];return{data:{currentLevel:i,nextLevel:n,currentAuthenticationMethods:l},error:null}}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:n},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:o}=su(n.access_token),l=null;o.aal&&(l=o.aal);let c=l;return(null!==(i=null===(s=n.user.factors)||void 0===s?void 0:s.filter(e=>"verified"===e.status))&&void 0!==i?i:[]).length>0&&(c="aal2"),{data:{currentLevel:l,nextLevel:c,currentAuthenticationMethods:o.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await sR(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new rG})})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new rG});let n=await sR(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return n.data&&n.data.redirect_url&&st()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(n.data.redirect_url),n})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new rG});let n=await sR(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return n.data&&n.data.redirect_url&&st()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(n.data.redirect_url),n})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await sR(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new rG})})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await sR(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new rG})})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;let s=Date.now();if((r=this.jwks.keys.find(t=>t.kid===e))&&this.jwks_cached_at+6e5>s)return r;let{data:i,error:n}=await sR(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(n)throw n;return i.keys&&0!==i.keys.length&&(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(t=>t.kid===e))?r:null}async getClaims(e,t={}){try{let r=e;if(!r){let{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});r=e.session.access_token}let{header:s,payload:i,signature:n,raw:{header:a,payload:o}}=su(r);if(!(null==t?void 0:t.allowExpired))try{!function(e){if(!e)throw Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}(i.exp)}catch(e){throw new r2(e instanceof Error?e.message:"JWT validation failed")}let l=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks);if(!l){let{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:i,header:s,signature:n},error:null}}let c=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw Error("Invalid alg claim")}}(s.alg),u=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!await crypto.subtle.verify(c,u,n,function(e){let t=[];return function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127){t(e);return}if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}(s,t)}}(e,e=>t.push(e)),new Uint8Array(t)}(`${a}.${o}`)))throw new r2("Invalid JWT signature");return{data:{claims:i,header:s,signature:n},error:null}}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async signInWithPasskey(e){var t,r,s;sw(this.experimental);try{if(!sz())return this._returnResult({data:null,error:new rV("Browser does not support WebAuthn",null)});let{data:i,error:n}=await this._startPasskeyAuthentication({options:{captchaToken:null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.captchaToken}});if(n||!i)return this._returnResult({data:null,error:n});let a=sW(i.options),o=null!==(s=null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.signal)&&void 0!==s?s:sH.createNewAbortSignal(),{data:l,error:c}=await sX({publicKey:a,signal:o});if(c||!l)return this._returnResult({data:null,error:null!=c?c:new rV("WebAuthn ceremony failed",null)});let u=sK(l);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:u})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async registerPasskey(e){var t,r;sw(this.experimental);try{if(!sz())return this._returnResult({data:null,error:new rV("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let n=sV(s.options),a=null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.signal)&&void 0!==r?r:sH.createNewAbortSignal(),{data:o,error:l}=await sJ({publicKey:n,signal:a});if(l||!o)return this._returnResult({data:null,error:null!=l?l:new rV("WebAuthn ceremony failed",null)});let c=sG(o);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:c})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyRegistration(){sw(this.experimental);try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new rG});let{data:s,error:i}=await sR(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){sw(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new rG});let{data:i,error:n}=await sR(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:i,error:null})})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyAuthentication(e){var t;sw(this.experimental);try{let{data:r,error:s}=await sR(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.captchaToken}}});if(s)return this._returnResult({data:null,error:s});return this._returnResult({data:r,error:null})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyAuthentication(e){sw(this.experimental);try{let{data:t,error:r}=await sR(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:sA});if(r)return this._returnResult({data:null,error:r});return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _listPasskeys(){sw(this.experimental);try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new rG});let{data:s,error:i}=await sR(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){sw(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new rG});let{data:i,error:n}=await sR(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:i,error:null})})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}async _deletePasskey(e){sw(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new rG});let{error:i}=await sR(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(e){if(rq(e))return this._returnResult({data:null,error:e});throw e}}}s3.nextInstanceID={};let s4=s3,s6="";"undefined"!=typeof Deno?(s6="deno",a=null===(E=Deno.version)||void 0===E?void 0:E.deno):"undefined"!=typeof document?s6="web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?s6="react-native":(s6="node",a="undefined"!=typeof process?null===(R=process.version)||void 0===R?void 0:R.replace(/^v/,""):void 0);let s5=[`runtime=${s6}`];a&&s5.push(`runtime-version=${a}`);let s8={headers:{"X-Client-Info":`supabase-js/2.108.0; ${s5.join("; ")}`}},s9={schema:"public"},s7={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ie={},it={enabled:!1,respectSamplingDecision:!0},ir=null;function is(e){return(is="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ii(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function ia(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ii(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=is(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=is(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==is(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ii(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}let io=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),il=()=>Headers,ic=(e,t,r,s,i)=>{let n=io(s),a=il(),o=(null==i?void 0:i.enabled)===!0,l=(null==i?void 0:i.respectSamplingDecision)!==!1,c=o?function(e){let t=[];try{let r=new URL(e);t.push(r.hostname)}catch(e){}return t.push("*.supabase.co","*.supabase.in"),t.push("localhost","127.0.0.1","[::1]"),t}(t):null;return async(t,s)=>{var i;let o=null!==(i=await r())&&void 0!==i?i:e,u=new a(null==s?void 0:s.headers);if(u.has("apikey")||u.set("apikey",e),u.has("Authorization")||u.set("Authorization",`Bearer ${o}`),c){let e=await iu(t,c,l);e&&(e.traceparent&&!u.has("traceparent")&&u.set("traceparent",e.traceparent),e.tracestate&&!u.has("tracestate")&&u.set("tracestate",e.tracestate),e.baggage&&!u.has("baggage")&&u.set("baggage",e.baggage))}return n(t,ia(ia({},s),{},{headers:u}))}};async function iu(e,t,r){if(!function(e,t){let r;if(!e||!t||0===t.length)return!1;if(e instanceof URL)r=e;else try{r=new URL(e)}catch(e){return!1}for(let e of t)try{if("string"==typeof e){if(function(e,t){if(t===e)return!0;if(t.startsWith("*.")){let r=t.slice(2);if(e.endsWith(r)&&(e===r||e.endsWith("."+r)))return!0}return!1}(r.hostname,e))return!0}else if(e instanceof RegExp){if(e.test(r.hostname))return!0}else if("function"==typeof e&&e(r))return!0}catch(e){continue}return!1}("string"==typeof e?e:e instanceof URL?e:e.url,t))return null;let s=await function(){var e,t,r,s;return e=this,t=void 0,r=void 0,s=function*(){try{let e=yield(null===ir&&(ir=import("@opentelemetry/api").catch(()=>null)),ir);if(!e||!e.propagation||!e.context)return null;let t={};e.propagation.inject(e.context.active(),t);let r=t.traceparent;if(!r)return null;return{traceparent:r,tracestate:t.tracestate,baggage:t.baggage}}catch(e){return null}},new(r||(r=Promise))(function(i,n){function a(e){try{l(s.next(e))}catch(e){n(e)}}function o(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(a,o)}l((s=s.apply(e,t||[])).next())})}();if(!s||!s.traceparent)return null;if(r){let e=function(e){if(!e||"string"!=typeof e)return null;let t=e.split("-");if(4!==t.length)return null;let[r,s,i,n]=t;if(2!==r.length||32!==s.length||16!==i.length||2!==n.length)return null;let a=/^[0-9a-f]+$/i;return a.test(r)&&a.test(s)&&a.test(i)&&a.test(n)&&"00000000000000000000000000000000"!==s&&"0000000000000000"!==i?{version:r,traceId:s,parentId:i,traceFlags:n,isSampled:(1&parseInt(n,16))==1}:null}(s.traceparent);if(e&&!e.isSampled)return null}return s}function ih(e){return"boolean"==typeof e?{enabled:e}:e}var id=class extends s4{constructor(e){super(e)}},ip=class{constructor(e,t,r){var s,i,n;this.supabaseUrl=e,this.supabaseKey=t;let a=function(e){let t=null==e?void 0:e.trim();if(!t)throw Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(t.endsWith("/")?t:t+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(e);if(!t)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);let o=`sb-${a.hostname.split(".")[0]}-auth-token`,l=function(e,t){var r,s,i,n,a,o;let{db:l,auth:c,realtime:u,global:h}=e,{db:d,auth:p,realtime:f,global:g}=t,m=ih(e.tracePropagation),b=ih(t.tracePropagation),y={db:ia(ia({},d),l),auth:ia(ia({},p),c),realtime:ia(ia({},f),u),storage:{},global:ia(ia(ia({},g),h),{},{headers:ia(ia({},null!==(r=null==g?void 0:g.headers)&&void 0!==r?r:{}),null!==(s=null==h?void 0:h.headers)&&void 0!==s?s:{})}),tracePropagation:{enabled:null!==(i=null!==(n=null==m?void 0:m.enabled)&&void 0!==n?n:null==b?void 0:b.enabled)&&void 0!==i&&i,respectSamplingDecision:null===(a=null!==(o=null==m?void 0:m.respectSamplingDecision)&&void 0!==o?o:null==b?void 0:b.respectSamplingDecision)||void 0===a||a},accessToken:async()=>""};return e.accessToken?y.accessToken=e.accessToken:delete y.accessToken,y}(null!=r?r:{},{db:s9,realtime:ie,auth:ia(ia({},s7),{},{storageKey:o}),global:s8,tracePropagation:it});this.settings=l,this.storageKey=null!==(s=l.auth.storageKey)&&void 0!==s?s:"",this.headers=null!==(i=l.global.headers)&&void 0!==i?i:{},l.accessToken?(this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(n=l.auth)&&void 0!==n?n:{},this.headers,l.global.fetch),this.fetch=ic(t,e,this._getAccessToken.bind(this),l.global.fetch,l.tracePropagation),this.realtime=this._initRealtimeClient(ia({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new ta(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new rN(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new e2(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();let{data:r}=await this.auth.getSession();return null!==(e=null===(t=r.session)||void 0===t?void 0:t.access_token)&&void 0!==e?e:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:n,flowType:a,lock:o,debug:l,throwOnError:c,experimental:u,lockAcquireTimeout:h,skipAutoInitialize:d},p,f){let g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new id({url:this.authUrl.href,headers:ia(ia({},g),p),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,flowType:a,lock:o,debug:l,throwOnError:c,experimental:u,fetch:f,lockAcquireTimeout:h,skipAutoInitialize:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new tY(this.realtimeUrl.href,ia(ia({},e),{},{params:ia(ia({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){("TOKEN_REFRESHED"===e||"SIGNED_IN"===e)&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}};let ig=(e,t,r)=>new ip(e,t,r);(function(){if("undefined"!=typeof window)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(null==t)return!1;let r=t.match(/^v(\d+)\./);return!!r&&18>=parseInt(r[1],10)})()&&console.warn("⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var im=r(322);let ib="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),iy=" 	\n\r=".split(""),iw=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<iy.length;t+=1)e[iy[t].charCodeAt(0)]=-2;for(let t=0;t<ib.length;t+=1)e[ib[t].charCodeAt(0)]=t;return e})();function iv(e){let t=[],r=0,s=0;if(function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127){t(e);return}if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}(s,t)}}(e,e=>{for(r=r<<8|e,s+=8;s>=6;){let e=r>>s-6&63;t.push(ib[e]),s-=6}}),s>0)for(r<<=6-s,s=6;s>=6;){let e=r>>s-6&63;t.push(ib[e]),s-=6}return t.join("")}function i_(){return"undefined"!=typeof window&&void 0!==window.document}im.Qc,im.qC;let ik=/^(.*)[.](0|[1-9][0-9]*)$/;function iS(e,t){if(e===t)return!0;let r=e.match(ik);return!!r&&r[1]===t}function iT(e,t,r){let s=r??3180,i=encodeURIComponent(t);if(i.length<=s)return[{name:e,value:t}];let n=[];for(;i.length>0;){let e=i.slice(0,s),t=e.lastIndexOf("%");t>s-3&&(e=e.slice(0,t));let r="";for(;e.length>0;)try{r=decodeURIComponent(e);break}catch(t){if(t instanceof URIError&&"%"===e.at(-3)&&e.length>3)e=e.slice(0,e.length-3);else throw t}n.push(r),i=i.slice(e.length)}return n.map((t,r)=>({name:`${e}.${r}`,value:t}))}async function iE(e,t){let r=await t(e);if(r)return r;let s=[];for(let r=0;;r++){let i=`${e}.${r}`,n=await t(i);if(!n)break;s.push(n)}return s.length>0?s.join(""):null}let iR={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4},iO="base64-";function iA(e){let t;if(!e.startsWith(iO))return e;try{t=function(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i=0,n=0;for(let t=0;t<e.length;t+=1){let a=iw[e.charCodeAt(t)];if(a>-1)for(i=i<<6|a,n+=6;n>=8;)(function(e,t,r){if(0===t.utf8seq){if(e<=127){r(e);return}for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}})(i>>n-8&255,s,r),n-=8;else if(-2===a)continue;else throw Error(`Invalid Base64-URL character "${e.at(t)}" at position ${t}`)}return t.join("")}(e.substring(iO.length))}catch(e){return console.warn("@supabase/ssr: could not base64url-decode chunked cookie value, treating as absent. Cookie chunks may have been written partially across responses.",e),null}try{JSON.parse(t)}catch{return console.warn("@supabase/ssr: chunked cookie decoded to invalid JSON, treating as absent. This usually indicates that cookie chunks from different writes were combined (e.g. response committed before all Set-Cookie headers were sent)."),null}return t}async function iP({getAll:e,setAll:t,setItems:r,removedItems:s},i){let n=i.cookieEncoding,a=i.cookieOptions??null,o=await e([...r?Object.keys(r):[],...s?Object.keys(s):[]]),l=o?.map(({name:e})=>e)||[],c=Object.keys(s).flatMap(e=>l.filter(t=>iS(t,e))),u=Object.keys(r).flatMap(e=>{let t=new Set(l.filter(t=>iS(t,e))),s=r[e];"base64url"===n&&(s=iO+iv(s));let i=iT(e,s);return i.forEach(e=>{t.delete(e.name)}),c.push(...t),i}),h={...iR,...a,maxAge:0},d={...iR,...a,maxAge:iR.maxAge};delete h.name,delete d.name;let p=h.domain&&c.length>0?(()=>{let{domain:e,...t}=h;return t})():null;await t([...c.map(e=>({name:e,value:"",options:h})),...p?c.map(e=>({name:e,value:"",options:p})):[],...u.map(({name:e,value:t})=>({name:e,value:t,options:d}))],{"Cache-Control":"private, no-cache, no-store, must-revalidate, max-age=0",Expires:"0",Pragma:"no-cache"})}let iC=!1,ix=["@supabase/auth-helpers-nextjs","@supabase/auth-helpers-react","@supabase/auth-helpers-remix","@supabase/auth-helpers-sveltekit"];async function iI(e){let t=eo.next({request:e}),r=function(e,t,r){if(!function(){if(iC||"undefined"==typeof process||!process.env?.npm_package_name)return;let e=process.env.npm_package_name;ix.includes(e)&&(iC=!0,console.warn(`
╔════════════════════════════════════════════════════════════════════════════╗
║ ⚠️  IMPORTANT: Package Consolidation Notice                                ║
║                                                                            ║
║ The ${e.padEnd(35)} package name is deprecated.  ║
║                                                                            ║
║ You are now using @supabase/ssr - a unified solution for all frameworks.  ║
║                                                                            ║
║ The auth-helpers packages have been consolidated into @supabase/ssr       ║
║ to provide better maintenance and consistent APIs across frameworks.      ║
║                                                                            ║
║ Please update your package.json to use @supabase/ssr directly:            ║
║   npm uninstall ${e.padEnd(42)} ║
║   npm install @supabase/ssr                                               ║
║                                                                            ║
║ For more information, visit:                                              ║
║ https://supabase.com/docs/guides/auth/server-side                         ║
╚════════════════════════════════════════════════════════════════════════════╝
    `))}(),!e||!t)throw Error(`Your project's URL and Key are required to create a Supabase client!

Check your Supabase project's API settings to find these values

https://supabase.com/dashboard/project/_/settings/api`);let{storage:s,getAll:i,setAll:n,setItems:a,removedItems:o}=function(e,t){let r,s;let i=e.cookies??null,n=e.cookieEncoding,a={},o={},l=()=>{let e=(0,im.Qc)(document.cookie);return Object.keys(e).map(t=>({name:t,value:e[t]??""}))},c=e=>{e.forEach(({name:e,value:t,options:r})=>{document.cookie=(0,im.qC)(e,t,r)})};if(i){if("get"in i){let e=async e=>{let t=e.flatMap(e=>[e,...Array.from({length:5}).map((t,r)=>`${e}.${r}`)]),r=[];for(let e=0;e<t.length;e+=1){let s=await i.get(t[e]);(s||"string"==typeof s)&&r.push({name:t[e],value:s})}return r};if(r=async t=>await e(t),"set"in i&&"remove"in i)s=async e=>{for(let t=0;t<e.length;t+=1){let{name:r,value:s,options:n}=e[t];s?await i.set(r,s,n):await i.remove(r,n)}};else if(t)s=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness. Consider switching to the getAll and setAll cookie methods instead of get, set and remove which are deprecated and can be difficult to use correctly.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring a getAll and setAll cookie method (deprecated: alternatively both get, set and remove can be used)")}else if("getAll"in i){if(r=async()=>await i.getAll(),"setAll"in i)s=i.setAll;else if(t)s=async()=>{console.warn("@supabase/ssr: createServerClient was configured without the setAll cookie method, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring both getAll and setAll cookie methods (deprecated: alternatively both get, set and remove can be used)")}else if(!t&&i_())r=()=>l(),s=c;else throw Error(`@supabase/ssr: ${t?"createServerClient":"createBrowserClient"} requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).${i_()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""}`)}else if(!t&&i_())r=()=>l(),s=c;else if(t)throw Error("@supabase/ssr: createServerClient must be initialized with cookie options that specify getAll and setAll functions (deprecated, not recommended: alternatively use get, set and remove)");else r=()=>[],s=()=>{throw Error("@supabase/ssr: createBrowserClient in non-browser runtimes (including Next.js pre-rendering mode) was not initialized cookie options that specify getAll and setAll functions (deprecated: alternatively use get, set and remove), but they were needed")};return t?{getAll:r,setAll:s,setItems:a,removedItems:o,storage:{isServer:!0,getItem:async e=>{if("string"==typeof a[e])return a[e];if(o[e])return null;let t=await r([e]),s=await iE(e,async e=>{let r=t?.find(({name:t})=>t===e)||null;return r?r.value:null});return s?"string"!=typeof s?s:iA(s):null},setItem:async(t,i)=>{t.endsWith("-code-verifier")&&await iP({getAll:r,setAll:s,setItems:{[t]:i},removedItems:{}},{cookieOptions:e?.cookieOptions??null,cookieEncoding:n}),a[t]=i,delete o[t]},removeItem:async e=>{delete a[e],o[e]=!0}}}:{getAll:r,setAll:s,setItems:a,removedItems:o,storage:{isServer:!1,getItem:async e=>{let t=await r([e]),s=await iE(e,async e=>{let r=t?.find(({name:t})=>t===e)||null;return r?r.value:null});return s?iA(s):null},setItem:async(t,i)=>{let a=await r([t]),o=new Set((a?.map(({name:e})=>e)||[]).filter(e=>iS(e,t))),l=i;"base64url"===n&&(l=iO+iv(i));let c=iT(t,l);c.forEach(({name:e})=>{o.delete(e)});let u={...iR,...e?.cookieOptions,maxAge:0},h={...iR,...e?.cookieOptions,maxAge:iR.maxAge};delete u.name,delete h.name;let d=u.domain?(()=>{let{domain:e,...t}=u;return t})():null,p=[...[...o].map(e=>({name:e,value:"",options:u})),...d?[...o].map(e=>({name:e,value:"",options:d})):[],...c.map(({name:e,value:t})=>({name:e,value:t,options:h}))];p.length>0&&await s(p,{})},removeItem:async t=>{let i=await r([t]),n=(i?.map(({name:e})=>e)||[]).filter(e=>iS(e,t));if(0===n.length)return;let a={...iR,...e?.cookieOptions,maxAge:0};delete a.name;let o=n.map(e=>({name:e,value:"",options:a}));if(a.domain){let{domain:e,...t}=a;o.push(...n.map(e=>({name:e,value:"",options:t})))}await s(o,{})}}}}({...r,cookieEncoding:r?.cookieEncoding??"base64url"},!0),l=ig(e,t,{...r,global:{...r?.global,headers:{...r?.global?.headers,"X-Client-Info":"supabase-ssr/0.12.0 createServerClient"}},auth:{...r?.cookieOptions?.name?{storageKey:r.cookieOptions.name}:null,...r?.auth,flowType:"pkce",autoRefreshToken:!1,detectSessionInUrl:!1,persistSession:!0,skipAutoInitialize:!0,storage:s,...r?.cookies&&"encode"in r.cookies&&"tokens-only"===r.cookies.encode?{userStorage:r?.auth?.userStorage??function(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}()}:null}});return l.auth.onAuthStateChange(async e=>{(Object.keys(a).length>0||Object.keys(o).length>0)&&("SIGNED_IN"===e||"TOKEN_REFRESHED"===e||"USER_UPDATED"===e||"PASSWORD_RECOVERY"===e||"SIGNED_OUT"===e||"MFA_CHALLENGE_VERIFIED"===e)&&await iP({getAll:i,setAll:n,setItems:a,removedItems:o},{cookieOptions:r?.cookieOptions??null,cookieEncoding:r?.cookieEncoding??"base64url"})}),l}("https://dummy.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.dummy",{cookies:{getAll:()=>e.cookies.getAll(),setAll(r){r.forEach(({name:t,value:r})=>e.cookies.set(t,r)),t=eo.next({request:e}),r.forEach(({name:e,value:r,options:s})=>t.cookies.set(e,r,s))}}}),{data:{user:s}}=await r.auth.getUser(),i=e.nextUrl.pathname,n=["/dashboard","/generator","/history","/templates","/products","/settings","/storyboard","/ugc-generator"].some(e=>i.startsWith(e));if(!s&&n){let t=e.nextUrl.clone();return t.pathname="/auth/login",eo.redirect(t)}if(i.startsWith("/admin")){if(!s){let t=e.nextUrl.clone();return t.pathname="/auth/login",eo.redirect(t)}let{data:t}=await r.from("profiles").select("role").eq("id",s.id).single();if(!t||"admin"!==t.role){let t=e.nextUrl.clone();return t.pathname="/dashboard",t.searchParams.set("error","unauthorized"),eo.redirect(t)}}if(s&&i.startsWith("/auth")){let t=e.nextUrl.clone();return t.pathname="/dashboard",eo.redirect(t)}return t}r(340),"undefined"==typeof URLPattern||URLPattern;let ij="nodejs";async function iN(e){return await iI(e)}let i$={matcher:["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"]},iL={...O},iD=iL.middleware||iL.default,iU="/src/middleware";if("function"!=typeof iD)throw Error(`The Middleware "${iU}" must export a \`middleware\` or a \`default\` function`);function iM(e){return eJ({...e,page:iU,handler:iD})}},322:(e,t)=>{"use strict";t.Qc=function(e,t){let r=new o,s=e.length;if(s<2)return r;let i=t?.decode||u,n=0;do{let t=function(e,t,r){let s=e.indexOf("=",t);return s<r?s:-1}(e,n,s);if(-1===t)break;let a=function(e,t,r){let s=e.indexOf(";",t);return -1===s?r:s}(e,n,s);if(t>a){n=e.lastIndexOf(";",t-1)+1;continue}let o=c(e,n,t);void 0===r[o]&&(r[o]=i(c(e,t+1,a))),n=a+1}while(n<s);return r},t.qC=l,t.qC=l;let r=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,s=/^[\u0021-\u003A\u003C-\u007E]*$/,i=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,n=/^[\u0020-\u003A\u003D-\u007E]*$/,a=Object.prototype.toString,o=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function l(e,t,o){let l="object"==typeof e?e:{...o,name:e,value:String(t)},c=("object"==typeof t?t:o)?.encode||encodeURIComponent;if(!r.test(l.name))throw TypeError(`argument name is invalid: ${l.name}`);let u=l.value?c(l.value):"";if(!s.test(u))throw TypeError(`argument val is invalid: ${l.value}`);let h=l.name+"="+u;if(void 0!==l.maxAge){if(!Number.isInteger(l.maxAge))throw TypeError(`option maxAge is invalid: ${l.maxAge}`);h+="; Max-Age="+l.maxAge}if(l.domain){if(!i.test(l.domain))throw TypeError(`option domain is invalid: ${l.domain}`);h+="; Domain="+l.domain}if(l.path){if(!n.test(l.path))throw TypeError(`option path is invalid: ${l.path}`);h+="; Path="+l.path}if(l.expires){var d;if(d=l.expires,"[object Date]"!==a.call(d)||!Number.isFinite(l.expires.valueOf()))throw TypeError(`option expires is invalid: ${l.expires}`);h+="; Expires="+l.expires.toUTCString()}if(l.httpOnly&&(h+="; HttpOnly"),l.secure&&(h+="; Secure"),l.partitioned&&(h+="; Partitioned"),l.priority)switch("string"==typeof l.priority?l.priority.toLowerCase():void 0){case"low":h+="; Priority=Low";break;case"medium":h+="; Priority=Medium";break;case"high":h+="; Priority=High";break;default:throw TypeError(`option priority is invalid: ${l.priority}`)}if(l.sameSite)switch("string"==typeof l.sameSite?l.sameSite.toLowerCase():l.sameSite){case!0:case"strict":h+="; SameSite=Strict";break;case"lax":h+="; SameSite=Lax";break;case"none":h+="; SameSite=None";break;default:throw TypeError(`option sameSite is invalid: ${l.sameSite}`)}return h}function c(e,t,r){let s=t,i=r;do{let t=e.charCodeAt(s);if(32!==t&&9!==t)break}while(++s<i);for(;i>s;){let t=e.charCodeAt(i-1);if(32!==t&&9!==t)break;i--}return e.slice(s,i)}function u(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch(t){return e}}},945:e=>{"use strict";var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,n={};function a(e){var t;let r=["path"in e&&e.path&&`Path=${e.path}`,"expires"in e&&(e.expires||0===e.expires)&&`Expires=${("number"==typeof e.expires?new Date(e.expires):e.expires).toUTCString()}`,"maxAge"in e&&"number"==typeof e.maxAge&&`Max-Age=${e.maxAge}`,"domain"in e&&e.domain&&`Domain=${e.domain}`,"secure"in e&&e.secure&&"Secure","httpOnly"in e&&e.httpOnly&&"HttpOnly","sameSite"in e&&e.sameSite&&`SameSite=${e.sameSite}`,"partitioned"in e&&e.partitioned&&"Partitioned","priority"in e&&e.priority&&`Priority=${e.priority}`].filter(Boolean),s=`${e.name}=${encodeURIComponent(null!=(t=e.value)?t:"")}`;return 0===r.length?s:`${s}; ${r.join("; ")}`}function o(e){let t=new Map;for(let r of e.split(/; */)){if(!r)continue;let e=r.indexOf("=");if(-1===e){t.set(r,"true");continue}let[s,i]=[r.slice(0,e),r.slice(e+1)];try{t.set(s,decodeURIComponent(null!=i?i:"true"))}catch{}}return t}function l(e){var t,r;if(!e)return;let[[s,i],...n]=o(e),{domain:a,expires:l,httponly:h,maxage:d,path:p,samesite:f,secure:g,partitioned:m,priority:b}=Object.fromEntries(n.map(([e,t])=>[e.toLowerCase(),t]));return function(e){let t={};for(let r in e)e[r]&&(t[r]=e[r]);return t}({name:s,value:decodeURIComponent(i),domain:a,...l&&{expires:new Date(l)},...h&&{httpOnly:!0},..."string"==typeof d&&{maxAge:Number(d)},path:p,...f&&{sameSite:c.includes(t=(t=f).toLowerCase())?t:void 0},...g&&{secure:!0},...b&&{priority:u.includes(r=(r=b).toLowerCase())?r:void 0},...m&&{partitioned:!0}})}((e,r)=>{for(var s in r)t(e,s,{get:r[s],enumerable:!0})})(n,{RequestCookies:()=>h,ResponseCookies:()=>d,parseCookie:()=>o,parseSetCookie:()=>l,stringifyCookie:()=>a}),e.exports=((e,n,a,o)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let l of s(n))i.call(e,l)||l===a||t(e,l,{get:()=>n[l],enumerable:!(o=r(n,l))||o.enumerable});return e})(t({},"__esModule",{value:!0}),n);var c=["strict","lax","none"],u=["low","medium","high"],h=class{constructor(e){this._parsed=new Map,this._headers=e;let t=e.get("cookie");if(t)for(let[e,r]of o(t))this._parsed.set(e,{name:e,value:r})}[Symbol.iterator](){return this._parsed[Symbol.iterator]()}get size(){return this._parsed.size}get(...e){let t="string"==typeof e[0]?e[0]:e[0].name;return this._parsed.get(t)}getAll(...e){var t;let r=Array.from(this._parsed);if(!e.length)return r.map(([e,t])=>t);let s="string"==typeof e[0]?e[0]:null==(t=e[0])?void 0:t.name;return r.filter(([e])=>e===s).map(([e,t])=>t)}has(e){return this._parsed.has(e)}set(...e){let[t,r]=1===e.length?[e[0].name,e[0].value]:e,s=this._parsed;return s.set(t,{name:t,value:r}),this._headers.set("cookie",Array.from(s).map(([e,t])=>a(t)).join("; ")),this}delete(e){let t=this._parsed,r=Array.isArray(e)?e.map(e=>t.delete(e)):t.delete(e);return this._headers.set("cookie",Array.from(t).map(([e,t])=>a(t)).join("; ")),r}clear(){return this.delete(Array.from(this._parsed.keys())),this}[Symbol.for("edge-runtime.inspect.custom")](){return`RequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(e=>`${e.name}=${encodeURIComponent(e.value)}`).join("; ")}},d=class{constructor(e){var t,r,s;this._parsed=new Map,this._headers=e;let i=null!=(s=null!=(r=null==(t=e.getSetCookie)?void 0:t.call(e))?r:e.get("set-cookie"))?s:[];for(let e of Array.isArray(i)?i:function(e){if(!e)return[];var t,r,s,i,n,a=[],o=0;function l(){for(;o<e.length&&/\s/.test(e.charAt(o));)o+=1;return o<e.length}for(;o<e.length;){for(t=o,n=!1;l();)if(","===(r=e.charAt(o))){for(s=o,o+=1,l(),i=o;o<e.length&&"="!==(r=e.charAt(o))&&";"!==r&&","!==r;)o+=1;o<e.length&&"="===e.charAt(o)?(n=!0,o=i,a.push(e.substring(t,s)),t=o):o=s+1}else o+=1;(!n||o>=e.length)&&a.push(e.substring(t,e.length))}return a}(i)){let t=l(e);t&&this._parsed.set(t.name,t)}}get(...e){let t="string"==typeof e[0]?e[0]:e[0].name;return this._parsed.get(t)}getAll(...e){var t;let r=Array.from(this._parsed.values());if(!e.length)return r;let s="string"==typeof e[0]?e[0]:null==(t=e[0])?void 0:t.name;return r.filter(e=>e.name===s)}has(e){return this._parsed.has(e)}set(...e){let[t,r,s]=1===e.length?[e[0].name,e[0].value,e[0]]:e,i=this._parsed;return i.set(t,function(e={name:"",value:""}){return"number"==typeof e.expires&&(e.expires=new Date(e.expires)),e.maxAge&&(e.expires=new Date(Date.now()+1e3*e.maxAge)),(null===e.path||void 0===e.path)&&(e.path="/"),e}({name:t,value:r,...s})),function(e,t){for(let[,r]of(t.delete("set-cookie"),e)){let e=a(r);t.append("set-cookie",e)}}(i,this._headers),this}delete(...e){let[t,r,s]="string"==typeof e[0]?[e[0]]:[e[0].name,e[0].path,e[0].domain];return this.set({name:t,path:r,domain:s,value:"",expires:new Date(0)})}[Symbol.for("edge-runtime.inspect.custom")](){return`ResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(a).join("; ")}}},439:(e,t,r)=>{(()=>{"use strict";var t={491:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextAPI=void 0;let s=r(223),i=r(172),n=r(930),a="context",o=new s.NoopContextManager;class l{constructor(){}static getInstance(){return this._instance||(this._instance=new l),this._instance}setGlobalContextManager(e){return(0,i.registerGlobal)(a,e,n.DiagAPI.instance())}active(){return this._getContextManager().active()}with(e,t,r,...s){return this._getContextManager().with(e,t,r,...s)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return(0,i.getGlobal)(a)||o}disable(){this._getContextManager().disable(),(0,i.unregisterGlobal)(a,n.DiagAPI.instance())}}t.ContextAPI=l},930:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagAPI=void 0;let s=r(56),i=r(912),n=r(957),a=r(172);class o{constructor(){function e(e){return function(...t){let r=(0,a.getGlobal)("diag");if(r)return r[e](...t)}}let t=this;t.setLogger=(e,r={logLevel:n.DiagLogLevel.INFO})=>{var s,o,l;if(e===t){let e=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error(null!==(s=e.stack)&&void 0!==s?s:e.message),!1}"number"==typeof r&&(r={logLevel:r});let c=(0,a.getGlobal)("diag"),u=(0,i.createLogLevelDiagLogger)(null!==(o=r.logLevel)&&void 0!==o?o:n.DiagLogLevel.INFO,e);if(c&&!r.suppressOverrideMessage){let e=null!==(l=Error().stack)&&void 0!==l?l:"<failed to generate stacktrace>";c.warn(`Current logger will be overwritten from ${e}`),u.warn(`Current logger will overwrite one already registered from ${e}`)}return(0,a.registerGlobal)("diag",u,t,!0)},t.disable=()=>{(0,a.unregisterGlobal)("diag",t)},t.createComponentLogger=e=>new s.DiagComponentLogger(e),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}static instance(){return this._instance||(this._instance=new o),this._instance}}t.DiagAPI=o},653:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetricsAPI=void 0;let s=r(660),i=r(172),n=r(930),a="metrics";class o{constructor(){}static getInstance(){return this._instance||(this._instance=new o),this._instance}setGlobalMeterProvider(e){return(0,i.registerGlobal)(a,e,n.DiagAPI.instance())}getMeterProvider(){return(0,i.getGlobal)(a)||s.NOOP_METER_PROVIDER}getMeter(e,t,r){return this.getMeterProvider().getMeter(e,t,r)}disable(){(0,i.unregisterGlobal)(a,n.DiagAPI.instance())}}t.MetricsAPI=o},181:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PropagationAPI=void 0;let s=r(172),i=r(874),n=r(194),a=r(277),o=r(369),l=r(930),c="propagation",u=new i.NoopTextMapPropagator;class h{constructor(){this.createBaggage=o.createBaggage,this.getBaggage=a.getBaggage,this.getActiveBaggage=a.getActiveBaggage,this.setBaggage=a.setBaggage,this.deleteBaggage=a.deleteBaggage}static getInstance(){return this._instance||(this._instance=new h),this._instance}setGlobalPropagator(e){return(0,s.registerGlobal)(c,e,l.DiagAPI.instance())}inject(e,t,r=n.defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,r)}extract(e,t,r=n.defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,r)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,s.unregisterGlobal)(c,l.DiagAPI.instance())}_getGlobalPropagator(){return(0,s.getGlobal)(c)||u}}t.PropagationAPI=h},997:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceAPI=void 0;let s=r(172),i=r(846),n=r(139),a=r(607),o=r(930),l="trace";class c{constructor(){this._proxyTracerProvider=new i.ProxyTracerProvider,this.wrapSpanContext=n.wrapSpanContext,this.isSpanContextValid=n.isSpanContextValid,this.deleteSpan=a.deleteSpan,this.getSpan=a.getSpan,this.getActiveSpan=a.getActiveSpan,this.getSpanContext=a.getSpanContext,this.setSpan=a.setSpan,this.setSpanContext=a.setSpanContext}static getInstance(){return this._instance||(this._instance=new c),this._instance}setGlobalTracerProvider(e){let t=(0,s.registerGlobal)(l,this._proxyTracerProvider,o.DiagAPI.instance());return t&&this._proxyTracerProvider.setDelegate(e),t}getTracerProvider(){return(0,s.getGlobal)(l)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){(0,s.unregisterGlobal)(l,o.DiagAPI.instance()),this._proxyTracerProvider=new i.ProxyTracerProvider}}t.TraceAPI=c},277:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteBaggage=t.setBaggage=t.getActiveBaggage=t.getBaggage=void 0;let s=r(491),i=(0,r(780).createContextKey)("OpenTelemetry Baggage Key");function n(e){return e.getValue(i)||void 0}t.getBaggage=n,t.getActiveBaggage=function(){return n(s.ContextAPI.getInstance().active())},t.setBaggage=function(e,t){return e.setValue(i,t)},t.deleteBaggage=function(e){return e.deleteValue(i)}},993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BaggageImpl=void 0;class r{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let t=this._entries.get(e);if(t)return Object.assign({},t)}getAllEntries(){return Array.from(this._entries.entries()).map(([e,t])=>[e,t])}setEntry(e,t){let s=new r(this._entries);return s._entries.set(e,t),s}removeEntry(e){let t=new r(this._entries);return t._entries.delete(e),t}removeEntries(...e){let t=new r(this._entries);for(let r of e)t._entries.delete(r);return t}clear(){return new r}}t.BaggageImpl=r},830:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.baggageEntryMetadataSymbol=void 0,t.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")},369:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.baggageEntryMetadataFromString=t.createBaggage=void 0;let s=r(930),i=r(993),n=r(830),a=s.DiagAPI.instance();t.createBaggage=function(e={}){return new i.BaggageImpl(new Map(Object.entries(e)))},t.baggageEntryMetadataFromString=function(e){return"string"!=typeof e&&(a.error(`Cannot create baggage metadata from unknown type: ${typeof e}`),e=""),{__TYPE__:n.baggageEntryMetadataSymbol,toString:()=>e}}},67:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.context=void 0;let s=r(491);t.context=s.ContextAPI.getInstance()},223:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopContextManager=void 0;let s=r(780);class i{active(){return s.ROOT_CONTEXT}with(e,t,r,...s){return t.call(r,...s)}bind(e,t){return t}enable(){return this}disable(){return this}}t.NoopContextManager=i},780:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ROOT_CONTEXT=t.createContextKey=void 0,t.createContextKey=function(e){return Symbol.for(e)};class r{constructor(e){let t=this;t._currentContext=e?new Map(e):new Map,t.getValue=e=>t._currentContext.get(e),t.setValue=(e,s)=>{let i=new r(t._currentContext);return i._currentContext.set(e,s),i},t.deleteValue=e=>{let s=new r(t._currentContext);return s._currentContext.delete(e),s}}}t.ROOT_CONTEXT=new r},506:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diag=void 0;let s=r(930);t.diag=s.DiagAPI.instance()},56:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagComponentLogger=void 0;let s=r(172);class i{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return n("debug",this._namespace,e)}error(...e){return n("error",this._namespace,e)}info(...e){return n("info",this._namespace,e)}warn(...e){return n("warn",this._namespace,e)}verbose(...e){return n("verbose",this._namespace,e)}}function n(e,t,r){let i=(0,s.getGlobal)("diag");if(i)return r.unshift(t),i[e](...r)}t.DiagComponentLogger=i},972:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagConsoleLogger=void 0;let r=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];class s{constructor(){for(let e=0;e<r.length;e++)this[r[e].n]=function(e){return function(...t){if(console){let r=console[e];if("function"!=typeof r&&(r=console.log),"function"==typeof r)return r.apply(console,t)}}}(r[e].c)}}t.DiagConsoleLogger=s},912:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createLogLevelDiagLogger=void 0;let s=r(957);t.createLogLevelDiagLogger=function(e,t){function r(r,s){let i=t[r];return"function"==typeof i&&e>=s?i.bind(t):function(){}}return e<s.DiagLogLevel.NONE?e=s.DiagLogLevel.NONE:e>s.DiagLogLevel.ALL&&(e=s.DiagLogLevel.ALL),t=t||{},{error:r("error",s.DiagLogLevel.ERROR),warn:r("warn",s.DiagLogLevel.WARN),info:r("info",s.DiagLogLevel.INFO),debug:r("debug",s.DiagLogLevel.DEBUG),verbose:r("verbose",s.DiagLogLevel.VERBOSE)}}},957:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagLogLevel=void 0,function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"}(t.DiagLogLevel||(t.DiagLogLevel={}))},172:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unregisterGlobal=t.getGlobal=t.registerGlobal=void 0;let s=r(200),i=r(521),n=r(130),a=i.VERSION.split(".")[0],o=Symbol.for(`opentelemetry.js.api.${a}`),l=s._globalThis;t.registerGlobal=function(e,t,r,s=!1){var n;let a=l[o]=null!==(n=l[o])&&void 0!==n?n:{version:i.VERSION};if(!s&&a[e]){let t=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return r.error(t.stack||t.message),!1}if(a.version!==i.VERSION){let t=Error(`@opentelemetry/api: Registration of version v${a.version} for ${e} does not match previously registered API v${i.VERSION}`);return r.error(t.stack||t.message),!1}return a[e]=t,r.debug(`@opentelemetry/api: Registered a global for ${e} v${i.VERSION}.`),!0},t.getGlobal=function(e){var t,r;let s=null===(t=l[o])||void 0===t?void 0:t.version;if(s&&(0,n.isCompatible)(s))return null===(r=l[o])||void 0===r?void 0:r[e]},t.unregisterGlobal=function(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${i.VERSION}.`);let r=l[o];r&&delete r[e]}},130:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isCompatible=t._makeCompatibilityCheck=void 0;let s=r(521),i=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function n(e){let t=new Set([e]),r=new Set,s=e.match(i);if(!s)return()=>!1;let n={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};if(null!=n.prerelease)return function(t){return t===e};function a(e){return r.add(e),!1}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;let s=e.match(i);if(!s)return a(e);let o={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};return null!=o.prerelease||n.major!==o.major?a(e):0===n.major?n.minor===o.minor&&n.patch<=o.patch?(t.add(e),!0):a(e):n.minor<=o.minor?(t.add(e),!0):a(e)}}t._makeCompatibilityCheck=n,t.isCompatible=n(s.VERSION)},886:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.metrics=void 0;let s=r(653);t.metrics=s.MetricsAPI.getInstance()},901:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueType=void 0,function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"}(t.ValueType||(t.ValueType={}))},102:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createNoopMeter=t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=t.NOOP_OBSERVABLE_GAUGE_METRIC=t.NOOP_OBSERVABLE_COUNTER_METRIC=t.NOOP_UP_DOWN_COUNTER_METRIC=t.NOOP_HISTOGRAM_METRIC=t.NOOP_COUNTER_METRIC=t.NOOP_METER=t.NoopObservableUpDownCounterMetric=t.NoopObservableGaugeMetric=t.NoopObservableCounterMetric=t.NoopObservableMetric=t.NoopHistogramMetric=t.NoopUpDownCounterMetric=t.NoopCounterMetric=t.NoopMetric=t.NoopMeter=void 0;class r{constructor(){}createHistogram(e,r){return t.NOOP_HISTOGRAM_METRIC}createCounter(e,r){return t.NOOP_COUNTER_METRIC}createUpDownCounter(e,r){return t.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,r){return t.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,r){return t.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,r){return t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}t.NoopMeter=r;class s{}t.NoopMetric=s;class i extends s{add(e,t){}}t.NoopCounterMetric=i;class n extends s{add(e,t){}}t.NoopUpDownCounterMetric=n;class a extends s{record(e,t){}}t.NoopHistogramMetric=a;class o{addCallback(e){}removeCallback(e){}}t.NoopObservableMetric=o;class l extends o{}t.NoopObservableCounterMetric=l;class c extends o{}t.NoopObservableGaugeMetric=c;class u extends o{}t.NoopObservableUpDownCounterMetric=u,t.NOOP_METER=new r,t.NOOP_COUNTER_METRIC=new i,t.NOOP_HISTOGRAM_METRIC=new a,t.NOOP_UP_DOWN_COUNTER_METRIC=new n,t.NOOP_OBSERVABLE_COUNTER_METRIC=new l,t.NOOP_OBSERVABLE_GAUGE_METRIC=new c,t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new u,t.createNoopMeter=function(){return t.NOOP_METER}},660:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NOOP_METER_PROVIDER=t.NoopMeterProvider=void 0;let s=r(102);class i{getMeter(e,t,r){return s.NOOP_METER}}t.NoopMeterProvider=i,t.NOOP_METER_PROVIDER=new i},200:function(e,t,r){var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||s(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(46),t)},651:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._globalThis=void 0,t._globalThis="object"==typeof globalThis?globalThis:r.g},46:function(e,t,r){var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||s(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(651),t)},939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.propagation=void 0;let s=r(181);t.propagation=s.PropagationAPI.getInstance()},874:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTextMapPropagator=void 0;class r{inject(e,t){}extract(e,t){return e}fields(){return[]}}t.NoopTextMapPropagator=r},194:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultTextMapSetter=t.defaultTextMapGetter=void 0,t.defaultTextMapGetter={get(e,t){if(null!=e)return e[t]},keys:e=>null==e?[]:Object.keys(e)},t.defaultTextMapSetter={set(e,t,r){null!=e&&(e[t]=r)}}},845:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.trace=void 0;let s=r(997);t.trace=s.TraceAPI.getInstance()},403:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NonRecordingSpan=void 0;let s=r(476);class i{constructor(e=s.INVALID_SPAN_CONTEXT){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}t.NonRecordingSpan=i},614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTracer=void 0;let s=r(491),i=r(607),n=r(403),a=r(139),o=s.ContextAPI.getInstance();class l{startSpan(e,t,r=o.active()){if(null==t?void 0:t.root)return new n.NonRecordingSpan;let s=r&&(0,i.getSpanContext)(r);return"object"==typeof s&&"string"==typeof s.spanId&&"string"==typeof s.traceId&&"number"==typeof s.traceFlags&&(0,a.isSpanContextValid)(s)?new n.NonRecordingSpan(s):new n.NonRecordingSpan}startActiveSpan(e,t,r,s){let n,a,l;if(arguments.length<2)return;2==arguments.length?l=t:3==arguments.length?(n=t,l=r):(n=t,a=r,l=s);let c=null!=a?a:o.active(),u=this.startSpan(e,n,c),h=(0,i.setSpan)(c,u);return o.with(h,l,void 0,u)}}t.NoopTracer=l},124:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTracerProvider=void 0;let s=r(614);class i{getTracer(e,t,r){return new s.NoopTracer}}t.NoopTracerProvider=i},125:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyTracer=void 0;let s=new(r(614)).NoopTracer;class i{constructor(e,t,r,s){this._provider=e,this.name=t,this.version=r,this.options=s}startSpan(e,t,r){return this._getTracer().startSpan(e,t,r)}startActiveSpan(e,t,r,s){let i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):s}}t.ProxyTracer=i},846:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyTracerProvider=void 0;let s=r(125),i=new(r(124)).NoopTracerProvider;class n{getTracer(e,t,r){var i;return null!==(i=this.getDelegateTracer(e,t,r))&&void 0!==i?i:new s.ProxyTracer(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:i}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,r){var s;return null===(s=this._delegate)||void 0===s?void 0:s.getTracer(e,t,r)}}t.ProxyTracerProvider=n},996:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SamplingDecision=void 0,function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(t.SamplingDecision||(t.SamplingDecision={}))},607:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSpanContext=t.setSpanContext=t.deleteSpan=t.setSpan=t.getActiveSpan=t.getSpan=void 0;let s=r(780),i=r(403),n=r(491),a=(0,s.createContextKey)("OpenTelemetry Context Key SPAN");function o(e){return e.getValue(a)||void 0}function l(e,t){return e.setValue(a,t)}t.getSpan=o,t.getActiveSpan=function(){return o(n.ContextAPI.getInstance().active())},t.setSpan=l,t.deleteSpan=function(e){return e.deleteValue(a)},t.setSpanContext=function(e,t){return l(e,new i.NonRecordingSpan(t))},t.getSpanContext=function(e){var t;return null===(t=o(e))||void 0===t?void 0:t.spanContext()}},325:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceStateImpl=void 0;let s=r(564);class i{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,t){let r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+"="+this.get(t)),e),[]).join(",")}_parse(e){!(e.length>512)&&(this._internalState=e.split(",").reverse().reduce((e,t)=>{let r=t.trim(),i=r.indexOf("=");if(-1!==i){let n=r.slice(0,i),a=r.slice(i+1,t.length);(0,s.validateKey)(n)&&(0,s.validateValue)(a)&&e.set(n,a)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new i;return e._internalState=new Map(this._internalState),e}}t.TraceStateImpl=i},564:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateValue=t.validateKey=void 0;let r="[_0-9a-z-*/]",s=`[a-z]${r}{0,255}`,i=`[a-z0-9]${r}{0,240}@[a-z]${r}{0,13}`,n=RegExp(`^(?:${s}|${i})$`),a=/^[ -~]{0,255}[!-~]$/,o=/,|=/;t.validateKey=function(e){return n.test(e)},t.validateValue=function(e){return a.test(e)&&!o.test(e)}},98:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createTraceState=void 0;let s=r(325);t.createTraceState=function(e){return new s.TraceStateImpl(e)}},476:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.INVALID_SPAN_CONTEXT=t.INVALID_TRACEID=t.INVALID_SPANID=void 0;let s=r(475);t.INVALID_SPANID="0000000000000000",t.INVALID_TRACEID="00000000000000000000000000000000",t.INVALID_SPAN_CONTEXT={traceId:t.INVALID_TRACEID,spanId:t.INVALID_SPANID,traceFlags:s.TraceFlags.NONE}},357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SpanKind=void 0,function(e){e[e.INTERNAL=0]="INTERNAL",e[e.SERVER=1]="SERVER",e[e.CLIENT=2]="CLIENT",e[e.PRODUCER=3]="PRODUCER",e[e.CONSUMER=4]="CONSUMER"}(t.SpanKind||(t.SpanKind={}))},139:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapSpanContext=t.isSpanContextValid=t.isValidSpanId=t.isValidTraceId=void 0;let s=r(476),i=r(403),n=/^([0-9a-f]{32})$/i,a=/^[0-9a-f]{16}$/i;function o(e){return n.test(e)&&e!==s.INVALID_TRACEID}function l(e){return a.test(e)&&e!==s.INVALID_SPANID}t.isValidTraceId=o,t.isValidSpanId=l,t.isSpanContextValid=function(e){return o(e.traceId)&&l(e.spanId)},t.wrapSpanContext=function(e){return new i.NonRecordingSpan(e)}},847:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SpanStatusCode=void 0,function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}(t.SpanStatusCode||(t.SpanStatusCode={}))},475:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceFlags=void 0,function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"}(t.TraceFlags||(t.TraceFlags={}))},521:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.VERSION=void 0,t.VERSION="1.6.0"}},s={};function i(e){var r=s[e];if(void 0!==r)return r.exports;var n=s[e]={exports:{}},a=!0;try{t[e].call(n.exports,n,n.exports,i),a=!1}finally{a&&delete s[e]}return n.exports}i.ab="//";var n={};(()=>{Object.defineProperty(n,"__esModule",{value:!0}),n.trace=n.propagation=n.metrics=n.diag=n.context=n.INVALID_SPAN_CONTEXT=n.INVALID_TRACEID=n.INVALID_SPANID=n.isValidSpanId=n.isValidTraceId=n.isSpanContextValid=n.createTraceState=n.TraceFlags=n.SpanStatusCode=n.SpanKind=n.SamplingDecision=n.ProxyTracerProvider=n.ProxyTracer=n.defaultTextMapSetter=n.defaultTextMapGetter=n.ValueType=n.createNoopMeter=n.DiagLogLevel=n.DiagConsoleLogger=n.ROOT_CONTEXT=n.createContextKey=n.baggageEntryMetadataFromString=void 0;var e=i(369);Object.defineProperty(n,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return e.baggageEntryMetadataFromString}});var t=i(780);Object.defineProperty(n,"createContextKey",{enumerable:!0,get:function(){return t.createContextKey}}),Object.defineProperty(n,"ROOT_CONTEXT",{enumerable:!0,get:function(){return t.ROOT_CONTEXT}});var r=i(972);Object.defineProperty(n,"DiagConsoleLogger",{enumerable:!0,get:function(){return r.DiagConsoleLogger}});var s=i(957);Object.defineProperty(n,"DiagLogLevel",{enumerable:!0,get:function(){return s.DiagLogLevel}});var a=i(102);Object.defineProperty(n,"createNoopMeter",{enumerable:!0,get:function(){return a.createNoopMeter}});var o=i(901);Object.defineProperty(n,"ValueType",{enumerable:!0,get:function(){return o.ValueType}});var l=i(194);Object.defineProperty(n,"defaultTextMapGetter",{enumerable:!0,get:function(){return l.defaultTextMapGetter}}),Object.defineProperty(n,"defaultTextMapSetter",{enumerable:!0,get:function(){return l.defaultTextMapSetter}});var c=i(125);Object.defineProperty(n,"ProxyTracer",{enumerable:!0,get:function(){return c.ProxyTracer}});var u=i(846);Object.defineProperty(n,"ProxyTracerProvider",{enumerable:!0,get:function(){return u.ProxyTracerProvider}});var h=i(996);Object.defineProperty(n,"SamplingDecision",{enumerable:!0,get:function(){return h.SamplingDecision}});var d=i(357);Object.defineProperty(n,"SpanKind",{enumerable:!0,get:function(){return d.SpanKind}});var p=i(847);Object.defineProperty(n,"SpanStatusCode",{enumerable:!0,get:function(){return p.SpanStatusCode}});var f=i(475);Object.defineProperty(n,"TraceFlags",{enumerable:!0,get:function(){return f.TraceFlags}});var g=i(98);Object.defineProperty(n,"createTraceState",{enumerable:!0,get:function(){return g.createTraceState}});var m=i(139);Object.defineProperty(n,"isSpanContextValid",{enumerable:!0,get:function(){return m.isSpanContextValid}}),Object.defineProperty(n,"isValidTraceId",{enumerable:!0,get:function(){return m.isValidTraceId}}),Object.defineProperty(n,"isValidSpanId",{enumerable:!0,get:function(){return m.isValidSpanId}});var b=i(476);Object.defineProperty(n,"INVALID_SPANID",{enumerable:!0,get:function(){return b.INVALID_SPANID}}),Object.defineProperty(n,"INVALID_TRACEID",{enumerable:!0,get:function(){return b.INVALID_TRACEID}}),Object.defineProperty(n,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return b.INVALID_SPAN_CONTEXT}});let y=i(67);Object.defineProperty(n,"context",{enumerable:!0,get:function(){return y.context}});let w=i(506);Object.defineProperty(n,"diag",{enumerable:!0,get:function(){return w.diag}});let v=i(886);Object.defineProperty(n,"metrics",{enumerable:!0,get:function(){return v.metrics}});let _=i(939);Object.defineProperty(n,"propagation",{enumerable:!0,get:function(){return _.propagation}});let k=i(845);Object.defineProperty(n,"trace",{enumerable:!0,get:function(){return k.trace}}),n.default={context:y.context,diag:w.diag,metrics:v.metrics,propagation:_.propagation,trace:k.trace}})(),e.exports=n})()},133:e=>{(()=>{"use strict";"undefined"!=typeof __nccwpck_require__&&(__nccwpck_require__.ab="//");var t={};(()=>{t.parse=function(t,r){if("string"!=typeof t)throw TypeError("argument str must be a string");for(var i={},n=t.split(s),a=(r||{}).decode||e,o=0;o<n.length;o++){var l=n[o],c=l.indexOf("=");if(!(c<0)){var u=l.substr(0,c).trim(),h=l.substr(++c,l.length).trim();'"'==h[0]&&(h=h.slice(1,-1)),void 0==i[u]&&(i[u]=function(e,t){try{return t(e)}catch(t){return e}}(h,a))}}return i},t.serialize=function(e,t,s){var n=s||{},a=n.encode||r;if("function"!=typeof a)throw TypeError("option encode is invalid");if(!i.test(e))throw TypeError("argument name is invalid");var o=a(t);if(o&&!i.test(o))throw TypeError("argument val is invalid");var l=e+"="+o;if(null!=n.maxAge){var c=n.maxAge-0;if(isNaN(c)||!isFinite(c))throw TypeError("option maxAge is invalid");l+="; Max-Age="+Math.floor(c)}if(n.domain){if(!i.test(n.domain))throw TypeError("option domain is invalid");l+="; Domain="+n.domain}if(n.path){if(!i.test(n.path))throw TypeError("option path is invalid");l+="; Path="+n.path}if(n.expires){if("function"!=typeof n.expires.toUTCString)throw TypeError("option expires is invalid");l+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(l+="; HttpOnly"),n.secure&&(l+="; Secure"),n.sameSite)switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":l+="; SameSite=Strict";break;case"lax":l+="; SameSite=Lax";break;case"none":l+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid")}return l};var e=decodeURIComponent,r=encodeURIComponent,s=/; */,i=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/})(),e.exports=t})()},340:(e,t,r)=>{var s;(()=>{var i={226:function(i,n){!function(a,o){"use strict";var l="function",c="undefined",u="object",h="string",d="major",p="model",f="name",g="type",m="vendor",b="version",y="architecture",w="console",v="mobile",_="tablet",k="smarttv",S="wearable",T="embedded",E="Amazon",R="Apple",O="ASUS",A="BlackBerry",P="Browser",C="Chrome",x="Firefox",I="Google",j="Huawei",N="Microsoft",$="Motorola",L="Opera",D="Samsung",U="Sharp",M="Sony",B="Xiaomi",q="Zebra",H="Facebook",V="Chromium OS",W="Mac OS",G=function(e,t){var r={};for(var s in e)t[s]&&t[s].length%2==0?r[s]=t[s].concat(e[s]):r[s]=e[s];return r},K=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},F=function(e,t){return typeof e===h&&-1!==z(t).indexOf(z(e))},z=function(e){return e.toLowerCase()},J=function(e,t){if(typeof e===h)return e=e.replace(/^\s\s*/,""),typeof t===c?e:e.substring(0,350)},X=function(e,t){for(var r,s,i,n,a,c,h=0;h<t.length&&!a;){var d=t[h],p=t[h+1];for(r=s=0;r<d.length&&!a&&d[r];)if(a=d[r++].exec(e))for(i=0;i<p.length;i++)c=a[++s],typeof(n=p[i])===u&&n.length>0?2===n.length?typeof n[1]==l?this[n[0]]=n[1].call(this,c):this[n[0]]=n[1]:3===n.length?typeof n[1]!==l||n[1].exec&&n[1].test?this[n[0]]=c?c.replace(n[1],n[2]):void 0:this[n[0]]=c?n[1].call(this,c,n[2]):void 0:4===n.length&&(this[n[0]]=c?n[3].call(this,c.replace(n[1],n[2])):void 0):this[n]=c||o;h+=2}},Y=function(e,t){for(var r in t)if(typeof t[r]===u&&t[r].length>0){for(var s=0;s<t[r].length;s++)if(F(t[r][s],e))return"?"===r?o:r}else if(F(t[r],e))return"?"===r?o:r;return e},Q={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Z={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[b,[f,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[b,[f,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[f,b],[/opios[\/ ]+([\w\.]+)/i],[b,[f,L+" Mini"]],[/\bopr\/([\w\.]+)/i],[b,[f,L]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[f,b],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[b,[f,"UC"+P]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[b,[f,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[b,[f,"WeChat"]],[/konqueror\/([\w\.]+)/i],[b,[f,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[b,[f,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[b,[f,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[f,/(.+)/,"$1 Secure "+P],b],[/\bfocus\/([\w\.]+)/i],[b,[f,x+" Focus"]],[/\bopt\/([\w\.]+)/i],[b,[f,L+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[b,[f,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[b,[f,"Dolphin"]],[/coast\/([\w\.]+)/i],[b,[f,L+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[b,[f,"MIUI "+P]],[/fxios\/([-\w\.]+)/i],[b,[f,x]],[/\bqihu|(qi?ho?o?|360)browser/i],[[f,"360 "+P]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[f,/(.+)/,"$1 "+P],b],[/(comodo_dragon)\/([\w\.]+)/i],[[f,/_/g," "],b],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[f,b],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[f],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[f,H],b],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[f,b],[/\bgsa\/([\w\.]+) .*safari\//i],[b,[f,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[b,[f,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[b,[f,C+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[f,C+" WebView"],b],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[b,[f,"Android "+P]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[f,b],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[b,[f,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[b,f],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[f,[b,Y,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[f,b],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[f,"Netscape"],b],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[b,[f,x+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[f,b],[/(cobalt)\/([\w\.]+)/i],[f,[b,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[y,"amd64"]],[/(ia32(?=;))/i],[[y,z]],[/((?:i[346]|x)86)[;\)]/i],[[y,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[y,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[y,"armhf"]],[/windows (ce|mobile); ppc;/i],[[y,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[y,/ower/,"",z]],[/(sun4\w)[;\)]/i],[[y,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[y,z]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[p,[m,D],[g,_]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[p,[m,D],[g,v]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[p,[m,R],[g,v]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[p,[m,R],[g,_]],[/(macintosh);/i],[p,[m,R]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[p,[m,U],[g,v]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[p,[m,j],[g,_]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[p,[m,j],[g,v]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[p,/_/g," "],[m,B],[g,v]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[p,/_/g," "],[m,B],[g,_]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[p,[m,"OPPO"],[g,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[p,[m,"Vivo"],[g,v]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[p,[m,"Realme"],[g,v]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[p,[m,$],[g,v]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[p,[m,$],[g,_]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[p,[m,"LG"],[g,_]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[p,[m,"LG"],[g,v]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[p,[m,"Lenovo"],[g,_]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[p,/_/g," "],[m,"Nokia"],[g,v]],[/(pixel c)\b/i],[p,[m,I],[g,_]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[p,[m,I],[g,v]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[p,[m,M],[g,v]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[p,"Xperia Tablet"],[m,M],[g,_]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[p,[m,"OnePlus"],[g,v]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[p,[m,E],[g,_]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[p,/(.+)/g,"Fire Phone $1"],[m,E],[g,v]],[/(playbook);[-\w\),; ]+(rim)/i],[p,m,[g,_]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[p,[m,A],[g,v]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[p,[m,O],[g,_]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[p,[m,O],[g,v]],[/(nexus 9)/i],[p,[m,"HTC"],[g,_]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[m,[p,/_/g," "],[g,v]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[p,[m,"Acer"],[g,_]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[p,[m,"Meizu"],[g,v]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[m,p,[g,v]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[m,p,[g,_]],[/(surface duo)/i],[p,[m,N],[g,_]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[p,[m,"Fairphone"],[g,v]],[/(u304aa)/i],[p,[m,"AT&T"],[g,v]],[/\bsie-(\w*)/i],[p,[m,"Siemens"],[g,v]],[/\b(rct\w+) b/i],[p,[m,"RCA"],[g,_]],[/\b(venue[\d ]{2,7}) b/i],[p,[m,"Dell"],[g,_]],[/\b(q(?:mv|ta)\w+) b/i],[p,[m,"Verizon"],[g,_]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[p,[m,"Barnes & Noble"],[g,_]],[/\b(tm\d{3}\w+) b/i],[p,[m,"NuVision"],[g,_]],[/\b(k88) b/i],[p,[m,"ZTE"],[g,_]],[/\b(nx\d{3}j) b/i],[p,[m,"ZTE"],[g,v]],[/\b(gen\d{3}) b.+49h/i],[p,[m,"Swiss"],[g,v]],[/\b(zur\d{3}) b/i],[p,[m,"Swiss"],[g,_]],[/\b((zeki)?tb.*\b) b/i],[p,[m,"Zeki"],[g,_]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[m,"Dragon Touch"],p,[g,_]],[/\b(ns-?\w{0,9}) b/i],[p,[m,"Insignia"],[g,_]],[/\b((nxa|next)-?\w{0,9}) b/i],[p,[m,"NextBook"],[g,_]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[m,"Voice"],p,[g,v]],[/\b(lvtel\-)?(v1[12]) b/i],[[m,"LvTel"],p,[g,v]],[/\b(ph-1) /i],[p,[m,"Essential"],[g,v]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[p,[m,"Envizen"],[g,_]],[/\b(trio[-\w\. ]+) b/i],[p,[m,"MachSpeed"],[g,_]],[/\btu_(1491) b/i],[p,[m,"Rotor"],[g,_]],[/(shield[\w ]+) b/i],[p,[m,"Nvidia"],[g,_]],[/(sprint) (\w+)/i],[m,p,[g,v]],[/(kin\.[onetw]{3})/i],[[p,/\./g," "],[m,N],[g,v]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[p,[m,q],[g,_]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[p,[m,q],[g,v]],[/smart-tv.+(samsung)/i],[m,[g,k]],[/hbbtv.+maple;(\d+)/i],[[p,/^/,"SmartTV"],[m,D],[g,k]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[m,"LG"],[g,k]],[/(apple) ?tv/i],[m,[p,R+" TV"],[g,k]],[/crkey/i],[[p,C+"cast"],[m,I],[g,k]],[/droid.+aft(\w)( bui|\))/i],[p,[m,E],[g,k]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[p,[m,U],[g,k]],[/(bravia[\w ]+)( bui|\))/i],[p,[m,M],[g,k]],[/(mitv-\w{5}) bui/i],[p,[m,B],[g,k]],[/Hbbtv.*(technisat) (.*);/i],[m,p,[g,k]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[m,J],[p,J],[g,k]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[g,k]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[m,p,[g,w]],[/droid.+; (shield) bui/i],[p,[m,"Nvidia"],[g,w]],[/(playstation [345portablevi]+)/i],[p,[m,M],[g,w]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[p,[m,N],[g,w]],[/((pebble))app/i],[m,p,[g,S]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[p,[m,R],[g,S]],[/droid.+; (glass) \d/i],[p,[m,I],[g,S]],[/droid.+; (wt63?0{2,3})\)/i],[p,[m,q],[g,S]],[/(quest( 2| pro)?)/i],[p,[m,H],[g,S]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[m,[g,T]],[/(aeobc)\b/i],[p,[m,E],[g,T]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[p,[g,v]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[p,[g,_]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[g,_]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[g,v]],[/(android[-\w\. ]{0,9});.+buil/i],[p,[m,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[b,[f,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[b,[f,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[f,b],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[b,f]],os:[[/microsoft (windows) (vista|xp)/i],[f,b],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[f,[b,Y,Q]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[f,"Windows"],[b,Y,Q]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/ios;fbsv\/([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[b,/_/g,"."],[f,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[f,W],[b,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[b,f],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[f,b],[/\(bb(10);/i],[b,[f,A]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[b,[f,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[b,[f,x+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[b,[f,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[b,[f,"watchOS"]],[/crkey\/([\d\.]+)/i],[b,[f,C+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[f,V],b],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[f,b],[/(sunos) ?([\w\.\d]*)/i],[[f,"Solaris"],b],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[f,b]]},ee=function(e,t){if(typeof e===u&&(t=e,e=o),!(this instanceof ee))return new ee(e,t).getResult();var r=typeof a!==c&&a.navigator?a.navigator:o,s=e||(r&&r.userAgent?r.userAgent:""),i=r&&r.userAgentData?r.userAgentData:o,n=t?G(Z,t):Z,w=r&&r.userAgent==s;return this.getBrowser=function(){var e,t={};return t[f]=o,t[b]=o,X.call(t,s,n.browser),t[d]=typeof(e=t[b])===h?e.replace(/[^\d\.]/g,"").split(".")[0]:o,w&&r&&r.brave&&typeof r.brave.isBrave==l&&(t[f]="Brave"),t},this.getCPU=function(){var e={};return e[y]=o,X.call(e,s,n.cpu),e},this.getDevice=function(){var e={};return e[m]=o,e[p]=o,e[g]=o,X.call(e,s,n.device),w&&!e[g]&&i&&i.mobile&&(e[g]=v),w&&"Macintosh"==e[p]&&r&&typeof r.standalone!==c&&r.maxTouchPoints&&r.maxTouchPoints>2&&(e[p]="iPad",e[g]=_),e},this.getEngine=function(){var e={};return e[f]=o,e[b]=o,X.call(e,s,n.engine),e},this.getOS=function(){var e={};return e[f]=o,e[b]=o,X.call(e,s,n.os),w&&!e[f]&&i&&"Unknown"!=i.platform&&(e[f]=i.platform.replace(/chrome os/i,V).replace(/macos/i,W)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return s},this.setUA=function(e){return s=typeof e===h&&e.length>350?J(e,350):e,this},this.setUA(s),this};ee.VERSION="1.0.35",ee.BROWSER=K([f,b,d]),ee.CPU=K([y]),ee.DEVICE=K([p,m,g,w,v,k,_,S,T]),ee.ENGINE=ee.OS=K([f,b]),typeof n!==c?(i.exports&&(n=i.exports=ee),n.UAParser=ee):r.amdO?void 0!==(s=(function(){return ee}).call(t,r,t,e))&&(e.exports=s):typeof a!==c&&(a.UAParser=ee);var et=typeof a!==c&&(a.jQuery||a.Zepto);if(et&&!et.ua){var er=new ee;et.ua=er.getResult(),et.ua.get=function(){return er.getUA()},et.ua.set=function(e){er.setUA(e);var t=er.getResult();for(var r in t)et.ua[r]=t[r]}}}("object"==typeof window?window:this)}},n={};function a(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}},s=!0;try{i[e].call(r.exports,r,r.exports,a),s=!1}finally{s&&delete n[e]}return r.exports}a.ab="//";var o=a(226);e.exports=o})()},488:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getTestReqInfo:function(){return a},withRequest:function(){return n}});let s=new(r(67)).AsyncLocalStorage;function i(e,t){let r=t.header(e,"next-test-proxy-port");if(r)return{url:t.url(e),proxyPort:Number(r),testData:t.header(e,"next-test-data")||""}}function n(e,t,r){let n=i(e,t);return n?s.run(n,r):r()}function a(e,t){return s.getStore()||(e&&t?i(e,t):void 0)}},375:(e,t,r)=>{"use strict";var s=r(195).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{handleFetch:function(){return o},interceptFetch:function(){return l},reader:function(){return n}});let i=r(488),n={url:e=>e.url,header:(e,t)=>e.headers.get(t)};async function a(e,t){let{url:r,method:i,headers:n,body:a,cache:o,credentials:l,integrity:c,mode:u,redirect:h,referrer:d,referrerPolicy:p}=t;return{testData:e,api:"fetch",request:{url:r,method:i,headers:[...Array.from(n),["next-test-stack",function(){let e=(Error().stack??"").split("\n");for(let t=1;t<e.length;t++)if(e[t].length>0){e=e.slice(t);break}return(e=(e=(e=e.filter(e=>!e.includes("/next/dist/"))).slice(0,5)).map(e=>e.replace("webpack-internal:///(rsc)/","").trim())).join("    ")}()]],body:a?s.from(await t.arrayBuffer()).toString("base64"):null,cache:o,credentials:l,integrity:c,mode:u,redirect:h,referrer:d,referrerPolicy:p}}}async function o(e,t){let r=(0,i.getTestReqInfo)(t,n);if(!r)return e(t);let{testData:o,proxyPort:l}=r,c=await a(o,t),u=await e(`http://localhost:${l}`,{method:"POST",body:JSON.stringify(c),next:{internal:!0}});if(!u.ok)throw Error(`Proxy request failed: ${u.status}`);let h=await u.json(),{api:d}=h;switch(d){case"continue":return e(t);case"abort":case"unhandled":throw Error(`Proxy request aborted [${t.method} ${t.url}]`)}return function(e){let{status:t,headers:r,body:i}=e.response;return new Response(i?s.from(i,"base64"):null,{status:t,headers:new Headers(r)})}(h)}function l(e){return r.g.fetch=function(t,r){var s;return(null==r?void 0:null==(s=r.next)?void 0:s.internal)?e(t,r):o(e,new Request(t,r))},()=>{r.g.fetch=e}}},177:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{interceptTestApis:function(){return n},wrapRequestHandler:function(){return a}});let s=r(488),i=r(375);function n(){return(0,i.interceptFetch)(r.g.fetch)}function a(e){return(t,r)=>(0,s.withRequest)(t,i.reader,()=>e(t,r))}}},e=>{var t=e(e.s=206);(_ENTRIES="undefined"==typeof _ENTRIES?{}:_ENTRIES)["middleware_src/middleware"]=t}]);
//# sourceMappingURL=middleware.js.map