1import{a as e,i as t,n,r,t as i}from"./rolldown-runtime-BYbx6iT9.js";import{h as a}from"./react-vendor-BdiHhWcx.js";var o=e=>{let t;return t=e||(typeof fetch>`u`?(...e)=>a(async()=>{let{default:e}=await Promise.resolve().then(()=>(_(),m));return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},s=class extends Error{constructor(e,t=`FunctionsError`,n){super(e),this.name=t,this.context=n}},c=class extends s{constructor(e){super(`Failed to send a request to the Edge Function`,`FunctionsFetchError`,e)}},l=class extends s{constructor(e){super(`Relay Error invoking the Edge Function`,`FunctionsRelayError`,e)}},u=class extends s{constructor(e){super(`Edge Function returned a non-2xx status code`,`FunctionsHttpError`,e)}},d;(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`})(d||={});var f=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},p=class{constructor(e,{headers:t={},customFetch:n,region:r=d.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=o(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){return f(this,void 0,void 0,function*(){try{let{headers:n,method:r,body:i}=t,a={},{region:o}=t;o||=this.region;let s=new URL(`${this.url}/${e}`);o&&o!==`any`&&(a[`x-region`]=o,s.searchParams.set(`forceFunctionRegion`,o));let d;i&&(n&&!Object.prototype.hasOwnProperty.call(n,`Content-Type`)||!n)&&(typeof Blob<`u`&&i instanceof Blob||i instanceof ArrayBuffer?(a[`Content-Type`]=`application/octet-stream`,d=i):typeof i==`string`?(a[`Content-Type`]=`text/plain`,d=i):typeof FormData<`u`&&i instanceof FormData?d=i:(a[`Content-Type`]=`application/json`,d=JSON.stringify(i)));let f=yield this.fetch(s.toString(),{method:r||`POST`,headers:Object.assign(Object.assign(Object.assign({},a),this.headers),n),body:d}).catch(e=>{throw new c(e)}),p=f.headers.get(`x-relay-error`);if(p&&p===`true`)throw new l(f);if(!f.ok)throw new u(f);let m=(f.headers.get(`Content-Type`)??`text/plain`).split(`;`)[0].trim(),h;return h=m===`application/json`?yield f.json():m===`application/octet-stream`?yield f.blob():m===`text/event-stream`?f:m===`multipart/form-data`?yield f.formData():yield f.text(),{data:h,error:null,response:f}}catch(e){return{data:null,error:e,response:e instanceof u||e instanceof l?e.context:void 0}}})}},m=r({Headers:()=>ne,Request:()=>
1re,Response:()=>ie,default:()=>te,fetch:()=>ee}),h,g,ee,te,ne,re,ie,_=n((()=>{h=function(){if(typeof self<`u`)return self;if(typeof window<`u`)return window;if(typeof global<`u`)return global;throw Error(`unable to locate global object`)},g=h(),ee=g.fetch,te=g.fetch.bind(g),ne=g.Headers,re=g.Request,ie=g.Response})),ae=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(e.message),this.name=`PostgrestError`,this.details=e.details,this.hint=e.hint,this.code=e.code}}})),oe=i((e=>{var n=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,`__esModule`,{value:!0});var r=n((_(),t(m))),i=n(ae());e.default=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,e.fetch?this.fetch=e.fetch:typeof fetch>`u`?this.fetch=r.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){this.schema===void 0||([`GET`,`HEAD`].includes(this.method)?this.headers.set(`Accept-Profile`,this.schema):this.headers.set(`Content-Profile`,this.schema)),this.method!==`GET`&&this.method!==`HEAD`&&this.headers.set(`Content-Type`,`application/json`);let n=this.fetch,r=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,n=null,r=null,a=e.status,o=e.statusText;if(e.ok){if(this.method!==`HEAD`){let t=await e.text();t===``||(n=this.headers.get(`Accept`)===`text/csv`||this.headers.get(`Accept`)&&this.headers.get(`Accept`)?.includes(`application/vnd.pgrst.plan+text`)?t:JSON.parse(t))}let i=this.headers.get(`Prefer`)?.match(/count=(exact|planned|estimated)/),s=e.headers.get(`content-range`)?.split(`/`);i&&s&&s.length>1&&(r=parseInt(s[1])),this.isMaybeSingle&&this.method===`GET`&&Array.isArray(n)&&(n.length>1?(t={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,r=null,a=406,o=`Not Acceptable`):n=n.length===1?n[0]:null)}else{let r=await e.text();try{t=JSON.parse(r),Array.isArray(t)&&e.status===404&&(n=[],t=null,a=200,o=`OK`)}
1catch{e.status===404&&r===``?(a=204,o=`No Content`):t={message:r}}if(t&&this.isMaybeSingle&&(t?.details)?.includes(`0 rows`)&&(t=null,a=200,o=`OK`),t&&this.shouldThrowOnError)throw new i.default(t)}return{error:t,data:n,count:r,status:a,statusText:o}});return this.shouldThrowOnError||(r=r.catch(e=>({error:{message:`${e?.name??`FetchError`}: ${e?.message}`,details:`${e?.stack??``}`,hint:``,code:`${e?.code??``}`},data:null,count:null,status:0,statusText:``}))),r.then(e,t)}returns(){return this}overrideTypes(){return this}}})),se=i((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,`__esModule`,{value:!0});var n=t(oe());e.default=class extends n.default{select(e){let t=!1,n=(e??`*`).split(``).map(e=>/\s/.test(e)&&!t?``:(e===`"`&&(t=!t),e)).join(``);return this.url.searchParams.set(`select`,n),this.headers.append(`Prefer`,`return=representation`),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){let a=i?`${i}.order`:`order`,o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:``}${e}.${t?`asc`:`desc`}${n===void 0?``:n?`.nullsfirst`:`.nullslast`}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){let r=n===void 0?`limit`:`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){let i=r===void 0?`offset`:`${r}.offset`,a=r===void 0?`limit`:`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${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.method===`GET`?this.headers.set(`Accept`,`application/json`):this.headers.set(`Accept`,`application/vnd.pgrst.object+json`),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:n=!1,buffers:r=!1,wal:i=!1,format:a=`text`}={}){let o=[e?`analyze`:null,t?`verbose`:null,n?`settings`:null,r?`buffers`:null,i?`wal`:null].filter(Boolean).join(`|`),s=this.headers.get(`Accept`)??`application/json`;return this.headers.set(`Accept`,`application/vnd.pgrst.plan+${a}; for="${s}"; 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}}})),ce=i((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,`__esModule`,{value:!0});var n=t(se());e.default=class extends n.default{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}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&RegExp(`[,()]`).test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`in.(${n})`),this}contains(e,t){return typeof t==`string`?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 typeof t==`string`?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 typeof t==`string`?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(`,`)}}`),this}textSearch(e,t,{config:n,type:r}={}){let i=``;
1r===`plain`?i=`pl`:r===`phrase`?i=`ph`:r===`websearch`&&(i=`w`);let a=n===void 0?``:`(${n})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){let r=n?`${n}.or`:`or`;return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}}})),le=i((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,`__esModule`,{value:!0});var n=t(ce());e.default=class{constructor(e,{headers:t={},schema:n,fetch:r}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r}select(e,{head:t=!1,count:r}={}){let i=t?`HEAD`:`GET`,a=!1,o=(e??`*`).split(``).map(e=>/\s/.test(e)&&!a?``:(e===`"`&&(a=!a),e)).join(``);return this.url.searchParams.set(`select`,o),r&&this.headers.append(`Prefer`,`count=${r}`),new n.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){if(t&&this.headers.append(`Prefer`,`count=${t}`),r||this.headers.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}"`);this.url.searchParams.set(`columns`,e.join(`,`))}}return new n.default({method:`POST`,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch??fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:a=!0}={}){if(this.headers.append(`Prefer`,`resolution=${r?`ignore`:`merge`}-duplicates`),t!==void 0&&this.url.searchParams.set(`on_conflict`,t),i&&this.headers.append(`Prefer`,`count=${i}`),a||this.headers.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}"`);this.url.searchParams.set(`columns`,e.join(`,`))}}return new n.default({method:`POST`,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch??fetch})}update(e,{count:t}={}){return t&&this.headers.append(`Prefer`,`count=${t}`),new n.default({method:`PATCH`,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch??fetch})}delete({count:e}={}){return e&&this.headers.append(`Prefer`,`count=${e}`),new n.default({method:`DELETE`,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch??fetch})}}})),ue=i((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,`__esModule`,{value:!0});var n=t(le()),r=t(ce());e.default=class e{constructor(e,{headers:t={},schema:n,fetch:r}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.fetch=r}from(e){let t=new URL(`${this.url}/${e}`);return new n.default(t,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(e,t={},{head:n=!1,get:i=!1,count:a}={}){let o,s=new URL(`${this.url}/rpc/${e}`),c;n||i?(o=n?`HEAD`:`GET`,Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(`,`)}}`:`${t}`]).forEach(([e,t])=>{s.searchParams.append(e,t)})):(o=`POST`,c=t);let l=new Headers(this.headers);return a&&l.set(`Prefer`,`count=${a}`),new r.default({method:o,url:s,headers:l,schema:this.schemaName,body:c,fetch:this.fetch??fetch})}}})),{PostgrestClient:de,PostgrestQueryBuilder:fe,PostgrestFilterBuilder:pe,PostgrestTransformBuilder:me,PostgrestBuilder:he,PostgrestError:ge}=e(i((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,`__esModule`,{value:!0}),e.PostgrestError=e.PostgrestBuilder=e.PostgrestTransformBuilder=e.PostgrestFilterBuilder=e.PostgrestQueryBuilder=e.PostgrestClient=void 0;var n=t(ue());e.PostgrestClient=n.default;var r=t(le());e.PostgrestQueryBuilder=r.default;var i=t(ce());e.PostgrestFilterBuilder=i.default;var a=t(se());e.PostgrestTransformBuilder=a.default;var o=t(oe());e.PostgrestBuilder=o.default;var s=t(ae());e.PostgrestError=s.default,e.default={PostgrestClient:n.default,PostgrestQueryBuilder:r.default,PostgrestFilterBuilder:i.default,PostgrestTransformBuilder:
1a.default,PostgrestBuilder:o.default,PostgrestError:s.default}}))(),1).default,_e=class{static detectEnvironment(){if(typeof WebSocket<`u`)return{type:`native`,constructor:WebSocket};if(typeof globalThis<`u`&&globalThis.WebSocket!==void 0)return{type:`native`,constructor:globalThis.WebSocket};if(typeof global<`u`&&global.WebSocket!==void 0)return{type:`native`,constructor:global.WebSocket};if(typeof globalThis<`u`&&globalThis.WebSocketPair!==void 0&&globalThis.WebSocket===void 0)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(typeof globalThis<`u`&&globalThis.EdgeRuntime||typeof navigator<`u`&&navigator.userAgent?.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.`};if(typeof process<`u`){let e=process.versions;if(e&&e.node){let t=e.node,n=parseInt(t.replace(/^v/,``).split(`.`)[0]);return n>=22?globalThis.WebSocket===void 0?{type:`unsupported`,error:`Node.js ${n} detected but native WebSocket not found.`,workaround:`Provide a WebSocket implementation via the transport option.`}:{type:`native`,constructor:globalThis.WebSocket}:{type:`unsupported`,error:`Node.js ${n} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: 2import ws from "ws" 3new 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.constructor)return e.constructor;let t=e.error||`WebSocket not supported in this environment.`;throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type===`native`||e.type===`ws`}catch{return!1}}},ve=`realtime-js/2.15.5`,ye=`1.0.0`,be=1e4,v;(function(e){e[e.connecting=0]=`connecting`,e[e.open=1]=`open`,e[e.closing=2]=`closing`,e[e.closed=3]=`closed`})(v||={});var y;(function(e){e.closed=`closed`,e.errored=`errored`,e.joined=`joined`,e.joining=`joining`,e.leaving=`leaving`})(y||={});var b;(function(e){e.close=`phx_close`,e.error=`phx_error`,e.join=`phx_join`,e.reply=`phx_reply`,e.leave=`phx_leave`,e.access_token=`access_token`})(b||={});var xe;(function(e){e.websocket=`websocket`})(xe||={});var x;(function(e){e.Connecting=`connecting`,e.Open=`open`,e.Closing=`closing`,e.Closed=`closed`})(x||={});var Se=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e==`string`?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),n=new TextDecoder;return this._decodeBroadcast(e,t,n)}_decodeBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=this.HEADER_LENGTH+2,o=n.decode(e.slice(a,a+r));a+=r;let s=n.decode(e.slice(a,a+i));return a+=i,{ref:null,topic:o,event:s,payload:JSON.parse(n.decode(e.slice(a,e.byteLength)))}}},Ce=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries+=1,this.callback()},this.timerCalc(this.tries+1))}},S;(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`})(S||={});var we=(e,t,n={})=>{let r=n.skipTypes??[];return Object.keys(t).reduce((n,i)=>(n[i]=Te(i,e,t,r),n),{})},Te=(e,t,n,r)=>{let i=t.find(t=>t.name===e)?.type,a=n[e];return i&&!r.includes(i)?Ee(i,a):De(a)},Ee=(e,t)=>{if(e.charAt(0)===`_`)return je(t,e.slice(1,e.length));switch(e){case S.bool:return Oe(t);case S.float4:case S.float8:case S.int2:case S.int4:case S.int8:case S.numeric:case S.oid:return ke(t);case S.json:case S.jsonb:return Ae(t);case S.timestamp:return Me(t);case S.abstime:case S.date:case S.daterange:case S.int4range:case S.int8range:case S.money:case S.reltime:case S.text:case S.time:case S.timestamptz:case S.timetz:case S.tsrange:case S.tstzrange:return De(t);default:return De(t)}},De=e=>e,Oe=e=>{switch(e){case`t`:return!0;case`f`:return!1;default:return e}},ke=e=>{if(typeof e==`string`){let t=parseFloat(e);
3if(!Number.isNaN(t))return t}return e},Ae=e=>{if(typeof e==`string`)try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},je=(e,t)=>{if(typeof e!=`string`)return e;let n=e.length-1,r=e[n];if(e[0]===`{`&&r===`}`){let r,i=e.slice(1,n);try{r=JSON.parse(`[`+i+`]`)}catch{r=i?i.split(`,`):[]}return r.map(e=>Ee(t,e))}return e},Me=e=>typeof e==`string`?e.replace(` `,`T`):e,Ne=e=>{let t=e;return t=t.replace(/^ws/i,`http`),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,``),t.replace(/\/+$/,``)+`/api/broadcast`},Pe=class{constructor(e,t,n={},r=be){this.channel=e,this.event=t,this.payload=n,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref=``,this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref=``,this.refEvent=null,this.receivedResp=null,this.sent=!1,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()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){return this._hasReceived(e)&&t(this.receivedResp?.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){this.timeoutTimer||=(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)}),setTimeout(()=>{this.trigger(`timeout`,{})},this.timeout))}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}},Fe;(function(e){e.SYNC=`sync`,e.JOIN=`join`,e.LEAVE=`leave`})(Fe||={});var Ie=class e{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=n?.events||{state:`presence_state`,diff:`presence_diff`};this.channel._on(r.state,{},t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.joinRef=this.channel._joinRef(),this.state=e.syncState(this.state,t,n,r),this.pendingDiffs.forEach(t=>{this.state=e.syncDiff(this.state,t,n,r)}),this.pendingDiffs=[],i()}),this.channel._on(r.diff,{},t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,n,r),i())}),this.onJoin((e,t,n)=>{this.channel._trigger(`presence`,{event:`join`,key:e,currentPresences:t,newPresences:n})}),this.onLeave((e,t,n)=>{this.channel._trigger(`presence`,{event:`leave`,key:e,currentPresences:t,leftPresences:n})}),this.onSync(()=>{this.channel._trigger(`presence`,{event:`sync`})})}static syncState(e,t,n,r){let i=this.cloneDeep(e),a=this.transformState(t),o={},s={};return this.map(i,(e,t)=>{a[e]||(s[e]=t)}),this.map(a,(e,t)=>{let n=i[e];if(n){let r=t.map(e=>e.presence_ref),i=n.map(e=>e.presence_ref),a=t.filter(e=>i.indexOf(e.presence_ref)<0),c=n.filter(e=>r.indexOf(e.presence_ref)<0);a.length>0&&(o[e]=a),c.length>0&&(s[e]=c)}else o[e]=t}),this.syncDiff(i,{joins:o,leaves:s},n,r)}static syncDiff(e,t,n,r){let{joins:i,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return n||=()=>{},r||=()=>{},this.map(i,(t,r)=>{let i=e[t]??[];if(e[t]=this.cloneDeep(r),i.length>0){let n=e[t].map(e=>e.presence_ref),r=i.filter(e=>n.indexOf(e.presence_ref)<0);e[t].unshift(...r)}n(t,i,r)}),this.map(a,(t,n)=>{let i=e[t];if(!i)return;let a=n.map(e=>e.presence_ref);i=i.filter(e=>a.indexOf(e.presence_ref)<0),e[t]=i,r(t,i,n),i.length===0&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(n=>t(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,n)=>{let r=e[n];return`metas`in r?t[n]=r.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):t[n]=r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}},Le;(function(e){e.ALL=`*`,e.INSERT=`INSERT`,e.UPDATE=`UPDATE`,e.DELETE=`DELETE`})(Le||={});var C;(function(e){e.BROADCAST=`broadcast`,e.PRESENCE=`presence`,e.POSTGRES_CHANGES=`postgres_changes`,e.SYSTEM=`system`})(C||={});var w;(function(e){e.SUBSCRIBED=`SUBSCRIBED`,e.TIMED_OUT=`TIMED_OUT`,e.CLOSED=`CLOSED`,e.CHANNEL_ERROR=`CHANNEL_ERROR`})(w||={});var Re=class e{constructor(e,t={config:{}},n){this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=y.closed,this.joinedOnce=!1,this.pushBuffer=[],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.timeout=this.socket.timeout,this.joinPush=new Pe(this,b.join,this.params,this.timeout),this.rejoinTimer=new Ce(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive(`ok`,()=>{this.state=y.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e
3=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log(`channel`,`close ${this.topic} ${this._joinRef()}`),this.state=y.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log(`channel`,`error ${this.topic}`,e),this.state=y.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive(`timeout`,()=>{this._isJoining()&&(this.socket.log(`channel`,`timeout ${this.topic}`,this.joinPush.timeout),this.state=y.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive(`error`,e=>{this._isLeaving()||this._isClosed()||(this.socket.log(`channel`,`error ${this.topic}`,e),this.state=y.errored,this.rejoinTimer.scheduleTimeout())}),this._on(b.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new Ie(this),this.broadcastEndpointURL=Ne(this.socket.endPoint),this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){if(this.socket.isConnected()||this.socket.connect(),this.state==y.closed){let{config:{broadcast:n,presence:r,private:i}}=this.params,a=this.bindings.postgres_changes?.map(e=>e.filter)??[],o=!!this.bindings[C.PRESENCE]&&this.bindings[C.PRESENCE].length>0||this.params.config.presence?.enabled===!0,s={},c={broadcast:n,presence:Object.assign(Object.assign({},r),{enabled:o}),postgres_changes:a,private:i};this.socket.accessTokenValue&&(s.access_token=this.socket.accessTokenValue),this._onError(t=>e?.(w.CHANNEL_ERROR,t)),this._onClose(()=>e?.(w.CLOSED)),this.updateJoinPayload(Object.assign({config:c},s)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive(`ok`,async({postgres_changes:t})=>{if(this.socket.setAuth(),t===void 0){e?.(w.SUBSCRIBED);return}else{let n=this.bindings.postgres_changes,r=n?.length??0,i=[];for(let a=0;a<r;a++){let r=n[a],{filter:{event:o,schema:s,table:c,filter:l}}=r,u=t&&t[a];if(u&&u.event===o&&u.schema===s&&u.table===c&&u.filter===l)i.push(Object.assign(Object.assign({},r),{id:u.id}));else{this.unsubscribe(),this.state=y.errored,e?.(w.CHANNEL_ERROR,Error(`mismatch between server and client bindings for postgres changes`));return}}this.bindings.postgres_changes=i,e&&e(w.SUBSCRIBED);return}}).receive(`error`,t=>{this.state=y.errored,e?.(w.CHANNEL_ERROR,Error(JSON.stringify(Object.values(t).join(`, `)||`error`)))}).receive(`timeout`,()=>{e?.(w.TIMED_OUT)})}return this}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,n){return this.state===y.joined&&e===C.PRESENCE&&(this.socket.log(`channel`,`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,n)}async send(e,t={}){if(!this._canPush()&&e.type===`broadcast`){let{event:n,payload:r}=e,i={method:`POST`,headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:``,apikey:this.socket.apiKey?this.socket.apiKey:``,"Content-Type":`application/json`},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:r,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,i,t.timeout??this.timeout);return await e.body?.cancel(),e.ok?`ok`:`error`}catch(e){return e.name===`AbortError`?`timed out`:`error`}}else return new Promise(n=>{let r=this._push(e.type,e,t.timeout||this.timeout);e.type===`broadcast`&&!this.params?.config?.broadcast?.ack&&n(`ok`),r.receive(`ok`,()=>n(`ok`)),r.receive(`error`,()=>n(`error`)),r.receive(`timeout`,()=>n(`timed out`))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=y.leaving;let t=()=>{this.socket.log(`channel`,`leave ${this.topic}`),this._trigger(b.close,`leave`,this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(r=>{n=new Pe(this,b.leave,{},e),n.receive(`ok`,()=>{t(),r(`ok`)}).receive(`timeout`,()=>{t(),r(`timed out`)}).receive(`error`,()=>{r(`error`)}),n.send(),this._canPush()||n.trigger(`ok`,{})}).finally(()=>{n?.destroy()})}
3teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=y.closed,this.bindings={}}async _fetchWithTimeout(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),n),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),a}_push(e,t,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new Pe(this,e,t,n);return this._canPush()?r.send():this._addToPushBuffer(r),r}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){let e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log(`channel`,`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,n){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,n){var r,i;let a=e.toLocaleLowerCase(),{close:o,error:s,leave:c,join:l}=b;if(n&&[o,s,c,l].indexOf(a)>=0&&n!==this._joinRef())return;let u=this._onMessage(a,t,n);if(t&&!u)throw`channel onMessage callbacks must return the payload, modified or unmodified`;[`insert`,`update`,`delete`].includes(a)?(r=this.bindings.postgres_changes)==null||r.filter(e=>e.filter?.event===`*`||(e.filter?.event)?.toLocaleLowerCase()===a).map(e=>e.callback(u,n)):(i=this.bindings[a])==null||i.filter(e=>{if([`broadcast`,`presence`,`postgres_changes`].includes(a))if(`id`in e){let n=e.id,r=e.filter?.event;return n&&t.ids?.includes(n)&&(r===`*`||r?.toLocaleLowerCase()===t.data?.type.toLocaleLowerCase())}else{let n=(e?.filter?.event)?.toLocaleLowerCase();return n===`*`||n===(t?.event)?.toLocaleLowerCase()}else return e.type.toLocaleLowerCase()===a}).map(e=>{if(typeof u==`object`&&`ids`in u){let e=u.data,{schema:t,table:n,commit_timestamp:r,type:i,errors:a}=e;u=Object.assign(Object.assign({},{schema:t,table:n,commit_timestamp:r,eventType:i,new:{},old:{},errors:a}),this._getPayloadRecords(e))}e.callback(u,n)})}_isClosed(){return this.state===y.closed}_isJoined(){return this.state===y.joined}_isJoining(){return this.state===y.joining}_isLeaving(){return this.state===y.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,n){let r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:n};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(t,n){let r=t.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(t=>!(t.type?.toLocaleLowerCase()===r&&e.isEqual(t.filter,n)))),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(b.close,{},e)}_onError(e){this._on(b.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=y.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type===`INSERT`||e.type===`UPDATE`)&&(t.new=we(e.columns,e.record)),(e.type===`UPDATE`||e.type===`DELETE`)&&(t.old=we(e.columns,e.old_record)),t}},ze=()=>{},T={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Be=[1e3,2e3,5e3,1e4],Ve=1e4,He=` 4 addEventListener("message", (e) => { 5 if (e.data.event === "start") { 6 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 7 } 8 });`,Ue=class{constructor(e,t){if(this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint=``,this.httpEndpoint=``,this.headers={},this.params={},this.timeout=be,this.transport=null,this.heartbeatIntervalMs=T.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ze,this.ref=0,this.reconnectTimer=null,this.logger=ze,this.conn=null,this.sendBuffer=[],this.serializer=new Se,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState=`disconnected`,this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=e=>{let t;return t=e||(typeof fetch>`u`?(...e)=>a(async()=>{let{default:e}=await Promise.resolve().then(()=>(_(),m));return{default:e}},void 0).then(({default:t})=>t(...e)).catch(e=>{throw Error(`Failed to load @supabase/node-fetch: ${e.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):fetch),(...e)=>t(...e)},!t?.params?.apikey)throw Error(`API key is required to connect to Realtime`);this.apiKey=t.params.apikey,this.endPoint=`${e}/${xe.websocket}`,this.httpEndpoint=Ne(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState(`connecting`),this._setAuthSafely(`connect`),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=_e.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState(`disconnected`);let t=e.message;throw t.includes(`Node.js`)?Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation: 9 10Option 1: Use Node.js 22+ which has native WebSocket support 11Option 2: Install and provide the "ws" package: 12 13 npm install ws 14 15 import ws from "ws" 16 const client = new RealtimeClient(url, { 17 ...options, 18 transport: ws 19 })`):Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:ye}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState(`disconnecting`,!0),this.conn){let n=setTimeout(()=>{this._setConnectionState(`disconnected`)},100);
19this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState(`disconnected`)},e?this.conn.close(e,t??``):this.conn.close(),this._teardownConnection()}else this._setConnectionState(`disconnected`)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case v.connecting:return x.Connecting;case v.open:return x.Open;case v.closing:return x.Closing;default:return x.Closed}}isConnected(){return this.connectionState()===x.Open}isConnecting(){return this._connectionState===`connecting`}isDisconnecting(){return this._connectionState===`disconnecting`}channel(e,t={config:{}}){let n=`realtime:${e}`,r=this.getChannels().find(e=>e.topic===n);if(r)return r;{let n=new Re(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){let{topic:t,event:n,payload:r,ref:i}=e,a=()=>{this.encode(e,e=>{var t;(t=this.conn)==null||t.send(e)})};this.log(`push`,`${t} ${n} (${i})`,r),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback(`disconnected`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,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._wasManualDisconnect=!1,(e=this.conn)==null||e.close(1e3,`heartbeat timeout`),setTimeout(()=>{var e;this.isConnected()||(e=this.reconnectTimer)==null||e.scheduleTimeout()},T.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),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._setAuthSafely(`heartbeat`)}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log(`transport`,`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if(e.topic===`phoenix`&&e.event===`phx_reply`)try{this.heartbeatCallback(e.payload.status===`ok`?`ok`:`error`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}e.ref&&e.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);let{topic:t,event:n,payload:r,ref:i}=e,a=i?`(${i})`:``,o=r.status||``;this.log(`receive`,`${o} ${t} ${n} ${a}`.trim(),r),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(n,r,i)),this._triggerStateCallbacks(`message`,e)})}_clearTimer(e){var t;e===`heartbeat`&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e===`reconnect`&&((t=this.reconnectTimer)==null||t.reset())}_clearAllTimers(){this._clearTimer(`heartbeat`),this._clearTimer(`reconnect`)}_setupConnectionHandlers(){this.conn&&(`binaryType`in this.conn&&(this.conn.binaryType=`arraybuffer`),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))}_teardownConnection(){this.conn&&=(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState(`connected`),this.log(`transport`,`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer(`reconnect`),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks(`open`)}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_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.workerRef.terminate()},this.workerRef.onmessage=e=>{e.data.event===`keepAlive`&&this.sendHeartbeat()},this.workerRef.postMessage({event:`start`,interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState(`disconnected`),this.log(`transport`,`close`,e),this._triggerChanError(),this._clearTimer(`heartbeat`),this._wasManualDisconnect||(t=this.reconnectTimer)==null||t.scheduleTimeout(),this._triggerStateCallbacks(`close`,e)}_onConnError(e){this._setConnectionState(`disconnected`),this.log(`transport`,`${e}`),this._triggerChanError(),this._triggerStateCallbacks(`error`,e)}
19_triggerChanError(){this.channels.forEach(e=>e._trigger(b.error))}_appendParams(e,t){return Object.keys(t).length===0?e:`${e}${e.match(/\?/)?`&`:`?`}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([He],{type:`application/javascript`});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e===`connecting`?this._wasManualDisconnect=!1:e===`disconnecting`&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;t=e||(this.accessToken?await this.accessToken():this.accessTokenValue),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{let n={access_token:t,version:ve};t&&e.updateJoinPayload(n),e.joinedOnce&&e._isJoined()&&e._push(b.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e=`general`){this.setAuth().catch(t=>{this.log(`error`,`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(t)}catch(t){this.log(`error`,`error in ${e} callback`,t)}})}catch(t){this.log(`error`,`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new Ce(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},T.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){if(this.transport=e?.transport??null,this.timeout=e?.timeout??be,this.heartbeatIntervalMs=e?.heartbeatIntervalMs??T.HEARTBEAT_INTERVAL,this.worker=e?.worker??!1,this.accessToken=e?.accessToken??null,this.heartbeatCallback=e?.heartbeatCallback??ze,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=e?.reconnectAfterMs??(e=>Be[e-1]||Ve),this.encode=e?.encode??((e,t)=>t(JSON.stringify(e))),this.decode=e?.decode??this.serializer.decode.bind(this.serializer),this.worker){if(typeof window<`u`&&!window.Worker)throw Error(`Web Worker is not supported`);this.workerUrl=e?.workerUrl}}},We=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name=`StorageError`}};function E(e){return typeof e==`object`&&!!e&&`__isStorageError`in e}var Ge=class extends We{constructor(e,t,n){super(e),this.name=`StorageApiError`,this.status=t,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Ke=class extends We{constructor(e,t){super(e),this.name=`StorageUnknownError`,this.originalError=t}},qe=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Je=e=>{let t;return t=e||(typeof fetch>`u`?(...e)=>a(async()=>{let{default:e}=await Promise.resolve().then(()=>(_(),m));return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},Ye=()=>qe(void 0,void 0,void 0,function*(){return typeof Response>`u`?(yield a(()=>Promise.resolve().then(()=>(_(),m)),void 0)).Response:Response}),Xe=e=>{if(Array.isArray(e))return e.map(e=>Xe(e));if(typeof e==`function`||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,``));t[r]=Xe(n)}),t},Ze=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},D=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Qe=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),$e=(e,t,n)=>D(void 0,void 0,void 0,function*(){e instanceof(yield Ye())&&!n?.noResolveJson?e.json().then(n=>{let r=e.status||500,i=n?.statusCode||r+``;
19t(new Ge(Qe(n),r,i))}).catch(e=>{t(new Ke(Qe(e),e))}):t(new Ke(Qe(e),e))}),et=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};return e===`GET`||!r?i:(Ze(r)?(i.headers=Object.assign({"Content-Type":`application/json`},t?.headers),i.body=JSON.stringify(r)):i.body=r,t?.duplex&&(i.duplex=t.duplex),Object.assign(Object.assign({},i),n))};function O(e,t,n,r,i,a){return D(this,void 0,void 0,function*(){return new Promise((o,s)=>{e(n,et(t,r,i,a)).then(e=>{if(!e.ok)throw e;return r?.noResolveJson?e:e.json()}).then(e=>o(e)).catch(e=>$e(e,s,r))})})}function k(e,t,n,r){return D(this,void 0,void 0,function*(){return O(e,`GET`,t,n,r)})}function A(e,t,n,r,i){return D(this,void 0,void 0,function*(){return O(e,`POST`,t,r,i,n)})}function tt(e,t,n,r,i){return D(this,void 0,void 0,function*(){return O(e,`PUT`,t,r,i,n)})}function nt(e,t,n,r){return D(this,void 0,void 0,function*(){return O(e,`HEAD`,t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function rt(e,t,n,r,i){return D(this,void 0,void 0,function*(){return O(e,`DELETE`,t,r,i,n)})}var j=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},it={limit:100,offset:0,sortBy:{column:`name`,order:`asc`}},at={cacheControl:`3600`,contentType:`text/plain;charset=UTF-8`,upsert:!1},ot=class{constructor(e,t={},n,r){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=n,this.fetch=Je(r)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,n,r){return j(this,void 0,void 0,function*(){try{let i,a=Object.assign(Object.assign({},at),r),o=Object.assign(Object.assign({},this.headers),e===`POST`&&{"x-upsert":String(a.upsert)}),s=a.metadata;typeof Blob<`u`&&n instanceof Blob?(i=new FormData,i.append(`cacheControl`,a.cacheControl),s&&i.append(`metadata`,this.encodeMetadata(s)),i.append(``,n)):typeof FormData<`u`&&n instanceof FormData?(i=n,i.append(`cacheControl`,a.cacheControl),s&&i.append(`metadata`,this.encodeMetadata(s))):(i=n,o[`cache-control`]=`max-age=${a.cacheControl}`,o[`content-type`]=a.contentType,s&&(o[`x-metadata`]=this.toBase64(this.encodeMetadata(s)))),r?.headers&&(o=Object.assign(Object.assign({},o),r.headers));let c=this._removeEmptyFolders(t),l=this._getFinalPath(c),u=yield(e==`PUT`?tt:A)(this.fetch,`${this.url}/object/${l}`,i,Object.assign({headers:o},a?.duplex?{duplex:a.duplex}:{}));return{data:{path:c,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}upload(e,t,n){return j(this,void 0,void 0,function*(){return this.uploadOrUpdate(`POST`,e,t,n)})}uploadToSignedUrl(e,t,n,r){return j(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),a=this._getFinalPath(i),o=new URL(this.url+`/object/upload/sign/${a}`);o.searchParams.set(`token`,t);try{let e,t=Object.assign({upsert:at.upsert},r),a=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});return typeof Blob<`u`&&n instanceof Blob?(e=new FormData,e.append(`cacheControl`,t.cacheControl),e.append(``,n)):typeof FormData<`u`&&n instanceof FormData?(e=n,e.append(`cacheControl`,t.cacheControl)):(e=n,a[`cache-control`]=`max-age=${t.cacheControl}`,a[`content-type`]=t.contentType),{data:{path:i,fullPath:(yield tt(this.fetch,o.toString(),e,{headers:a})).Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}createSignedUploadUrl(e,t){return j(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e),r=Object.assign({},this.headers);t?.upsert&&(r[`x-upsert`]=`true`);let i=yield A(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:r}),a=new URL(this.url+i.url),o=a.searchParams.get(`token`);if(!o)throw new We(`No token returned by API`);return{data:{signedUrl:a.toString(),path:e,token:o},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}update(e,t,n){return j(this,void 0,void 0,function*(){return this.uploadOrUpdate(`PUT`,e,t,n)})}move(e,t,n){return j(this,void 0,void 0,function*(){try{return{data:yield A(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,de
19stinationBucket:n?.destinationBucket},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}copy(e,t,n){return j(this,void 0,void 0,function*(){try{return{data:{path:(yield A(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}createSignedUrl(e,t,n){return j(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=yield A(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},n?.transform?{transform:n.transform}:{}),{headers:this.headers}),a=n?.download?`&download=${n.download===!0?``:n.download}`:``;return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${a}`)},{data:i,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}createSignedUrls(e,t,n){return j(this,void 0,void 0,function*(){try{let r=yield A(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=n?.download?`&download=${n.download===!0?``:n.download}`:``;return{data:r.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}download(e,t){return j(this,void 0,void 0,function*(){let n=t?.transform===void 0?`object`:`render/image/authenticated`,r=this.transformOptsToQueryString(t?.transform||{}),i=r?`?${r}`:``;try{let t=this._getFinalPath(e);return{data:yield(yield k(this.fetch,`${this.url}/${n}/${t}${i}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}info(e){return j(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return{data:Xe(yield k(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers})),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}exists(e){return j(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield nt(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e)&&e instanceof Ke){let t=e.originalError;if([400,404].includes(t?.status))return{data:!1,error:e}}throw e}})}getPublicUrl(e,t){let n=this._getFinalPath(e),r=[],i=t?.download?`download=${t.download===!0?``:t.download}`:``;i!==``&&r.push(i);let a=t?.transform===void 0?`object`:`render/image`,o=this.transformOptsToQueryString(t?.transform||{});o!==``&&r.push(o);let s=r.join(`&`);return s!==``&&(s=`?${s}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${n}${s}`)}}}remove(e){return j(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}list(e,t,n){return j(this,void 0,void 0,function*(){try{let r=Object.assign(Object.assign(Object.assign({},it),t),{prefix:e||``});return{data:yield A(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},n),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}listV2(e,t){return j(this,void 0,void 0,function*(){try{let n=Object.assign({},e);return{data:yield A(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,n,{headers:this.headers},t),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<`u`?Buffer.from(e).toString(`base64`):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,``)}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,``).replace(/\/+/g,`/`)}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join(`&`)}},st={"X-Client-Info":`storage-js/2.12.1`},M=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},ct=class{constructor(e,t={},n,r){this.shouldThrowOnError=!1;let i=new URL(e);r?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes(`storage.supabase.`)&&(i.hostname=i.hostname.replace(`supabase.`,`storage.supabase.`)),this.url=i.href,this.headers=Object.assign(Object.assign({},st),t),this.fetch=Je(n)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(){return M(this,void 0,void 0,function*(){try{return{data:yield k(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}getBucket(e){return M(this,void 0,void 0,function*(){try{return{data:yield k(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}createBucket(e,t={public:!1}){return M(this,void 0,void 0,function*(){try{return{data:yield A(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}updateBucket(e,t){return M(this,void 0,void 0,function*(){try{return{data:yield tt(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}emptyBucket(e){return M(this,void 0,void 0,function*(){try{return{data:yield A(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}deleteBucket(e){return M(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(E(e))return{data:null,error:e};throw e}})}},lt=class extends ct{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new ot(this.url,this.headers,e,this.fetch)}},ut=`2.57.4`,dt=``;dt=typeof Deno<`u`?`deno`:typeof document<`u`?`web`:typeof navigator<`u`&&navigator.product===`ReactNative`?`react-native`:`node`;var ft={headers:{"X-Client-Info":`supabase-js-${dt}/${ut}`}},pt={schema:`public`},mt={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:`implicit`},ht={};_();var gt=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},_t=e=>{let t;return t=e||(typeof fetch>`u`?te:fetch),(...e)=>t(...e)},vt=()=>typeof Headers>
19`u`?ne:Headers,yt=(e,t,n)=>{let r=_t(n),i=vt();return(n,a)=>gt(void 0,void 0,void 0,function*(){let o=(yield t())??e,s=new i(a?.headers);return s.has(`apikey`)||s.set(`apikey`,e),s.has(`Authorization`)||s.set(`Authorization`,`Bearer ${o}`),r(n,Object.assign(Object.assign({},a),{headers:s}))})},bt=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})};function xt(e){return e.endsWith(`/`)?e:e+`/`}function St(e,t){let{db:n,auth:r,realtime:i,global:a}=e,{db:o,auth:s,realtime:c,global:l}=t,u={db:Object.assign(Object.assign({},o),n),auth:Object.assign(Object.assign({},s),r),realtime:Object.assign(Object.assign({},c),i),storage:{},global:Object.assign(Object.assign(Object.assign({},l),a),{headers:Object.assign(Object.assign({},l?.headers??{}),a?.headers??{})}),accessToken:()=>bt(this,void 0,void 0,function*(){return``})};return e.accessToken?u.accessToken=e.accessToken:delete u.accessToken,u}function Ct(e){let t=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(xt(t))}catch{throw Error(`Invalid supabaseUrl: Provided URL is malformed.`)}}var wt=`2.71.1`,N=30*1e3,Tt=3*N,Et=`http://localhost:9999`,Dt=`supabase.auth.token`,Ot={"X-Client-Info":`gotrue-js/${wt}`},kt=`X-Supabase-Api-Version`,At={"2024-01-01":{timestamp:Date.parse(`2024-01-01T00:00:00.0Z`),name:`2024-01-01`}},jt=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Mt=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name=`AuthError`,this.status=t,this.code=n}};function P(e){return typeof e==`object`&&!!e&&`__isAuthError`in e}var Nt=class extends Mt{constructor(e,t,n){super(e,t,n),this.name=`AuthApiError`,this.status=t,this.code=n}};function Pt(e){return P(e)&&e.name===`AuthApiError`}var Ft=class extends Mt{constructor(e,t){super(e),this.name=`AuthUnknownError`,this.originalError=t}},F=class extends Mt{constructor(e,t,n,r){super(e,n,r),this.name=t,this.status=n}},I=class extends F{constructor(){super(`Auth session missing!`,`AuthSessionMissingError`,400,void 0)}};function It(e){return P(e)&&e.name===`AuthSessionMissingError`}var L=class extends F{constructor(){super(`Auth session or user missing`,`AuthInvalidToken
19ResponseError`,500,void 0)}},R=class extends F{constructor(e){super(e,`AuthInvalidCredentialsError`,400,void 0)}},z=class extends F{constructor(e,t=null){super(e,`AuthImplicitGrantRedirectError`,500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function Lt(e){return P(e)&&e.name===`AuthImplicitGrantRedirectError`}var Rt=class extends F{constructor(e,t=null){super(e,`AuthPKCEGrantCodeExchangeError`,500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},zt=class extends F{constructor(e,t){super(e,`AuthRetryableFetchError`,t,void 0)}};function Bt(e){return P(e)&&e.name===`AuthRetryableFetchError`}var Vt=class extends F{constructor(e,t,n){super(e,`AuthWeakPasswordError`,t,`weak_password`),this.reasons=n}},Ht=class extends F{constructor(e){super(e,`AuthInvalidJwtError`,400,`invalid_jwt`)}},B=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`.split(``),Ut=` 20\r=`.split(``),Wt=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Ut.length;t+=1)e[Ut[t].charCodeAt(0)]=-2;for(let t=0;t<B.length;t+=1)e[B[t].charCodeAt(0)]=t;return e})();function Gt(e,t,n){if(e!==null)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)n(B[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue<<=6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)n(B[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function Kt(e,t,n){let r=Wt[e];if(r>-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(r===-2)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function qt(e){let t=[],n=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=e=>{Xt(e,r,n)};for(let t=0;t<e.length;t+=1)Kt(e.charCodeAt(t),i,a);return t.join(``)}function Jt(e,t){if(e<=127){t(e);return}else if(e<=2047){t(192|e>>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function Yt(e,t){for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>55295&&r<=56319){let t=(r-55296)*1024&65535;r=(e.charCodeAt(n+1)-56320&65535|t)+65536,n+=1}Jt(r,t)}}function Xt(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let n=1;n<6;n+=1)if(!(e>>7-n&1)){t.utf8seq=n;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw Error(`Invalid UTF-8 sequence`);--t.utf8seq}else if(t.utf8seq>0){if(e<=127)throw Error(`Invalid UTF-8 sequence`);t.codepoint=t.codepoint<<6|e&63,--t.utf8seq,t.utf8seq===0&&n(t.codepoint)}}function Zt(e){let t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)Kt(e.charCodeAt(t),n,r);return new Uint8Array(t)}function Qt(e){let t=[];return Yt(e,e=>t.push(e)),new Uint8Array(t)}function $t(e){let t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>Gt(e,n,r)),Gt(null,n,r),t.join(``)}function en(e){return Math.round(Date.now()/1e3)+e}function tn(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e==`x`?t:t&3|8).toString(16)})}var V=()=>typeof window<`u`&&typeof document<`u`,H={tested:!1,writable:!1},nn=()=>{if(!V())return!1;try{if(typeof globalThis.localStorage!=`object`)return!1}catch{return!1}if(H.tested)return H.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),H.tested=!0,H.writable=!0}catch{H.tested=!0,H.writable=!1}return H.writable};function rn(e){let t={},n=new URL(e);if(n.hash&&n.hash[0]===`#`)try{new URLSearchParams(n.hash.substring(1)).forEach((e,n)=>{t[n]=e})}catch{}return n.searchParams.forEach((e,n)=>{t[n]=e}),t}var an=e=>{let t;return t=e||(typeof fetch>`u`?(...e)=>a(async()=>{let{default:e}=await Promise.resolve().then(()=>(_(),m));return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},on=e=>typeof e==`object`&&!!e&&`status`in e&&`ok`in e&&`json`in e&&typeof e.json==`function`,U=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},W=async(e,t)=>{let n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},G=async(e,t)=>{await e.removeItem(t)},sn=class e{constructor(){this.promise=new e.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};sn.promiseConstructor=Promise;function cn(e){let t=e.split(`.`);if(t.length!==3)throw new Ht(`Invalid JWT structure`);for(let e=0;e<t.length;e++)if(!jt.test(t[e]))throw new Ht(`JWT not in base64url format`);return{header:JSON.parse(qt(t[0])),payload:JSON.parse(qt(t[1])),signature:Zt(t[2]),raw:{header:t[0],payload:t[1]}}}async function ln(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function un(e,t){return new Promise((n,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{let r=await e(i);if(!t(i,null,r)){n(r);return}}catch(e){if(!t(i,e)){r(e);return}}})()})}function dn(e){return(`0`+e.toString(16)).substr(-2)}function fn(){let e=new Uint32Array(56);if(typeof crypto>`u`){let e=``;for(let t=0;t<56;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~`.charAt(Math.floor(Math.random()*66));return e}return crypto.getRandomValues(e),Array.from(e,dn).join(``)}async function pn(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t),r=new Uint8Array(n);return Array.from(r).map(e=>String.fromCharCode(e)).join(``)}async function mn(e){if(!(typeof crypto<`u`&&crypto.subtle!==void 0&&typeof TextEncoder<`u`))return console.warn(`WebCrypto API is not supported. Code
20challenge method will default to use plain instead of sha256.`),e;let t=await pn(e);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}async function K(e,t,n=!1){let r=fn(),i=r;n&&(i+=`/PASSWORD_RECOVERY`),await U(e,`${t}-code-verifier`,i);let a=await mn(r);return[a,r===a?`plain`:`s256`]}var hn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function gn(e){let t=e.headers.get(kt);if(!t||!t.match(hn))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function _n(e){if(!e)throw Error(`Missing exp claim`);if(e<=Math.floor(Date.now()/1e3))throw Error(`JWT has expired`)}function vn(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`)}}var yn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function q(e){if(!yn.test(e))throw Error(`@supabase/auth-js: Expected parameter to be UUID but is not`)}function bn(){return new Proxy({},{get:(e,t)=>{if(t===`__isUserNotAvailableProxy`)return!0;if(typeof t==`symbol`){let e=t.toString();if(e===`Symbol(Symbol.toPrimitive)`||e===`Symbol(Symbol.toStringTag)`||e===`Symbol(util.inspect.custom)`)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 xn(e){return JSON.parse(JSON.stringify(e))}var Sn=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n},J=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Cn=[502,503,504];async function wn(e){if(!on(e))throw new zt(J(e),0);if(Cn.includes(e.status))throw new zt(J(e),e.status);let t;try{t=await e.json()}catch(e){throw new Ft(J(e),e)}let n,r=gn(e);if(r&&r.getTime()>=At[`2024-01-01`].timestamp&&typeof t==`object`&&t&&typeof t.code==`string`?n=t.code:typeof t==`object`&&t&&typeof t.error_code==`string`&&(n=t.error_code),!n){if(typeof t==`object`&&t&&typeof t.weak_password==`object`&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((e,t)=>e&&typeof t==`string`,!0))throw new Vt(J(t),e.status,t.weak_password.reasons)}else if(n===`weak_password`)throw new Vt(J(t),e.status,t.weak_password?.reasons||[]);else if(n===`session_not_found`)throw new I;throw new Nt(J(t),e.status||500,n)}var Tn=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};return e===`GET`?i:(i.headers=Object.assign({"Content-Type":`application/json;charset=UTF-8`},t?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};async function Y(e,t,n,r){let i=Object.assign({},r?.headers);i[`X-Supabase-Api-Version`]||(i[kt]=At[`2024-01-01`].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);let a=r?.query??{};r?.redirectTo&&(a.redirect_to=r.redirectTo);let o=await En(e,t,n+(Object.keys(a).length?`?`+new URLSearchParams(a).toString():``),{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(o):{data:Object.assign({},o),error:null}}async function En(e,t,n,r,i,a){let o=Tn(t,r,i,a),s;try{s=await e(n,Object.assign({},o))}catch(e){throw console.error(e),new zt(J(e),0)}if(s.ok||await wn(s),r?.noResolveJson)return s;try{return await s.json()}catch(e){await wn(e)}}function X(e){let t=null;jn(e)&&(t=Object.assign({},e),e.expires_at||(t.expires_at=en(e.expires_in)));let n=e.user??e;return{data:{session:t,user:n},error:null}}function Dn(e){let t=X(e);return!t.error&&e.weak_password&&typeof e.weak_password==`object`&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message==`string`&&e.weak_password.reasons.reduce((e,t)=>
20e&&typeof t==`string`,!0)&&(t.data.weak_password=e.weak_password),t}function Z(e){return{data:{user:e.user??e},error:null}}function On(e){return{data:e,error:null}}function kn(e){let{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:a}=e,o=Sn(e,[`action_link`,`email_otp`,`hashed_token`,`redirect_to`,`verification_type`]);return{data:{properties:{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:a},user:Object.assign({},o)},error:null}}function An(e){return e}function jn(e){return e.access_token&&e.refresh_token&&e.expires_in}var Mn=[`global`,`local`,`others`],Nn=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n},Pn=class{constructor({url:e=``,headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=an(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t=Mn[0]){if(Mn.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${Mn.join(`, `)}`);try{return await Y(this.fetch,`POST`,`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(P(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await Y(this.fetch,`POST`,`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Z})}catch(e){if(P(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,n=Nn(e,[`options`]),r=Object.assign(Object.assign({},n),t);return`newEmail`in n&&(r.new_email=n?.newEmail,delete r.newEmail),await Y(this.fetch,`POST`,`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:kn,redirectTo:t?.redirectTo})}catch(e){if(P(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await Y(this.fetch,`POST`,`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Z})}catch(e){if(P(e))return{data:{user:null},error:e};throw e}}async listUsers(e){try{let t={nextPage:null,lastPage:0,total:0},n=await Y(this.fetch,`GET`,`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??``,per_page:(e?.perPage)?.toString()??``},xform:An});if(n.error)throw n.error;let r=await n.json(),i=n.headers.get(`x-total-count`)??0,a=n.headers.get(`link`)?.split(`,`)??[];return a.length>0&&(a.forEach(e=>{let n=parseInt(e.split(`;`)[0].split(`=`)[1].substring(0,1)),r=JSON.parse(e.split(`;`)[1].split(`=`)[1]);t[`${r}Page`]=n}),t.total=parseInt(i)),{data:Object.assign(Object.assign({},r),t),error:null}}catch(e){if(P(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){q(e);try{return await Y(this.fetch,`GET`,`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Z})}catch(e){if(P(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){q(e);try{return await Y(this.fetch,`PUT`,`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Z})}catch(e){if(P(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){q(e);try{return await Y(this.fetch,`DELETE`,`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Z})}catch(e){if(P(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){q(e.userId);try{let{data:t,error:n}=await Y(this.fetch,`GET`,`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:n}}catch(e){if(P(e))return{data:null,error:e};throw e}}async _deleteFactor(e){q(e.userId),q(e.id);try{return{data:await Y(this.fetch,`DELETE`,`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(P(e))return{data:null,error:e};throw e}}};function Fn(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}function In(){if(typeof globalThis!=`object`)try{Object.defineProperty(Object.prototype,`__magic__`,{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<`u`&&(self.globalThis=self)}}var Q={debug:!!(globalThis&&nn()&&globalThis.localStorage&&globalThis.localStorage.getItem(`supabase.gotrue-js.locks.debug`)===`true`)}
20,Ln=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Rn=class extends Ln{};async function zn(e,t,n){Q.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquire lock`,e,t);let r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),Q.debug&&console.log(`@supabase/gotrue-js: navigatorLock acquire timed out`,e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,t===0?{mode:`exclusive`,ifAvailable:!0}:{mode:`exclusive`,signal:r.signal},async r=>{if(r){Q.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquired`,e,r.name);try{return await n()}finally{Q.debug&&console.log(`@supabase/gotrue-js: navigatorLock: released`,e,r.name)}}else if(t===0)throw Q.debug&&console.log(`@supabase/gotrue-js: navigatorLock: not immediately available`,e),new Rn(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);else{if(Q.debug)try{let e=await globalThis.navigator.locks.query();console.log(`@supabase/gotrue-js: Navigator LockManager state`,JSON.stringify(e,null,` `))}catch(e){console.warn(`@supabase/gotrue-js: Error when querying Navigator LockManager state`,e)}return console.warn(`@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request`),await n()}}))}In();var Bn={url:Et,storageKey:Dt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ot,flowType:`implicit`,debug:!1,hasCustomAuthorizationHeader:!1};async function Vn(e,t,n){return await n()}var $={},Hn=class e{constructor(t){var n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=e.nextInstanceID,e.nextInstanceID+=1,this.instanceID>0&&V()&&console.warn(`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.`);let r=Object.assign(Object.assign({},Bn),t);if(this.logDebugMessages=!!r.debug,typeof r.debug==`function`&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new Pn({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=an(r.fetch),this.lock=r.lock||Vn,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:V()&&(globalThis==null?void 0:globalThis.navigator)?.locks?this.lock=zn:this.lock=Vn,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=-(2**53-1)),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)},this.persistSession?(r.storage?this.storage=r.storage:nn()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Fn(this.memoryStorage)),r.userStorage&&(this.userStorage=r.userStorage)):(this.memoryStorage={},this.storage=Fn(this.memoryStorage)),V()&&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)}(n=this.broadcastChannel)==null||n.addEventListener(`message`,async e=>{this._debug(`received broadcast notification from other tab or client`,e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}get jwks(){return $[this.storageKey]?.jwks??{keys:[]}}set jwks(e){$[this.storageKey]=Object.assign(Object.assign({},$[this.storageKey]),{jwks:e})}get jwks_cached_at(){return $[this.storageKey]?.cachedAt??-(2**53-1)}set jwks_cached_at(e){$[this.storageKey]=Object.assign(Object.assign({},$[this.storageKey]),{cachedAt:e})}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${wt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise||=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise}async _initialize(){try{let e=rn(window.location.href),t=`none`;if(this._isImplicitGrantCallback(e)?t=`implicit`:await this._isPKCECallback(e)&&(t=`pkce`),V()&&this.detectSessionInUrl&&t!==`none`){let{data:n,error:r}=await this._getSessionFromURL(e,t);if(r){if(this._debug(`#_initialize()`,`error detecting session from URL`,r),Lt(r)){let e=r.details?.code;if(e===`identity_already_exists`||e===`identity_not_found`||e===`single_identity_not_deletable`)return{error:r}}return await this._removeSession(),{error:r}}let{session:i,redirectType:a}=n;return this._debug(`#_initialize()`,`detected session in URL`,i,`redirect type`,a),await this._saveSession(i),setTimeout(async()=>{a===`recovery`?await this._notifyAllSubscribers(`PASSWORD_RECOVERY`,i):await this._notifyAllSubscribers(`SIGNED_IN`,i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return P(e)?{error:e}:{error:new Ft(`Unexpected error during initialization`,e)}}finally{await this._handleVisibilityChange(),this._debug(`#_initialize()`,`end`)}}async signInAnonymously(e){try{let{data:t,error:n}=await Y(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,body:{data:e?.options?.data??{},gotrue_meta_security:{captcha_token:e?.options?.captchaToken}},xform:X});if(n||!t)return{data:{user:null,session:null},error:n};let r=t.session,i=t.user;return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers(`SIGNED_IN`,r)),{data:{user:i,session:r},error:null}}catch(e){if(P(e))return{data:{user:null,session:null},error:e};throw e}}async signUp(e){try{let t;if(`email`in e){let{email:n,password:r,options:i}=e,a=null,o=null;this.flowType===`pkce`&&([a,o]=await K(this.storage,this.storageKey)),t=await Y(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,redirectTo:i?.emailRedirectTo,body:{email:n,password:r,data:i?.data??{},gotrue_meta_security:{captcha_token:i?.captchaToken},code_challenge:a,code_challenge_method:o},xform:X})}else if(`phone`in e){let{phone:n,password:r,options:i}=e;t=await Y(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,body:{phone:n,password:r,data:i?.data??{},channel:i?.channel??`sms`,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:X})}else throw new R(`You must provide either an email or phone number and a password`);let{data:n,error:r}=t;if(r||!n)return{data:{user:null,session:null},error:r};let i=n.session,a=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers(`SIGNED_IN`,i)),{data:{user:a,session:i},error:null}}catch(e){if(P(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithPassword(e){try{let t;if(`email`in e){let{email:n,password:r,options:i}=e;t=await Y(this.fetch,`POST`,`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Dn})}else if(`phone`in e){let{phone:n,password:r,options:i}=e;t=await Y(this.fetch,`POST`,`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Dn})}else throw new R(`You must provide either an email or phone number and a password`);let{data:n,error:r}=t;return r?{data:{user:null,session:null},error:r}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new L}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers(`SIGNED_IN`,n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:r})}catch(e){if(P(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOAuth(e){return await this._handleProviderSignIn(e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:e.options?.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;if(t===`solana`)return await this.signInWithSolana(e);throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}async signInWithSolana(e){let t,n;if(`message`in e)t=e.message,n=e.signature;else{let{chain:r,wallet:i,statement:a,options:o}=e,s;
20if(!V()){if(typeof i!=`object`||!o?.url)throw Error(`@supabase/auth-js: Both wallet and url must be specified in non-browser environments.`);s=i}else if(typeof i==`object`)s=i;else{let e=window;if(`solana`in e&&typeof e.solana==`object`&&(`signIn`in e.solana&&typeof e.solana.signIn==`function`||`signMessage`in e.solana&&typeof e.solana.signMessage==`function`))s=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.`)}let c=new URL(o?.url??window.location.href);if(`signIn`in s&&s.signIn){let e=await s.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},o?.signInWithSolana),{version:`1`,domain:c.host,uri:c.href}),a?{statement:a}:null)),r;if(Array.isArray(e)&&e[0]&&typeof e[0]==`object`)r=e[0];else if(e&&typeof e==`object`&&`signedMessage`in e&&`signature`in e)r=e;else throw Error(`@supabase/auth-js: Wallet method signIn() returned unrecognized value`);if(`signedMessage`in r&&`signature`in r&&(typeof r.signedMessage==`string`||r.signedMessage instanceof Uint8Array)&&r.signature instanceof Uint8Array)t=typeof r.signedMessage==`string`?r.signedMessage:new TextDecoder().decode(r.signedMessage),n=r.signature;else throw Error(`@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields`)}else{if(!(`signMessage`in s)||typeof s.signMessage!=`function`||!(`publicKey`in s)||typeof s!=`object`||!s.publicKey||!(`toBase58`in s.publicKey)||typeof s.publicKey.toBase58!=`function`)throw Error(`@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API`);t=[`${c.host} wants you to sign in with your Solana account:`,s.publicKey.toBase58(),...a?[``,a,``]:[``],`Version: 1`,`URI: ${c.href}`,`Issued At: ${o?.signInWithSolana?.issuedAt??new Date().toISOString()}`,...o?.signInWithSolana?.notBefore?[`Not Before: ${o.signInWithSolana.notBefore}`]:[],...o?.signInWithSolana?.expirationTime?[`Expiration Time: ${o.signInWithSolana.expirationTime}`]:[],...o?.signInWithSolana?.chainId?[`Chain ID: ${o.signInWithSolana.chainId}`]:[],...o?.signInWithSolana?.nonce?[`Nonce: ${o.signInWithSolana.nonce}`]:[],...o?.signInWithSolana?.requestId?[`Request ID: ${o.signInWithSolana.requestId}`]:[],...o?.signInWithSolana?.resources?.length?[`Resources`,...o.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join(` 21`);let e=await s.signMessage(new TextEncoder().encode(t),`utf8`);if(!e||!(e instanceof Uint8Array))throw Error(`@supabase/auth-js: Wallet signMessage() API returned an recognized value`);n=e}}try{let{data:r,error:i}=await Y(this.fetch,`POST`,`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:`solana`,message:t,signature:$t(n)},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:X});if(i)throw i;return!r||!r.session||!r.user?{data:{user:null,session:null},error:new L}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,r.session)),{data:Object.assign({},r),error:i})}catch(e){if(P(e))return{data:{user:null,session:null},error:e};throw e}}async _exchangeCodeForSession(e){let[t,n]=(await W(this.storage,`${this.storageKey}-code-verifier`)??``).split(`/`);try{let{data:r,error:i}=await Y(this.fetch,`POST`,`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:X});if(await G(this.storage,`${this.storageKey}-code-verifier`),i)throw i;return!r||!r.session||!r.user?{data:{user:null,session:null,redirectType:null},error:new L}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,r.session)),{data:Object.assign(Object.assign({},r),{redirectType:n??null}),error:i})}catch(e){if(P(e))return{data:{user:null,session:null,redirectType:null},error:e};throw e}}async signInWithIdToken(e){try{let{options:t,provider:n,token:r,access_token:i,nonce:a}=e,{data:o,error:s}=await Y(this.fetch,`POST`,`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:r,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:X});return s?{data:{user:null,session:null},error:s}:!o||!o.session||!o.user?{data:{user:null,session:null},error:new L}:(o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers(`SIGNED_IN`,o.session)),{data:o,error:s})}catch(e){if(P(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOtp(e){try{if(`email`in e){let{email:t,options:n}=e,r=null,i=null;this.flowType===`pkce`&&([r,i]=await K(this.storage,this.storageKey));let{error:a}=await Y(this.fetch,`POST`,`${this.url}/otp`,{headers:this.headers,body:{email:t,data:n?.data??{},create_user:n?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:n?.captchaToken},code_challenge:r,code_challenge_method:i},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:a}}if(`phone`in e){let{phone:t,options:n}=e,{data:r,error:i}=await Y(this.fetch,`POST`,`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:n?.data??{},create_user:n?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:n?.captchaToken},channel:n?.channel??`sms`}});return{data:{user:null,session:null,messageId:r?.message_id},error:i}}throw new R(`You must provide either an email or phone number.`)}catch(e){if(P(e))return{data:{user:null,session:null},error:e};throw e}}async verifyOtp(e){try{let t,n;`options`in e&&(t=e.options?.redirectTo,n=e.options?.captchaToken);let{data:r,error:i}=await Y(this.fetch,`POST`,`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:t,xform:X});if(i)throw i;if(!r)throw Error(`An error occurred on token verification.`);let a=r.session,o=r.user;return a?.access_token&&(await this._saveSession(a),await this._notifyAllSubscribers(e.type==`recovery`?`PASSWORD_RECOVERY`:`SIGNED_IN`,a)),{data:{user:o,session:a},error:null}}catch(e){if(P(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSSO(e){try{let t=null,n=null;return this.flowType===`pkce`&&([t,n]=await K(this.storage,this.storageKey)),await Y(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:e.options?.redirectTo??void 0}),e?.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:t,code_challenge_method:n}),headers:this.headers,xform:On})}catch(e){if(P(e))return{data:null,error:e};throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new I;let{error:r}=await Y(this.fetch,`GET`,`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(P(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if(`email`in e){let{email:n,type:r,options:i}=e,{error:a}=await Y(this.fetch,`POST`,t,{headers:this.headers,body:{email:n,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return{data:{user:null,session:null},error:a}}else if(`phone`in e){let{phone:n,type:r,options:i}=e,{data:a,error:o}=await Y(this.fetch,`POST`,t,{headers:this.headers,body:{phone:n,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return{data:{user:null,session:null,messageId:a?.message_id},error:o}}throw new R(`You must provide either an email or phone number and a type`)}catch(e){if(P(e))return{data:{user:null,session:null},error:e};throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>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(),n=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}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{}})()),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{return await e(await this.__loadSession())}finally{this._debug(`#_useSession`,`end`)}}async __loadSession(){this._debug(`#__loadSession()`,`begin`),this.lockAcquired||this._debug(`#__loadSession()`,`used outside of an acquired lock!`,Error().stack);try{let e=null,t=await W(this.storage,this.storageKey);if(this._debug(`#getSession()`,`session from storage`,t),t!==null&&(this._isValidSession(t)?e=t:(this._debug(`#getSession()`,`session from storage is not val
21id`),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<Tt:!1;if(this._debug(`#__loadSession()`,`session has${n?``:` not`} expired`,`expires_at`,e.expires_at),!n){if(this.userStorage){let t=await W(this.userStorage,this.storageKey+`-user`);t?.user?e.user=t.user:e.user=bn()}if(this.storage.isServer&&e.user){let t=this.suppressGetSessionWarning;e=new Proxy(e,{get:(e,n,r)=>(!t&&n===`user`&&(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.`),t=!0,this.suppressGetSessionWarning=!0),Reflect.get(e,n,r))})}return{data:{session:e},error:null}}let{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:r},error:null}}finally{this._debug(`#__loadSession()`,`end`)}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await Y(this.fetch,`GET`,`${this.url}/user`,{headers:this.headers,jwt:e,xform:Z}):await this._useSession(async e=>{let{data:t,error:n}=e;if(n)throw n;return!t.session?.access_token&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new I}:await Y(this.fetch,`GET`,`${this.url}/user`,{headers:this.headers,jwt:t.session?.access_token??void 0,xform:Z})})}catch(e){if(P(e))return It(e)&&(await this._removeSession(),await G(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:e};throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async n=>{let{data:r,error:i}=n;if(i)throw i;if(!r.session)throw new I;let a=r.session,o=null,s=null;this.flowType===`pkce`&&e.email!=null&&([o,s]=await K(this.storage,this.storageKey));let{data:c,error:l}=await Y(this.fetch,`PUT`,`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:s}),jwt:a.access_token,xform:Z});if(l)throw l;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers(`USER_UPDATED`,a),{data:{user:a.user},error:null}})}catch(e){if(P(e))return{data:{user:null},error:e};throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new I;let t=Date.now()/1e3,n=t,r=!0,i=null,{payload:a}=cn(e.access_token);if(a.exp&&(n=a.exp,r=n<=t),r){let{session:t,error:n}=await this._callRefreshToken(e.refresh_token);if(n)return{data:{user:null,session:null},error:n};if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:r,error:a}=await this._getUser(e.access_token);if(a)throw a;i={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:`bearer`,expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers(`SIGNED_IN`,i)}return{data:{user:i.user,session:i},error:null}}catch(e){if(P(e))return{data:{session:null,user:null},error:e};throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{if(!e){let{data:n,error:r}=t;if(r)throw r;e=n.session??void 0}if(!e?.refresh_token)throw new I;let{session:n,error:r}=await this._callRefreshToken(e.refresh_token);return r?{data:{user:null,session:null},error:r}:n?{data:{user:n.user,session:n},error:null}:{data:{user:null,session:null},error:null}})}catch(e){if(P(e))return{data:{user:null,session:null},error:e};throw e}}async _getSessionFromURL(e,t){try{if(!V())throw new z(`No browser detected.`);if(e.error||e.error_description||e.error_code)throw new z(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(this.flowType===`pkce`)throw new Rt(`Not a valid PKCE flow url.`);break;case`pkce`:if(this.flowType===`implicit`)throw new z(`Not a valid implicit grant flow url.`);break;default:}if(t===`pkce`){if(this._debug(`#_initialize()`,`begin`,`is PKCE flow`,!0),!e.code)throw new Rt(`No code detected.`);let{data:t,error:n}=await this._exchangeCodeForSession(e.code);
21if(n)throw n;let r=new URL(window.location.href);return r.searchParams.delete(`code`),window.history.replaceState(window.history.state,``,r.toString()),{data:{session:t.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:r,access_token:i,refresh_token:a,expires_in:o,expires_at:s,token_type:c}=e;if(!i||!o||!a||!c)throw new z(`No session defined in URL`);let l=Math.round(Date.now()/1e3),u=parseInt(o),d=l+u;s&&(d=parseInt(s));let f=d-l;f*1e3<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let p=d-u;l-p>=120?console.warn(`@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale`,p,d,l):l-p<0&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew`,p,d,l);let{data:m,error:h}=await this._getUser(i);if(h)throw h;let g={provider_token:n,provider_refresh_token:r,access_token:i,expires_in:u,expires_at:d,refresh_token:a,token_type:c,user:m.user};return window.location.hash=``,this._debug(`#_getSessionFromURL()`,`clearing window.location.hash`),{data:{session:g,redirectType:e.type},error:null}}catch(e){if(P(e))return{data:{session:null,redirectType:null},error:e};throw e}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await W(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:`global`}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:`global`}){return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return{error:r};let i=n.session?.access_token;if(i){let{error:t}=await this.admin.signOut(i,e);if(t&&!(Pt(t)&&(t.status===404||t.status===401||t.status===403)))return{error:t}}return e!==`others`&&(await this._removeSession(),await G(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=tn(),n={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,n),(async()=>{await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{try{let{data:{session:n},error:r}=t;if(r)throw r;await this.stateChangeEmitters.get(e)?.callback(`INITIAL_SESSION`,n),this._debug(`INITIAL_SESSION`,`callback id`,e,`session`,n)}catch(t){await this.stateChangeEmitters.get(e)?.callback(`INITIAL_SESSION`,null),this._debug(`INITIAL_SESSION`,`callback id`,e,`error`,t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let n=null,r=null;this.flowType===`pkce`&&([n,r]=await K(this.storage,this.storageKey,!0));try{return await Y(this.fetch,`POST`,`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(P(e))return{data:null,error:e};throw e}}async getUserIdentities(){try{let{data:e,error:t}=await this.getUser();if(t)throw t;return{data:{identities:e.user.identities??[]},error:null}}catch(e){if(P(e))return{data:null,error:e};throw e}}async linkIdentity(e){try{let{data:t,error:n}=await this._useSession(async t=>{let{data:n,error:r}=t;if(r)throw r;let i=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:!0});return await Y(this.fetch,`GET`,i,{headers:this.headers,jwt:n.session?.access_token??void 0})});if(n)throw n;return V()&&!e.options?.skipBrowserRedirect&&window.location.assign(t?.url),{data:{provider:e.provider,url:t?.url},error:null}}catch(t){if(P(t))return{data:{provider:e.provider,url:null},error:t};throw t}}async unlinkIdentity(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)throw r;return await Y(this.fetch,`DELETE`,`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:n.session?.access_token??void 0})})}catch(e){if(P(e))return{data:null,error:e};throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,`begin`);try{let n=Date.now();return await un(async n=>(n>0&&await ln(200*2**(n-1)),this._debug(t,`refreshing attempt`,n),await Y(this.fetch,`POST`,`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:X})),(e,t)=>{let r=200*2**e;return t&&Bt(t)&&Date.now()+r-n<3e4})}catch(e){if(this._debug(t,`error`,e),P(e))return{data:{session:null,user:null},error:e};throw e}finally{this._debug(t,`end`)}}_isValidSession(e){return typeof e==`object`&&!!e&&`access_token`in e&&`refresh_token`in e&&`expires_at`in e}async _handleProviderSignIn(e,t){let n=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`,n),V()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){let e=`#_recoverAndRefresh()`;this._debug(e,`begin`);try{let t=await W(this.storage,this.storageKey);if(t&&this.userStorage){let e=await W(this.userStorage,this.storageKey+`-user`);!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!e&&(e={user:t.user},await U(this.userStorage,this.storageKey+`-user`,e)),t.user=e?.user??bn()}else if(t&&!t.user&&!t.user){let e=await W(this.storage,this.storageKey+`-user`);e&&e?.user?(t.user=e.user,await G(this.storage,this.storageKey+`-user`),await U(this.storage,this.storageKey,t)):t.user=bn()}if(this._debug(e,`session from storage`,t),!this._isValidSession(t)){this._debug(e,`session is not val
21id`),t!==null&&await this._removeSession();return}let n=(t.expires_at??1/0)*1e3-Date.now()<Tt;if(this._debug(e,`session has${n?``:` not`} expired with margin of ${Tt}s`),n){if(this.autoRefreshToken&&t.refresh_token){let{error:n}=await this._callRefreshToken(t.refresh_token);n&&(console.error(n),Bt(n)||(this._debug(e,`refresh failed with a non-retryable error, removing the session`,n),await this._removeSession()))}}else if(t.user&&t.user.__isUserNotAvailableProxy===!0)try{let{data:n,error:r}=await this._getUser(t.access_token);!r&&n?.user?(t.user=n.user,await this._saveSession(t),await this._notifyAllSubscribers(`SIGNED_IN`,t)):this._debug(e,`could not get user data, skipping SIGNED_IN notification`)}catch(t){console.error(`Error getting user data:`,t),this._debug(e,`error getting user data, skipping SIGNED_IN notification`,t)}else await this._notifyAllSubscribers(`SIGNED_IN`,t)}catch(t){this._debug(e,`error`,t),console.error(t);return}finally{this._debug(e,`end`)}}async _callRefreshToken(e){var t,n;if(!e)throw new I;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,`begin`);try{this.refreshingDeferred=new sn;let{data:t,error:n}=await this._refreshAccessToken(e);if(n)throw n;if(!t.session)throw new I;await this._saveSession(t.session),await this._notifyAllSubscribers(`TOKEN_REFRESHED`,t.session);let r={session:t.session,error:null};return this.refreshingDeferred.resolve(r),r}catch(e){if(this._debug(r,`error`,e),P(e)){let n={session:null,error:e};return Bt(e)||await this._removeSession(),(t=this.refreshingDeferred)==null||t.resolve(n),n}throw(n=this.refreshingDeferred)==null||n.reject(e),e}finally{this.refreshingDeferred=null,this._debug(r,`end`)}}async _notifyAllSubscribers(e,t,n=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,`begin`,t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let r=[],i=Array.from(this.stateChangeEmitters.values()).map(async n=>{try{await n.callback(e,t)}catch(e){r.push(e)}});if(await Promise.all(i),r.length>0){for(let e=0;e<r.length;e+=1)console.error(r[e]);throw r[0]}}finally{this._debug(r,`end`)}}async _saveSession(e){this._debug(`#_saveSession()`,e),this.suppressGetSessionWarning=!0;let t=Object.assign({},e),n=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&t.user&&await U(this.userStorage,this.storageKey+`-user`,{user:t.user});let e=Object.assign({},t);delete e.user;let r=xn(e);await U(this.storage,this.storageKey,r)}else{let e=xn(t);await U(this.storage,this.storageKey,e)}}async _removeSession(){this._debug(`#_removeSession()`),await G(this.storage,this.storageKey),await G(this.storage,this.storageKey+`-code-verifier`),await G(this.storage,this.storageKey+`-user`),this.userStorage&&await G(this.userStorage,this.storageKey+`-user`),await this._notifyAllSubscribers(`SIGNED_OUT`,null)}_removeVisibilityChangedCallback(){this._debug(`#_removeVisibilityChangedCallback()`);let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&V()&&window!=null&&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(),N);this.autoRefreshTicker=e,e&&typeof e==`object`&&typeof e.unref==`function`?e.unref():typeof Deno<`u`&&typeof Deno.unrefTimer==`function`&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug(`#_stopAutoRefresh()`);let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug(`#_autoRefreshTokenTick()`,`begin`);try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug(`#_autoRefreshTokenTick()`,`no session`);return}let r=Math.floor((n.expires_at*1e3-e)/N);this._debug(`#_autoRefreshTokenTick()`,`access token expires in ${r} ticks, a tick lasts ${N}ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(n.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.isAcquireTimeout||e instanceof Ln)this._debug(`auto refresh token tick lock not available`);else throw e}}async _handleVisibilityChange(){if(this._debug(`#_handleVisibilityChange()`),!V()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener(`visibilitychange`,this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error(`_handleVisibilityChange`,e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,`visibilityState`,document.visibilityState),document.visibilityState===`visible`?(this.autoRefreshToken&&this._startAutoRefresh(),e||(
21await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!==`visible`){this._debug(t,`acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting`);return}await this._recoverAndRefresh()}))):document.visibilityState===`hidden`&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let r=[`provider=${encodeURIComponent(t)}`];if(n?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&r.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType===`pkce`){let[e,t]=await K(this.storage,this.storageKey),n=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});r.push(n.toString())}if(n?.queryParams){let e=new URLSearchParams(n.queryParams);r.push(e.toString())}return n?.skipBrowserRedirect&&r.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${r.join(`&`)}`}async _unenroll(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;return r?{data:null,error:r}:await Y(this.fetch,`DELETE`,`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:n?.session?.access_token})})}catch(e){if(P(e))return{data:null,error:e};throw e}}async _enroll(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return{data:null,error:r};let i=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType===`phone`?{phone:e.phone}:{issuer:e.issuer}),{data:a,error:o}=await Y(this.fetch,`POST`,`${this.url}/factors`,{body:i,headers:this.headers,jwt:n?.session?.access_token});return o?{data:null,error:o}:(e.factorType===`totp`&&a?.totp?.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(e){if(P(e))return{data:null,error:e};throw e}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return{data:null,error:r};let{data:i,error:a}=await Y(this.fetch,`POST`,`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:n?.session?.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+i.expires_in},i)),await this._notifyAllSubscribers(`MFA_CHALLENGE_VERIFIED`,i),{data:i,error:a})})}catch(e){if(P(e))return{data:null,error:e};throw e}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;return r?{data:null,error:r}:await Y(this.fetch,`POST`,`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:n?.session?.access_token})})}catch(e){if(P(e))return{data:null,error:e};throw e}})}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?{data:null,error:n}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let n=e?.factors||[];return{data:{all:n,totp:n.filter(e=>e.factor_type===`totp`&&e.status===`verified`),phone:n.filter(e=>e.factor_type===`phone`&&e.status===`verified`)},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)return{data:null,error:n};if(!t)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:r}=cn(t.access_token),i=null;r.aal&&(i=r.aal);let a=i;(t.user.factors?.filter(e=>e.status===`verified`)??[]).length>0&&(a=`aal2`);let o=r.amr||[];return{data:{currentLevel:i,nextLevel:a,currentAuthenticationMethods:o},error:null}}))}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(t=>t.kid===e);if(n)return n;let r=Date.now();if(n=this.jwks.keys.find(t=>t.kid===e),n&&this.jwks_cached_at+6e5>r)return n;let{data:i,error:a}=await Y(this.fetch,`GET`,`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=r,n=i.keys.find(t=>t.kid===e),!n)?null:n}async getClaims(e,t={}){try{let n=e;if(!n){let{data:e,error:t}
21=await this.getSession();if(t||!e.session)return{data:null,error:t};n=e.session.access_token}let{header:r,payload:i,signature:a,raw:{header:o,payload:s}}=cn(n);t?.allowExpired||_n(i.exp);let c=!r.alg||r.alg.startsWith(`HS`)||!r.kid||!(`crypto`in globalThis&&`subtle`in globalThis.crypto)?null:await this.fetchJwk(r.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!c){let{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:i,header:r,signature:a},error:null}}let l=vn(r.alg),u=await crypto.subtle.importKey(`jwk`,c,l,!0,[`verify`]);if(!await crypto.subtle.verify(l,u,a,Qt(`${o}.${s}`)))throw new Ht(`Invalid JWT signature`);return{data:{claims:i,header:r,signature:a},error:null}}catch(e){if(P(e))return{data:null,error:e};throw e}}};Hn.nextInstanceID=0;var Un=Hn,Wn=class extends Un{constructor(e){super(e)}},Gn=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Kn=class{constructor(e,t,n){this.supabaseUrl=e,this.supabaseKey=t;let r=Ct(e);if(!t)throw Error(`supabaseKey is required.`);this.realtimeUrl=new URL(`realtime/v1`,r),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace(`http`,`ws`),this.authUrl=new URL(`auth/v1`,r),this.storageUrl=new URL(`storage/v1`,r),this.functionsUrl=new URL(`functions/v1`,r);let i=`sb-${r.hostname.split(`.`)[0]}-auth-token`,a={db:pt,realtime:ht,auth:Object.assign(Object.assign({},mt),{storageKey:i}),global:ft},o=St(n??{},a);this.storageKey=o.auth.storageKey??``,this.headers=o.global.headers??{},o.accessToken?(this.accessToken=o.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(o.auth??{},this.headers,o.global.fetch),this.fetch=yt(t,this._getAccessToken.bind(this),o.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},o.realtime)),this.rest=new de(new URL(`rest/v1`,r).href,{headers:this.headers,schema:o.db.schema,fetch:this.fetch}),this.storage=new lt(this.storageUrl.href,this.headers,this.fetch,n?.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new p(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={},n={}){return this.rest.rpc(e,t,n)}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()}_getAccessToken(){return Gn(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();let{data:e}=yield this.auth.getSession();return e.session?.access_token??this.supabaseKey})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,storageKey:a,flowType:o,lock:s,debug:c},l,u){let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Wn({url:this.authUrl.href,headers:Object.assign(Object.assign({},d),l),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,flowType:o,lock:s,debug:c,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>e.toLowerCase()===`authorization`)})}_initRealtimeClient(e){return new Ue(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,`CLIENT`,t?.access_token)})}_handleTokenChanged(e,t,n){(e===`TOKEN_REFRESHED`||e===`SIGNED_IN`)&&this.changedAccessToken!==n?this.changedAccessToken=n:e===`SIGNED_OUT`&&(this.realtime.setAuth(),t==`STORAGE`&&this.auth.signOut(),this.changedAccessToken=void 0)}},qn=(e,t,n)=>new Kn(e,t,n);function Jn(){if(typeof window<`u`||typeof process>`u`)return!1;let e=process.version;if(e==null)return!1;let t=e.match(/^v(\d+)\./);return t?parseInt(t[1],10)<=18:!1}Jn()&&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 N
21ode.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217`);export{m as n,_ as r,qn as t};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.