1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,9156,(e,t,r)=>{"use strict";let s;Object.defineProperty(r,"__esModule",{value:!0}),r.parseCookie=u,r.parse=u,r.stringifyCookie=function(e,t){let r=t?.encode||encodeURIComponent,s=[];for(let t of Object.keys(e)){let a=e[t];if(void 0===a)continue;if(!i.test(t))throw TypeError(`cookie name is invalid: ${t}`);let o=r(a);if(!n.test(o))throw TypeError(`cookie val is invalid: ${a}`);s.push(`${t}=${o}`)}return s.join("; ")},r.stringifySetCookie=d,r.serialize=d,r.parseSetCookie=function(e,t){let r=t?.decode||m,s=e.length,i=p(e,0,s),n=f(e,0,i),a=-1===n?{name:"",value:r(g(e,0,i))}:{name:g(e,0,n),value:r(g(e,n+1,i))},o=i+1;for(;o<s;){let t=p(e,o,s),r=f(e,o,t),i=-1===r?g(e,o,t):g(e,o,r),n=-1===r?void 0:g(e,r+1,t);switch(i.toLowerCase()){case"httponly":a.httpOnly=!0;break;case"secure":a.secure=!0;break;case"partitioned":a.partitioned=!0;break;case"domain":a.domain=n;break;case"path":a.path=n;break;case"max-age":n&&l.test(n)&&(a.maxAge=Number(n));break;case"expires":if(!n)break;let h=new Date(n);Number.isFinite(h.valueOf())&&(a.expires=h);break;case"priority":if(!n)break;let c=n.toLowerCase();("low"===c||"medium"===c||"high"===c)&&(a.priority=c);break;case"samesite":if(!n)break;let u=n.toLowerCase();("lax"===u||"strict"===u||"none"===u)&&(a.sameSite=u)}o=t+1}return a},r.stringifySetCookie=d,r.serialize=d;let i=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,n=/^[\u0021-\u003A\u003C-\u007E]*$/,a=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,o=/^[\u0020-\u003A\u003D-\u007E]*$/,l=/^-?\d+$/,h=Object.prototype.toString,c=((s=function(){}).prototype=Object.create(null),s);function u(e,t){let r=new c,s=e.length;if(s<2)return r;let i=t?.decode||m,n=0;do{let t=f(e,n,s);if(-1===t)break;let a=p(e,n,s);if(t>a){n=e.lastIndexOf(";",t-1)+1;continue}let o=g(e,n,t);void 0===r[o]&&(r[o]=i(g(e,t+1,a))),n=a+1}while(n<s)return r}function d(e,t,r){let s="object"==typeof e?e:{...r,name:e,value:String(t)},l=("object"==typeof t?t:r)?.encode||encodeURIComponent;if(!i.test(s.name))throw TypeError(`argument name is invalid: ${s.name}`);let c=s.value?l(s.value):"";if(!n.test(c))throw TypeError(`argument val is invalid: ${s.value}`);let u=s.name+"="+c;if(void 0!==s.maxAge){if(!Number.isInteger(s.maxAge))throw TypeError(`option maxAge is invalid: ${s.maxAge}`);u+="; Max-Age="+s.maxAge}if(s.domain){if(!a.test(s.domain))throw TypeError(`option domain is invalid: ${s.domain}`);u+="; Domain="+s.domain}if(s.path){if(!o.test(s.path))throw TypeError(`option path is invalid: ${s.path}`);u+="; Path="+s.path}if(s.expires){var d;if(d=s.expires,"[object Date]"!==h.call(d)||!Number.isFinite(s.expires.valueOf()))throw TypeError(`option expires is invali
1d: ${s.expires}`);u+="; Expires="+s.expires.toUTCString()}if(s.httpOnly&&(u+="; HttpOnly"),s.secure&&(u+="; Secure"),s.partitioned&&(u+="; Partitioned"),s.priority)switch("string"==typeof s.priority?s.priority.toLowerCase():void 0){case"low":u+="; Priority=Low";break;case"medium":u+="; Priority=Medium";break;case"high":u+="; Priority=High";break;default:throw TypeError(`option priority is invalid: ${s.priority}`)}if(s.sameSite)switch("string"==typeof s.sameSite?s.sameSite.toLowerCase():s.sameSite){case!0:case"strict":u+="; SameSite=Strict";break;case"lax":u+="; SameSite=Lax";break;case"none":u+="; SameSite=None";break;default:throw TypeError(`option sameSite is invalid: ${s.sameSite}`)}return u}function p(e,t,r){let s=e.indexOf(";",t);return -1===s?r:s}function f(e,t,r){let s=e.indexOf("=",t);return s<r?s:-1}function g(e,t,r){let s=t,i=r;do{let t=e.charCodeAt(s);if(32!==t&&9!==t)break}while(++s<i)for(;i>s;){let t=e.charCodeAt(i-1);if(32!==t&&9!==t)break;i--}return e.slice(s,i)}function m(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch(t){return e}}},90615,e=>{"use strict";let t,r;var s,i,n,a,o,l,h,c,u,d,p,f,g=e.i(47167);class m extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class y extends m{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class b extends m{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class w extends m{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}(s=h||(h={})).Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2";function v(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&0>t.indexOf(s)&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,s=Object.getOwnPropertySymbols(e);i<s.length;i++)0>t.indexOf(s[i])&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(r[s[i]]=e[s[i]]);return r}"function"==typeof SuppressedError&&SuppressedError;class _{constructor(e,{headers:t={},customFetch:r,region:s=h.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){var t,r,s,i;return t=this,r=arguments,s=void 0,i=function*(e,t={}){var r;let s,i;try{let n,{headers:a,method:o,body:l,signal:h,timeout:c}=t,u={},{region:d}=t;d||(d=this.region);let p=new URL(`${this.url}/${e}`);d&&"any"!==d&&(u["x-region"]=d,p.searchParams.set("forceFunctionRegion",d)),l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?"u">typeof Blob&&l instanceof Blob||l instanceof ArrayBuffer?(u["Content-Type"]="application/octet-stream",n=l):"string"==typeof l?(u["Content-Type"]="text/plain",n=l):"u">typeof FormData&&l instanceof FormData?n=l:(u["Content-Type"]="application/json",n=JSON.stringify(l)):n=!l||"string"==typeof l||"u">typeof Blob&&l instanceof Blob||l instanceof ArrayBuffer||"u">typeof FormData&&l instanceof FormData?l:JSON.stringify(l);let f=h;c&&(i=new AbortController,s=setTimeout(()=>i.abort(),c),h?(f=i.signal,h.addEventListener("abort",()=>i.abort())):f=i.signal);let g=yield this.fetch(p.toString(),{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},u),this.headers),a),body:n,signal:f}).catch(e=>{throw new y(e)}),m=g.headers.get("x-relay-error");if(m&&"true"===m)throw new b(g);if(!g.ok)throw new w(g);let v=(null!=(r=g.headers.get("Content-Type"))?r:"text/plain").split(";")[0].trim();return{data:"application/json"===v?yield g.json():"application/octet-stream"===v||"application/pdf"===v?yield g.blob():"text/event-stream"===v?g:"multipart/form-data"===v?yield g.formData():yield g.text(),error:null,response:g}}catch(e){return{data:null,error:e,response:e instanceof w||e instanceof b?e.context:void 0}}finally{s&&clearTimeout(s)}}
1,new(s||(s=Promise))(function(e,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof s?r:new s(function(e){e(r)})).then(a,o)}l((i=i.apply(t,r||[])).next())})}}var k=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},S=class{constructor(e){var t,r,s;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=null!=(t=e.shouldThrowOnError)&&t,this.signal=e.signal,this.isMaybeSingle=null!=(r=e.isMaybeSingle)&&r,this.urlLengthLimit=null!=(s=e.urlLengthLimit)?s:8e3,e.fetch?this.fetch=e.fetch: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){var r=this;void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let s=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,s=null,i=null,n=e.status,a=e.statusText;if(e.ok){var o,l,h;if("HEAD"!==r.method){let t=await e.text();""===t||(s="text/csv"===r.headers.get("Accept")||r.headers.get("Accept")&&(null==(h=r.headers.get("Accept"))?void 0:h.includes("application/vnd.pgrst.plan+text"))?t:JSON.parse(t))}let c=null==(o=r.headers.get("Prefer"))?void 0:o.match(/count=(exact|planned|estimated)/),u=null==(l=e.headers.get("content-range"))?void 0:l.split("/");c&&u&&u.length>1&&(i=parseInt(u[1])),r.isMaybeSingle&&Array.isArray(s)&&(s.length>1?(t={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,i=null,n=406,a="Not Acceptable"):s=1===s.length?s[0]:null)}else{let i=await e.text();try{t=JSON.parse(i),Array.isArray(t)&&404===e.status&&(s=[],t=null,n=200,a="OK")}catch(r){404===e.status&&""===i?(n=204,a="No Content"):t={message:i}}if(t&&r.shouldThrowOnError)throw new k(t)}return{error:t,data:s,count:i,status:n,statusText:a}});return this.shouldThrowOnError||(s=s.catch(e=>{var t,r,s,i,n,a;let o="",l="",h="",c=null==e?void 0:e.cause;if(c){let t=null!=(r=null==c?void 0:c.message)?r:"",a=null!=(s=null==c?void 0:c.code)?s:"";o=`${null!=(i=null==e?void 0:e.name)?i:"FetchError"}: ${null==e?void 0:e.message} 2 3Caused by: ${null!=(n=null==c?void 0:c.name)?n:"Error"}: ${t}`,a&&(o+=` (${a})`),(null==c?void 0:c.stack)&&(o+=` 4${c.stack}`)}else o=null!=(a=null==e?void 0:e.stack)?a:"";let u=this.url.toString().length;return(null==e?void 0:e.name)==="AbortError"||(null==e?void 0:e.code)==="ABORT_ERR"?(h="",l="Request was aborted (timeout or manual cancellation)",u>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${u} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((null==c?void 0:c.name)==="HeadersOverflowError"||(null==c?void 0:c.code)==="UND_ERR_HEADERS_OVERFLOW")&&(h="",l="HTTP headers exceeded server limits (typically 16KB)",u>this.urlLengthLimit&&(l+=`. Your request URL is ${u} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${null!=(t=null==e?void 0:e.name)?t:"FetchError"}: ${null==e?void 0:e.message}`,details:o,hint:l,code:h},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}},T=class extends S{select(e){let t=!1,r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){let i=void 0===s?"offset":`${s}.offset`,n=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
4explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){var a;let o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!=(a=this.headers.get("Accept"))?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};let E=RegExp("[,()]");var A=class extends T{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&E.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&E.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";"plain"===s?i="pl":"phrase"===s?i="ph":"websearch"===s&&(i="w");let n=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>void 0!==t).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},O=class{constructor(e,{headers:t={},schema:r,fetch:s,urlLengthLimit:i=8e3}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:s}=null!=t?t:{},i=!1,n=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:a,headers:o}=this.cloneRequestState();return a.searchParams.set("select",n),s&&o.append("Prefer",`count=${s}`),new A({method:r?"HEAD":"GET",url:a,headers:o,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(e,{count:t,defaultToNull:r=!0}={}){var s;let{url:i,headers:n}=this.cloneRequestState();if(t&&n.append("Prefer",`count=${t}`),r||n.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>
4e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);i.searchParams.set("columns",e.join(","))}}return new A({method:"POST",url:i,headers:n,schema:this.schema,body:e,fetch:null!=(s=this.fetch)?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var n;let{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&o.append("Prefer",`count=${s}`),i||o.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set("columns",e.join(","))}}return new A({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!=(n=this.fetch)?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(e,{count:t}={}){var r;let{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new A({method:"PATCH",url:s,headers:i,schema:this.schema,body:e,fetch:null!=(r=this.fetch)?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:e}={}){var t;let{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new A({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!=(t=this.fetch)?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function R(e){return(R="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function C(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function j(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?C(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=R(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=R(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==R(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):C(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var P=class e{constructor(e,{headers:t={},schema:r,fetch:s,timeout:i,urlLengthLimit:n=8e3}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.urlLengthLimit=n;const a=null!=s?s:globalThis.fetch;void 0!==i&&i>0?this.fetch=(e,t)=>{let r=new AbortController,s=setTimeout(()=>r.abort(),i),n=null==t?void 0:t.signal;if(n){if(n.aborted)return clearTimeout(s),a(e,t);let i=()=>{clearTimeout(s),r.abort()};return n.addEventListener("abort",i,{once:!0}),a(e,j(j({},t),{},{signal:r.signal})).finally(()=>{clearTimeout(s),n.removeEventListener("abort",i)})}return a(e,j(j({},t),{},{signal:r.signal})).finally(()=>clearTimeout(s))}:this.fetch=a}from(e){if(!e||"string"!=typeof e||""===e.trim())throw Error("Invalid relation name: relation must be a non-empty string.");return new O(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,t={},{head:r=!1,get:s=!1,count:i}={}){var n;let a,o,l=new URL(`${this.url}/rpc/${e}`),h=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(h)),c=r&&Object.values(t).some(h);c?(a="POST",o=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{l.searchParams.append(e,t)})):(a="POST",o=t);let u=new Headers(this.headers);return c?u.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&u.set("Prefer",`count=${i}`),new A({method:a,url:l,headers:u,schema:this.schemaName,body:o,fetch:null!=(n=this.fetch)?n:fetch,urlLengthLimit:this.urlLengthLimit})}};let $=class{static detectEnvironment(){var t;if("u">typeof WebSocket)return{type:"native",constructor:WebSocket};if("u">typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if(void 0!==e.g.WebSocket)return{type:"native",constructor:e.g.WebSocket};if("u">typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("u">typeof globalThis&&globalThis.EdgeRuntime||"u">typeof navigator&&(null==(t=navigator.userAgent)?void 0:t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let e=r.versions;if(e&&e.node){let t=parseInt(e.node.replace(/^v/,"").split(".")[0]);return t>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${t} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${t} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=` 5 6Suggested solution: ${e.workaround}`),Error(t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}},I="2.0.0",x="errored",N="joined",U={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};class L{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){return e.event!==this.BROADCAST_EVENT||e.payload instanceof ArrayBuffer||"string"!=typeof e.payload.event?t(JSON.stringify([e.join_ref,e.ref,e.topic,e.event,e.payload])):t(this._binaryEncodeUserBroadcastPush(e))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null==(t=e.payload)?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;let s=null!=(r=null==(t=e.payload)?void 0:t.payload)?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;let s=null!=(r=null==(t=e.payload)?void 0:t.payload)?r:{},i=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,t,r){let s=e.topic,i=null!=(p=e.ref)?p:"",n=null!=(f=e.join_ref)?f:"",a=e.payload.event,o=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},l=0===Object.keys(o).length?"":JSON.stringify(o);if(n.length>255)throw Error(`joinRef length ${n.length} exceeds maximum of 255`);if(i.length>255)throw Error(`ref length ${i.length} exceeds maximum of 255`);if(s.length>255)throw Error(`topic length ${s.length} exceeds maximum of 255`);if(a.length>255)throw Error(`userEvent length ${a.length} exceeds maximum of 255`);if(l.length>255)throw Error(`metadata length ${l.length} exceeds maximum of 255`);let h=this.USER_BROADCAST_PUSH_META_LENGTH+n.length+i.length+s.length+a.length+l.length,c=new ArrayBuffer(this.HEADER_LENGTH+h),u=new DataView(c),d=0;u.setUint8(d++,this.KINDS.userBroadcastPush),u.setUint8(d++,n.length),u.setUint8(d++,i.length),u.setUint8(d++,s.length),u.setUint8(d++,a.length),u.setUint8(d++,l.length),u.setUint8(d++,t),Array.from(n,e=>u.setUint8(d++,e.charCodeAt(0))),Array.from(i,e=>u.setUint8(d++,e.charCodeAt(0))),Array.from(s,e=>u.setUint8(d++,e.charCodeAt(0))),Array.from(a,e=>u.setUint8(d++,e.charCodeAt(0))),Array.from(l,e=>u.setUint8(d++,e.charCodeAt(0)));var p,f,g=new Uint8Array(c.byteLength+r.byteLength);return g.set(new Uint8Array(c),0),g.set(new Uint8Array(r),c.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if("string"==typeof e){let[r,s,i,n,a]=JSON.parse(e);return t({join_ref:r,ref:s,topic:i,event:n,payload:a})}return t({})}_binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s
6)}_decodeUserBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+4,l=r.decode(e.slice(o,o+s));o+=s;let h=r.decode(e.slice(o,o+i));o+=i;let c=r.decode(e.slice(o,o+n));o+=n;let u=e.slice(o,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:h,payload:d};return n>0&&(p.meta=JSON.parse(c)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||(null==(t=null==e?void 0:e.constructor)?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}(i=c||(c={})).abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange";let D=(e,t,r={})=>{var s;let i=null!=(s=r.skipTypes)?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=B(s,e,t,i),r),{}):{}},B=(e,t,r,s)=>{let i=t.find(t=>t.name===e),n=null==i?void 0:i.type,a=r[e];return n&&!s.includes(n)?q(n,a):H(a)},q=(e,t)=>{if("_"===e.charAt(0))return F(t,e.slice(1,e.length));switch(e){case c.bool:return M(t);case c.float4:case c.float8:case c.int2:case c.int4:case c.int8:case c.numeric:case c.oid:return W(t);case c.json:case c.jsonb:return K(t);case c.timestamp:return J(t);case c.abstime:case c.date:case c.daterange:case c.int4range:case c.int8range:case c.money:case c.reltime:case c.text:case c.time:case c.timestamptz:case c.timetz:case c.tsrange:case c.tstzrange:default:return H(t)}},H=e=>e,M=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},W=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},K=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},F=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s,i=e.slice(1,r);try{s=JSON.parse("["+i+"]")}catch(e){s=i?i.split(","):[]}return s.map(e=>q(t,e))}return e},J=e=>"string"==typeof e?e.replace(" ","T"):e,z=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};var G=e=>"function"==typeof e?e:function(){return e},V="u">typeof window?window:null,Y=("u">typeof self?self:null)||V||globalThis,X="closed",Q="errored",Z="joined",ee="joining",et="leaving",er="phx_close",es="phx_error",ei="phx_reply",en="phx_leave",ea="websocket",eo="base64url.bearer.phx.",el=class{constructor(e,t,r,s){this.channel=e,this.event=t,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:r}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},eh=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},ec=class{constructor(e,t,r){this.state=X,this.topic=e,this.params=G(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new el(this,"phx_join",this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new eh(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Z,this.rejoinTimer.reset(),this.pushBuffer.forEach(e
6=>e.send()),this.pushBuffer=[]}),this.joinPush.receive("error",e=>{this.state=Q,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=X,this.socket.remove(this)}),this.onError(e=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=Q,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new el(this,en,G({}),this.timeout).send(),this.state=Q,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(ei,(e,t)=>{this.trigger(this.replyEventName(t),e)})}join(e=this.timeout){if(!this.joinedOnce)return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush;throw Error("tried to join multiple times. 'join' can only be called a single time per channel instance")}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=X,this.bindings=[]}onClose(e){this.on(er,e)}onError(e){return this.on(es,t=>e(t))}on(e,t){let r=this.bindingRef++;return this.bindings.push({event:e,ref:r,callback:t}),r}off(e,t){this.bindings=this.bindings.filter(r=>r.event!==e||void 0!==t&&t!==r.ref)}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,r=this.timeout){if(t=t||{},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new el(this,e,function(){return t},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=et;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(er,"leave")},r=new el(this,en,G({}),e);return r.receive("ok",()=>t()).receive("timeout",()=>t()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(e,t,r){return t}filterBindings(e,t,r){return!0}isMember(e,t,r,s){return this.topic===e&&(!s||s===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:r,joinRef:s}),!1))}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=ee,this.joinPush.resend(e))}trigger(e,t,r,s){let i=this.onMessage(e,t,r,s);if(t&&!i)throw Error("channel onMessage callbacks must return the payload, modified or unmodified");let n=this.bindings.filter(s=>s.event===e&&this.filterBindings(s,t,r));for(let e=0;e<n.length;e++)n[e].callback(i,r,s||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===X}isErrored(){return this.state===Q}isJoined(){return this.state===Z}isJoining(){return this.state===ee}isLeaving(){return this.state===et}},eu=class{static request(e,t,r,s,i,n,a){if(Y.XDomainRequest){let r=new Y.XDomainRequest;return this.xdomainRequest(r,e,t,s,i,n,a)}if(Y.XMLHttpRequest){let o=new Y.XMLHttpRequest;return this.xhrRequest(o,e,t,r,s,i,n,a)}if(Y.fetch&&Y.AbortController)return this.fetchRequest(e,t,r,s,i,n,a);throw Error("No suitable XMLHttpRequest implementation found")}static fetchRequest(e,t,r,s,i,n,a){let o={method:e,headers:r,body:s},l=null;return i&&(l=new AbortController,setTimeout(()=>l.abort(),i),o.signal=l.signal),Y.fetch(t,o).then(e=>e.text()).then(e=>this.parseJSON(e)).then(e=>a&&a(e)).catch(e=>{"AbortError"===e.name&&n?n():a&&a(null)}),l}static xdomainRequest(e,t,r,s,i,n,a){return e.timeout=i,e.open(t,r),e.onload=()=>{let t=this.parseJSON(e.responseText);a&&a(t)},n&&(e.ontimeout=n),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,r,s,i,n,a,o){for(let[i,a]of(e.open(t,r,!0),e.timeout=n,Object.entries(s)))e.setRequestHeader(i,a);return e.onerror=()=>o&&o(null),e.onreadystatechange=()=>{4===e.readyState&&o&&o(this.parseJSON(e.responseText))},a&&(e.ontimeout=a),e.send(i),e}static parseJSON(e){if(!e||""===e)return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let r=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let i=t?`${t}[${s}]`:s,n=e[s];"object"==typeof n?r.push(this.serialize(n,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(n))}return r.join("&")}static appendParams(e,t){if(0===Object.keys(t).length)return e;let r=e.match(/\?/)?"&":"?";return`${e}${r}${this.serialize(t)}`}}
6,ed=class{constructor(e,t){t&&2===t.length&&t[1].startsWith(eo)&&(this.authToken=atob(t[1].slice(eo.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=0,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(RegExp("(.*)/"+ea),"$1/longpoll")}endpointURL(){return eu.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=0}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return 1===this.readyState||0===this.readyState}poll(){let e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:r,messages:s}=e;if(410===t&&null!==this.token){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=r}else t=0;switch(t){case 200:s.forEach(e=>{setTimeout(()=>this.onmessage({data:e}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=1,this.onopen({}),this.poll();break;
6case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw Error(`unhandled poll status ${t}`)}})}send(e){"string"!=typeof e&&(e=(e=>{let t="",r=new Uint8Array(e),s=r.byteLength;for(let e=0;e<s;e++)t+=String.fromCharCode(r[e]);return btoa(t)})(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join("\n"),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,e&&200===e.status?this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]):(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1))})}close(e,t,r){for(let e of this.reqs)e.abort();this.readyState=3;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,"u">typeof CloseEvent?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,r,s,i){let n,a=()=>{this.reqs.delete(n),s()};n=eu.request(e,this.endpointURL(),t,r,this.timeout,a,e=>{this.reqs.delete(n),this.isActive()&&i(e)}),this.reqs.add(n)}},ep=class e{constructor(t,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,t=>{let{onJoin:r,onLeave:s,onSync:i}=this.caller;this.joinRef=this.channel.joinRef(),this.state=e.syncState(this.state,t,r,s),this.pendingDiffs.forEach(t=>{this.state=e.syncDiff(this.state,t,r,s)}),this.pendingDiffs=[],i()}),this.channel.on(s.diff,t=>{let{onJoin:r,onLeave:s,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,r,s),i())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(t){return e.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,t,r,s){let i=this.clone(e),n={},a={};return this.map(i,(e,r)=>{t[e]||(a[e]=r)}),this.map(t,(e,t)=>{let r=i[e];if(r){let s=t.metas.map(e=>e.phx_ref),i=r.metas.map(e=>e.phx_ref),o=t.metas.filter(e=>0>i.indexOf(e.phx_ref)),l=r.metas.filter(e=>0>s.indexOf(e.phx_ref));o.length>0&&(n[e]=t,n[e].metas=o),l.length>0&&(a[e]=this.clone(r),a[e].metas=l)}else n[e]=t}),this.syncDiff(i,{joins:n,leaves:a},r,s)}static syncDiff(e,t,r,s){let{joins:i,leaves:n}=this.clone(t);return r||(r=function(){}),s||(s=function(){}),this.map(i,(t,s)=>{let i=e[t];if(e[t]=this.clone(s),i){let r=e[t].metas.map(e=>e.phx_ref),s=i.metas.filter(e=>0>r.indexOf(e.phx_ref));e[t].metas.unshift(...s)}r(t,i,s)}),this.map(n,(t,r)=>{let i=e[t];if(!i)return;let n=r.metas.map(e=>e.phx_ref);i.metas=i.metas.filter(e=>0>n.indexOf(e.phx_ref)),s(t,i,r),0===i.metas.length&&delete e[t]}),e}static list(e,t){return t||(t=function(e,t){return t}),this.map(e,(e,r)=>t(e,r))}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static clone(e){return JSON.parse(JSON.stringify(e))}},ef={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){return e.payload.constructor===ArrayBuffer?t(this.binaryEncode(e)):t(JSON.stringify([e.join_ref,e.ref,e.topic,e.event,e.payload]))},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[r,s,i,n,a]=JSON.parse(e);return t({join_ref:r,ref:s,topic:i,event:n,payload:a})}},binaryEncode(e){let{join_ref:t,ref:r,event:s,topic:i,payload:n}=e,a=this.META_LENGTH+t.length+r.length+i.length+s.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),l=new DataView(o),h=0;l.setUint8(h++,this.KINDS.push),l.setUint8(h++,t.length),l.setUint8(h++,r.length),l.setUint8(h++,i.length),l.setUint8(h++,s.length),Array.from(t,e=>l.setUint8(h++,e.charCodeAt(0))),Array.from(r,e=>l.setUint8(h++,e.charCodeAt(0))),Array.from(i,e=>l.setUint8(h++,e.charCodeAt(0))),Array.from(s,e=>l.setUint8(h++,e.charCodeAt(0)));var c=new Uint8Array(o.byteLength+n.byteLength);return c.set(new Uint8Array(o),0),c.set(new Uint8Array(n),o.byteLength),c.buffer},binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(e,t,s);case this.KINDS.reply:return this.decodeReply(e,t,s);
6case this.KINDS.broadcast:return this.decodeBroadcast(e,t,s)}},decodePush(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=t.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(e.slice(a,a+s));a+=s;let l=r.decode(e.slice(a,a+i));a+=i;let h=r.decode(e.slice(a,a+n));return a+=n,{join_ref:o,ref:null,topic:l,event:h,payload:e.slice(a,e.byteLength)}},decodeReply(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(e.slice(o,o+s));o+=s;let h=r.decode(e.slice(o,o+i));o+=i;let c=r.decode(e.slice(o,o+n));o+=n;let u=r.decode(e.slice(o,o+a));return o+=a,{join_ref:l,ref:h,topic:c,event:ei,payload:{status:u,response:e.slice(o,e.byteLength)}}},decodeBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=this.HEADER_LENGTH+2,a=r.decode(e.slice(n,n+s));n+=s;let o=r.decode(e.slice(n,n+i));return n+=i,{join_ref:null,ref:null,topic:a,event:o,payload:e.slice(n,e.byteLength)}}},eg=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||1e4,this.transport=t.transport||Y.WebSocket||ed,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||Y&&Y.sessionStorage,this.establishedConnections=0,this.defaultEncoder=ef.encode.bind(ef),this.defaultDecoder=ef.decode.bind(ef),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==ed?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;V&&V.addEventListener&&(V.addEventListener("pagehide",e=>{this.conn&&(this.disconnect(),r=this.connectClock)}),V.addEventListener("pageshow",e=>{r===this.connectClock&&(r=null,this.connect())}),V.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this.pageHidden=!0:(this.pageHidden=!1,this.isConnected()||this.closeWasClean||this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,r)=>{console.log(`${e}: ${t}`,r)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=G(t.params||{}),this.endPoint=`${e}/${ea}`,this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new eh(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return ed}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=eu.appendParams(eu.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==e.charAt(0)?e:"/"===e.charAt(1)?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,r)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=G(e)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==ed?this.connectWithF
6allback(ed,this.longPollFallbackMs):this.transportConnect())}log(e,t,r){this.logger&&this.logger(e,t,r)}hasLogger(){return null!==this.logger}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let s=this.onMessage(i=>{i.ref===t&&(this.off([s]),e(Date.now()-r))});return!0}transportName(e){return e===ed?"LongPoll":e.name}transportConnect(){let e;this.connectClock++,this.closeWasClean=!1,this.authToken&&(e=["phoenix",`${eo}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){let r,s;clearTimeout(this.fallbackTimer);let i=!1,n=!0,a=this.transportName(e),o=t=>{this.log("transport",`falling back to ${a}...`,t),this.off([r,s]),n=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,t),s=this.onError(e=>{this.log("transport","error",e),n&&!i&&(clearTimeout(this.fallbackTimer),o(e))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(i=!0,!n){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t}`,"true"),this.log("transport",`established ${t} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,t),this.ping(e=>{this.log("transport","connected to primary after",e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),1e3,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,r){if(!this.conn)return e&&e();let s=this.conn;this.waitForBufferDone(s,()=>{t?s.close(t,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,r=1){5!==r&&e.bufferedAmount?setTimeout(()=>{this.waitForBufferDone(e,t,r+1)},150*r):t()}waitForSocketClosed(e,t,r=1){5===r||3===e.readyState?t():setTimeout(()=>{this.waitForSocketClosed(e,t,r+1)},150*r)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport",e);let t=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",e,t,r),(t===this.transport||r>0)&&this.triggerChanError()}
6triggerChanError(){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(es)})}connectionState(){switch(this.conn&&this.conn.readyState){case 0:return"connecting";case 1:return"open";case 2:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([t])=>-1===e.indexOf(t))}channel(e,t={}){let r=new ec(e,t,this);return this.channels.push(r),r}push(e){if(this.hasLogger()){let{topic:t,event:r,payload:s,ref:i,join_ref:n}=e;this.log("push",`${t} ${r} (${n}, ${i})`,s)}this.isConnected()?this.encode(e,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(e,e=>this.conn.send(e)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef)return void this.heartbeatTimeout();this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:r,payload:s,ref:i,join_ref:n}=e;if(i&&i===this.pendingHeartbeatRef){let e=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback("ok"===s.status?"ok":"error",e)}catch(e){this.log("error","error in heartbeat callback",e)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${s.status||""} ${t} ${r} ${i&&"("+i+")"||""}`.trim(),s);for(let e=0;e<this.channels.length;e++){let a=this.channels[e];a.isMember(t,r,s,n)&&a.trigger(r,s,i,n)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([r,s])=>{try{s(...t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t.isJoined()||t.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};class em{constructor(e,t){const r=function(e){return(null==e?void 0:e.events)&&{events:e.events}}(t);this.presence=new ep(e.getChannel(),r),this.presence.onJoin((t,r,s)=>{let i=em.onJoinPayload(t,r,s);e.getChannel().trigger("presence",i)}),this.presence.onLeave((t,r,s)=>{let i=em.onLeavePayload(t,r,s);e.getChannel().trigger("presence",i)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return em.transformState(this.presence.state)}static transformState(e){return Object.getOwnPropertyNames(e=JSON.parse(JSON.stringify(e))).reduce((t,r)=>{let s=e[r];return t[r]=ey(s),t},{})}static onJoinPayload(e,t,r){return{event:"join",key:e,currentPresences:eb(t),newPresences:ey(r)}}static onLeavePayload(e,t,r){return{event:"leave",key:e,currentPresences:eb(t),leftPresences:ey(r)}}}function ey(e){return e.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function eb(e){return(null==e?void 0:e.metas)?ey(e):[]}(n=u||(u={})).SYNC="sync",n.JOIN="join",n.LEAVE="leave";class ew{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new em(this.channel.channelAdapter,t)}}class ev{constructor(e,t,r){const s=function(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}(r);this.channel=e.getSocket().channel(t,s),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,t){return this.channel.on(e,t)}off(e,t){this.channel.off(e,t)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,t,r){let s;try{s=this.channel.push(e,t,r)}catch(t){throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>100){let e=this.channel.pushBuffer.shift();e.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload())}return s}updateJoinPayload(e){let t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===N}isJoined(){return this.state===N}isJoining(){return"joining"===this.state}isClosed(){return"closed"===this.state}isLeaving(){return"leaving"===this.state}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}(a=d||(d={})).ALL="*",a.INSERT="INSERT",a.UPDATE="UPDATE",a.DELETE="DELETE",(o=p||(p={})).BROADCAST="broadcast",o.PRESENCE="presence",o.POSTGRES_CHANGES="postgres_changes",o.SYSTEM="system",(l=f||(f={})).SUBSCRIBED="SUBSCRIBED",l.TIMED_OUT="TIMED_OUT",l.CLOSED="CLOSED",l.CHANNEL_ERROR="CHANNEL_ERROR";class e_{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,t={config:{}},r){var s,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.channelAdapter=new ev(this.socket.socketAdapter,e,this.params),this.presence=new ew(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=z(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(null==(i=null==(s=this.params.config)?void 0:s.broadcast)?void 0:i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,s,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:n,presence:a,private:o}}=this.params,l=null!=(s=null==(r=this.bindings.postgres_changes)?void 0:r.map(e=>e.filter))?s:[],h=!!this.bindings[p.PRESENCE]&&this.bindings[p.PRESENCE].length>0||(null==(i=this.params.config.presence)?void 0:i.enabled)===!0,c={},u={broadcast:n,presence:Object.assign(Object.assign({},a),{enabled:h}),postgres_changes:l,private:o};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this._onError(t=>{null==e||e(f.CHANNEL_ERROR,t)}),this._onClose(()=>null==e?void 0:e(f.CLOSED)),this.updateJoinPayload(Object.assign({config:u},c)),this._updateFilterMessage(),this.channelAdapter.subscribe(t).receive("ok",async({postgres_changes:t})=>{if(this.socket._isManualToken()||this.socket.setAuth(),void 0===t){null==e||e(f.SUBSCRIBED);return}this._updatePostgresBindings(t,e)}).receive("error",t=>{this.state=x,null==e||e(f.CHANNEL_ERROR,Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(f.TIMED_OUT)})}return this}_updatePostgresBindings(e,t){var r;let s=this.bindings.postgres_changes,i=null!=(r=null==s?void 0:s.length)?r:0,n=[];for(let r=0;r<i;r++){let i=s[r],{filter:{event:a,schema:o,table:l,filter:h}}=i,c=e&&e[r];
6if(c&&c.event===a&&e_.isFilterValueEqual(c.schema,o)&&e_.isFilterValueEqual(c.table,l)&&e_.isFilterValueEqual(c.filter,h))n.push(Object.assign(Object.assign({},i),{id:c.id}));else{this.unsubscribe(),this.state=x,null==t||t(f.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=n,this.state!=x&&t&&t(f.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){let s=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===p.PRESENCE||e===p.POSTGRES_CHANGES;if(s&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,t,r)}async httpSend(e,t,r={}){var s;if(null==t)return Promise.reject("Payload is required for httpSend()");let i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let n={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,n,null!=(s=r.timeout)?s:this.timeout);if(202===a.status)return{success:!0};let o=a.statusText;try{let e=await a.json();o=e.error||e.message||o}catch(e){}return Promise.reject(Error(o))}async send(e,t={}){var r,s;if(this.channelAdapter.canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,i,n;let a=this.channelAdapter.push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null==(n=null==(i=null==(s=this.params)?void 0:s.config)?void 0:i.broadcast)?void 0:n.ack)||r("ok"),a.receive("ok",()=>r("ok")),a.receive("error",()=>r("error")),a.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated
6in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:n}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:n,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!=(r=t.timeout)?r:this.timeout);return await (null==(s=e.body)?void 0:s.cancel()),e.ok?"ok":"error"}catch(e){if("AbortError"===e.name)return"timed out";return"error"}}}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(t=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>t("ok")).receive("timeout",()=>t("timed out")).receive("error",()=>t("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,t,r){let s=new AbortController,i=setTimeout(()=>s.abort(),r),n=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),n}_on(e,t,r){let s=e.toLocaleLowerCase(),i=this.channelAdapter.on(e,r),n={type:s,filter:t,callback:r,ref:i};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,t,r)=>{var s,i,n,a,o,l,h;let c=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(c,r))return!1;let u=null==(s=this.bindings[c])?void 0:s.find(t=>t.ref===e.ref);if(!u)return!0;if(!["broadcast","presence","postgres_changes"].includes(c))return u.type.toLocaleLowerCase()===c;if("id"in u){let e=u.id,r=null==(i=u.filter)?void 0:i.event;return e&&(null==(n=t.ids)?void 0:n.includes(e))&&("*"===r||(null==r?void 0:r.toLocaleLowerCase())===(null==(a=t.data)?void 0:a.type.toLocaleLowerCase()))}{let e=null==(l=null==(o=null==u?void 0:u.filter)?void 0:o.event)?void 0:l.toLocaleLowerCase();return"*"===e||e===(null==(h=null==t?void 0:t.event)?void 0:h.toLocaleLowerCase())}})}_notThisChannelEvent(e,t){let{close:r,error:s,leave:i,join:n}=U;return t&&[r,s,i,n].includes(e)&&t!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,t,r)=>{if("object"==typeof t&&"ids"in t){let e=t.data,{schema:r,table:s,commit_timestamp:i,type:n,errors:a}=e;return Object.assign(Object.assign({},{schema:r,table:s,commit_timestamp:i,eventType:n,new:{},old:{},errors:a}),this._getPayloadRecords(e))}return t})}copyBindings(e){if(this.joinedOnce)throw Error("cannot copy bindings into joined channel");for(let t in e.bindings)for(let r of e.bindings[t])this._on(r.type,r.filter,r.callback)}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=D(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=D(e.columns,e.old_record)),t}}class ek{constructor(e,t){this.socket=new eg(e,t)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,t,r,s=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),s),this.socket.disconnect(()=>{e(),i("ok")},t,r)})}push(e){this.socket.push(e)}log(e,t,r){this.socket.log(e,t,r)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return"connecting"==this.socket.connectionState()}isDisconnecting(){return"closing"==this.socket.connectionState()}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}let eS=[1e3,2e3,5e3,1e4],eT=` 7 addEventListener("message", (e) => { 8 if (e.data.event === "start") { 9 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 10 } 11 });`;class eE{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,t){var r;if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={}
11,this.ref=0,this.serializer=new L,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null==(r=null==t?void 0:t.params)?void 0:r.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey;const s=this._initializeOptions(t);this.socketAdapter=new ek(e,s),this.httpEndpoint=z(e),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(t){let e=t.message;if(e.includes("Node.js"))throw Error(`${e} 12 13To use Realtime in Node.js, you need to provide a WebSocket implementation: 14 15Option 1: Use Node.js 22+ which has native WebSocket support 16Option 2: Install and provide the "ws" package: 17 18 npm install ws 19 20 import ws from "ws" 21 const client = new RealtimeClient(url, { 22 ...options, 23 transport: ws 24 })`);throw Error(`WebSocket not available: ${e}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,t)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return"ok"===t&&e.teardown(),0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){let e=this.channels.map(async e=>{let t=await e.unsubscribe();return e.teardown(),t}),t=await Promise.all(e);return this.disconnect(),t}log(e,t,r){this.socketAdapter.log(e,t,r)}connectionState(){return this.socketAdapter.connectionState()||"closed"}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,t={config:{}}){let r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{let r=new e_(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{let r={access_token:t,version:"realtime-js/2.101.1"};t&&e.updateJoinPayload(r),e.joinedOnce&&e.channelAdapter.isJoined()&&e.channelAdapter.push(U.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(e=>{this.log("error","error waiting for auth on connect",e)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(t,r)=>{"sent"==t&&this._setAuthSafely(),e&&e(t,r)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([eT],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_initializeOptions(e){var t,r,s,i,n,a,o,l,h;let c,u;this.worker=null!=(t=null==e?void 0:e.worker)&&t,this.accessToken=null!=(r=null==e?void 0:e.accessToken)?r:null;let d={};d.timeout=null!=(s=null==e?void 0:e.timeout)?s:1e4,d.heartbeatIntervalMs=null!=(i=null==e?void 0:e.heartbeatIntervalMs)?i:25e3,d.transport=null!=(n=null==e?void 0:e.transport)?n:$.getWebSocketConstructor(),d.params=null==e?void 0:e.params,d.logger=null==e?void 0:e.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(null==e?void 0:e.heartbeatCallback),d.reconnectAfterMs=null!=(a=null==e?void 0:e.reconnectAfterMs)?a:e=>eS[e-1]||1e4;let p=null!=(o=null==e?void 0:e.vsn)?o:I;switch(p){case"1.0.0":c=(e,t)=>t(JSON.stringify(e)),u=(e,t)=>
24t(JSON.parse(e));break;case I:c=this.serializer.encode.bind(this.serializer),u=this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=p,d.encode=null!=(l=null==e?void 0:e.encode)?l:c,d.decode=null!=(h=null==e?void 0:e.decode)?h:u,d.beforeReconnect=this._reconnectAuth.bind(this),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if("u">typeof window&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var eA=e.i(67034),eO=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&t.icebergType?.includes("CommitState")===!0}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};async function eR(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}function eC(e){return e.join("\x1f")}var ej=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:eC(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){let r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${eC(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${eC(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${eC(e.namespace)}`}),!0}catch(e){if(e instanceof eO&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof eO&&409===e.status)return;throw e}}};function eP(e){return e.join("\x1f")}var e$=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${eP(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${eP(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${eP(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${eP(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${eP(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${eP(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof eO&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof eO&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},eI=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=function(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:i,body:n,headers:a}){let o=function(e,t,r){let s=new URL(t,e);if(r)for(let[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,s,i),l=await eR(e.auth),h=await t(o,{method:r,headers:{...n?{"Content-Type":"application/json"}:{},...l,...a},body:n?JSON.stringify(n):void 0}),c=await h.text(),u=(h.headers.get("content-type")||"").includes("application/json"),d=u&&c?JSON.parse(c):c;if(!h.ok){let e=u?d:void 0,t=e?.error;throw new eO(t?.message??`Request failed with status ${h.status}`,{status:h.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:h.status,headers:h.headers,data:d}}}}({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new ej(this.client,t),this.tableOps=new e$(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}
24async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},ex=class extends Error{constructor(e,t="storage",r,s){super(e),this.__isStorageError=!0,this.namespace=t,this.name="vectors"===t?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function eN(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var eU=class extends ex{constructor(e,t,r,s="storage"){super(e,s,t,r),this.name="vectors"===s?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},eL=class extends ex{constructor(e,t,r="storage"){super(e,r),this.name="vectors"===r?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};let eD=e=>{if(Array.isArray(e))return e.map(e=>eD(e));if("function"==typeof e||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([e,r])=>{t[e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""))]=eD(r)}),t};function eB(e){return(eB="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function eq(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function eH(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?eq(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=eB(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=eB(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==eB(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):eq(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}let eM=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null==(t=e.error)?void 0:t.message)||JSON.stringify(e)},eW=async(e,t,r,s)=>{if(null!==e&&"object"==typeof e&&"function"==typeof e.json){let r=parseInt(e.status,10);Number.isFinite(r)||(r=500),e.json().then(e=>{let i=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new eU(eM(e),r,i,s))}).catch(()=>{let i=r+"";t(new eU(e.statusText||`HTTP ${r} error`,r,i,s))})}else t(new eL(eM(e),e,s))};async function eK(e,t,r,s,i,n,a){return new Promise((o,l)=>{let h;e(r,(h={method:t,headers:(null==s?void 0:s.headers)||{}},"GET"===t||"HEAD"===t||!n||((e=>{if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)})(n)?(h.headers=eH({"Content-Type":"application/json"},null==s?void 0:s.headers),h.body=JSON.stringify(n)):h.body=n,(null==s?void 0:s.duplex)&&(h.duplex=s.duplex)),eH(eH({},h),i))).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;if("vectors"===a){let t=e.headers.get("content-type");if("0"===e.headers.get("content-length")||204===e.status||!t||!t.includes("application/json"))return{}}return e.json()}).then(e=>o(e)).catch(e=>eW(e,l,s,a))})}function eF(e="storage"){return{get:async(t,r,s,i)=>eK(t,"GET",r,s,i,void 0,e),post:async(t,r,s,i,n)=>eK(t,"POST",r,i,n,s,e),put:async(t,r,s,i,n)=>eK(t,"PUT",r,i,n,s,e),head:async(t,r,s,i)=>eK(t,"HEAD",r,eH(eH({},s),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,r,s,i,n)=>eK(t,"DELETE",r,i,n,s,e)}}let{get:eJ,post:ez,put:eG,head:eV,remove:eY}=eF("storage"),eX=eF("vectors");var eQ=class{constructor(e,t={},r,s="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=eH(eH({},this.headers),{},{[e]:t}),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eN(e))return{data:null,error:e};throw e}}},eZ=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eN(e))return{data:null,error:e};throw e}}};
24t=Symbol.toStringTag;var e0=class{constructor(e,r){this.downloadFn=e,this.shouldThrowOnError=r,this[t]="BlobDownloadBuilder",this.promise=null}asStream(){return new eZ(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await (await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eN(e))return{data:null,error:e};throw e}}};let e1={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},e2={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var e8=class extends eQ{constructor(e,t={},r,s){super(e,t,s,"storage"),this.bucketId=r}async uploadOrUpdate(e,t,r,s){var i=this;return i.handleOperation(async()=>{let n,a=eH(eH({},e2),s),o=eH(eH({},i.headers),"POST"===e&&{"x-upsert":String(a.upsert)}),l=a.metadata;"u">typeof Blob&&r instanceof Blob?((n=new FormData).append("cacheControl",a.cacheControl),l&&n.append("metadata",i.encodeMetadata(l)),n.append("",r)):"u">typeof FormData&&r instanceof FormData?((n=r).has("cacheControl")||n.append("cacheControl",a.cacheControl),l&&!n.has("metadata")&&n.append("metadata",i.encodeMetadata(l))):(n=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=i.toBase64(i.encodeMetadata(l))),("u">typeof ReadableStream&&n instanceof ReadableStream||n&&"object"==typeof n&&"pipe"in n&&"function"==typeof n.pipe)&&!a.duplex&&(a.duplex="half")),(null==s?void 0:s.headers)&&(o=eH(eH({},o),s.headers));let h=i._removeEmptyFolders(t),c=i._getFinalPath(h),u=await ("PUT"==e?eG:ez)(i.fetch,`${i.url}/object/${c}`,n,eH({headers:o},(null==a?void 0:a.duplex)?{duplex:a.duplex}:{}));return{path:h,id:u.Id,fullPath:u.Key}})}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var i=this;let n=i._removeEmptyFolders(e),a=i._getFinalPath(n),o=new URL(i.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",t),i.handleOperation(async()=>{let e,t=eH(eH({},e2),s),a=eH(eH({},i.headers),{"x-upsert":String(t.upsert)});return"u">typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),e.append("",r)):"u">typeof FormData&&r instanceof FormData?(e=r).append("cacheControl",t.cacheControl):(e=r,a["cache-control"]=`max-age=${t.cacheControl}`,a["content-type"]=t.contentType),{path:n,fullPath:(await eG(i.fetch,o.toString(),e,{headers:a})).Key}})}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(e),i=eH({},r.headers);(null==t?void 0:t.upsert)&&(i["x-upsert"]="true");let n=await ez(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:i}),a=new URL(r.url+n.url),o=a.searchParams.get("token");if(!o)throw new ex("No token returned by API");return{signedUrl:a.toString(),path:e,token:o}})}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;return s.handleOperation(async()=>await ez(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,de
24stinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers}))}async copy(e,t,r){var s=this;return s.handleOperation(async()=>({path:(await ez(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(e,t,r){var s=this;return s.handleOperation(async()=>{let i=s._getFinalPath(e),n="object"==typeof(null==r?void 0:r.transform)&&null!==r.transform&&Object.keys(r.transform).length>0,a=await ez(s.fetch,`${s.url}/object/sign/${i}`,eH({expiresIn:t},n?{transform:r.transform}:{}),{headers:s.headers}),o=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"",l=n&&a.signedURL.includes("/object/sign/")?a.signedURL.replace("/object/sign/","/render/image/sign/"):a.signedURL;return{signedUrl:encodeURI(`${s.url}${l}${o}`)}})}async createSignedUrls(e,t,r){var s=this;return s.handleOperation(async()=>{let i=await ez(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),n=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return i.map(e=>eH(eH({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${n}`):null}))})}download(e,t,r){let s=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",i=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),n=i?`?${i}`:"",a=this._getFinalPath(e);return new e0(()=>eJ(this.fetch,`${this.url}/${s}/${a}${n}`,{headers:this.headers,noResolveJson:!0},r),this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);return t.handleOperation(async()=>eD(await eJ(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})))}async exists(e){var t;let r=this._getFinalPath(e);try{return await eV(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eN(e)){let r=e instanceof eU?e.status:e instanceof eL?null==(t=e.originalError)?void 0:t.status:void 0;if(void 0!==r&&[400,404].includes(r))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let r=this._getFinalPath(e),s=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&s.push(i);let n=void 0!==(null==t?void 0:t.transform)?"render/image":"object",a=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==a&&s.push(a);let o=s.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${r}${o}`)}}}async remove(e){var t=this;return t.handleOperation(async()=>await eY(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,r){var s=this;return s.handleOperation(async()=>{let i=eH(eH(eH({},e1),t),{},{prefix:e||""});return await ez(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(e,t){var r=this;return r.handleOperation(async()=>{let s=eH({},e);return await ez(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return void 0!==eA.Buffer?eA.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("&")}};let e5={"X-Client-Info":"storage-js/2.101.1"};var e6=class extends eQ{constructor(e,t={},r,s){const i=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),super(i.href.replace(/\/$/,""),eH(eH({},e5),t),r,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await eJ(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await eJ(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation(async()=>await ez(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async updateBucket(e,t){var r=this;return r.handleOperation(async()=>await eG(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await ez(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await eY(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},e3=class extends eQ{constructor(e,t={},r){super(e.replace(/\/$/,""),eH(eH({},e5),t),r,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await ez(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=new URLSearchParams;(null==e?void 0:e.limit)!==void 0&&r.set("limit",e.limit.toString()),(null==e?void 0:e.offset)!==void 0&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);let s=r.toString(),i=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return await eJ(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await eY(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!(!(!e||"string"!=typeof e||0===e.length||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\"))&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e)))throw new ex("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new eI({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){let r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}}})}},e4=class extends eQ{constructor(e,t={},r){super(e.replace(/\/$/,""),eH(eH({},e5),{},{"Content-Type":"application/json"},t),r,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await eX.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await eX.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}},e9=class extends eQ{constructor(e,t={},r){super(e.replace(/\/$/,""),eH(eH({},e5),{},{"Content-Type":"application/json"},t),r,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");
24if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},e7=class extends eQ{constructor(e,t={},r){super(e.replace(/\/$/,""),eH(eH({},e5),{},{"Content-Type":"application/json"},t),r,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await eX.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},te=class extends e7{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new tt(this.url,this.headers,e,this.fetch)}async createBucket(e){return super.createBucket.call(this,e)}async getBucket(e){return super.getBucket.call(this,e)}async listBuckets(e={}){return super.listBuckets.call(this,e)}async deleteBucket(e){return super.deleteBucket.call(this,e)}},tt=class extends e4{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return super.createIndex.call(this,eH(eH({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return super.listIndexes.call(this,eH(eH({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return super.getIndex.call(this,this.vectorBucketName,e)}async deleteIndex(e){return super.deleteIndex.call(this,this.vectorBucketName,e)}index(e){return new tr(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},tr=class extends e9{constructor(e,t,r,s,i){super(e,t,i),this.vectorBucketName=r,this.indexName=s}async putVectors(e){return super.putVectors.call(this,eH(eH({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async getVectors(e){return super.getVectors.call(this,eH(eH({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async listVectors(e={}){return super.listVectors.call(this,eH(eH({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async queryVectors(e){return super.queryVectors.call(this,eH(eH({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async deleteVectors(e){return super.deleteVectors.call(this,eH(eH({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}},ts=class extends e6{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new e8(this.url,this.headers,e,this.fetch)}get vectors(){return new te(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new e3(this.url+"/iceberg",this.headers,this.fetch)}};let ti="2.101.1",tn={"X-Client-Info":`gotrue-js/${ti}`},ta="X-Supabase-Api-Version",to={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},tl=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;
24class th extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function tc(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class tu extends th{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class td extends th{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class tp extends th{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class tf extends tp{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function tg(e){return tc(e)&&"AuthSessionMissingError"===e.name}class tm extends tp{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ty extends tp{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class tb extends tp{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}}}class tw extends tp{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}}}class tv extends tp{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class t_ extends tp{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function tk(e){return tc(e)&&"AuthRetryableFetchError"===e.name}class tS extends tp{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class tT extends tp{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}let tE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),tA=" \n\r=".split(""),tO=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<tA.length;t+=1)e[tA[t].charCodeAt(0)]=-2;for(let t=0;t<tE.length;t+=1)e[tE[t].charCodeAt(0)]=t;return e})();function tR(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)r(tE[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)r(tE[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function tC(e,t,r){let s=tO[e];if(s>-1)for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(-2===s)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function tj(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return r(e);for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t<e.length;t+=1)tC(e.charCodeAt(t),i,n);return t.join("")}function tP(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)tC(e.charCodeAt(t),r,s);return new Uint8Array(t)}function t$(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>tR(e,r,s)),tR(null,r,s),t.join("")}let tI=()=>"u">typeof window&&"u">typeof document,tx={tested:!1,writable:!1},tN=()=>{if(!tI())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(tx.tested)return tx.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),tx.tested=!0,tx.writable=!0}catch(e){tx.tested=!0,tx.writable=!1}return tx.writable},tU=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),tL=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},tD=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},tB=async(e,t)=>{await e.removeItem(t)};class tq{constructor(){this.promise=new tq.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function tH(e){let t=e.split(".");if(3!==t.length)throw new tT("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!tl.test(t[e]))throw new tT("JWT not in base64url format");return{header:JSON.parse(tj(t[0])),payload:JSON.parse(tj(t[1])),signature:tP(t[2]),raw:{header:t[0],payload:t[1]}}}async function tM(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function tW(e){return("0"+e.toString(16)).substr(-2)}async function tK(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>String.fromCharCode(e)).join("")}async function tF(e){return"u">typeof crypto&&void 0!==crypto.subtle&&"u">typeof TextEncoder?btoa(await tK(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):(console.warn("WebCrypto API is not supported. Code
24challenge method will default to use plain instead of sha256."),e)}async function tJ(e,t,r=!1){let s=function(){let e=new Uint32Array(56);if("u"<typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,tW).join("")}(),i=s;r&&(i+="/PASSWORD_RECOVERY"),await tL(e,`${t}-code-verifier`,i);let n=await tF(s),a=s===n?"plain":"s256";return[n,a]}tq.promiseConstructor=Promise;let tz=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,tG=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function tV(e){if(!tG.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function tY(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){let e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function tX(e){return JSON.parse(JSON.stringify(e))}let tQ=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),tZ=[502,503,504];async function t0(e){var t;let r,s;if(!("object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json))throw new t_(tQ(e),0);if(tZ.includes(e.status))throw new t_(tQ(e),e.status);try{r=await e.json()}catch(e){throw new td(tQ(e),e)}let i=function(e){let t=e.headers.get(ta);if(!t||!t.match(tz))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=to["2024-01-01"].timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?s=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(s=r.error_code),s){if("weak_password"===s)throw new tS(tQ(r),e.status,(null==(t=r.weak_password)?void 0:t.reasons)||[]);else if("session_not_found"===s)throw new tf}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new tS(tQ(r),e.status,r.weak_password.reasons);throw new tu(tQ(r),e.status||500,s)}async function t1(e,t,r,s){var i;let n=Object.assign({},null==s?void 0:s.headers);n[ta]||(n[ta]=to["2024-01-01"].name),(null==s?void 0:s.jwt)&&(n.Authorization=`Bearer ${s.jwt}`);let a=null!=(i=null==s?void 0:s.query)?i:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);let o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await t2(e,t,r+o,{headers:n,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(l):{data:Object.assign({},l),error:null}}async function t2(e,t,r,s,i,n){let a,o,l=(o={method:t,headers:(null==s?void 0:s.headers)||{}},"GET"===t?o:(o.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==s?void 0:s.headers),o.body=JSON.stringify(n),Object.assign(Object.assign({},o),i)));try{a=await e(r,Object.assign({},l))}catch(e){throw console.error(e),new t_(tQ(e),0)}if(a.ok||await t0(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await t0(e)}}function t8(e){var t,r,s;let i=null;(s=e).access_token&&s.refresh_token&&s.expires_in&&(i=Object.assign({},e),e.expires_at||(i.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)));return{data:{session:i,user:null!=(t=e.user)?t:e},error:null}}function t5(e){let t=t8(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>
24e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function t6(e){var t;return{data:{user:null!=(t=e.user)?t:e},error:null}}function t3(e){return{data:e,error:null}}function t4(e){let{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n}=e;return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n},user:Object.assign({},v(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function t9(e){return e}let t7=["global","local","others"];class re{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=tU(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,t=t7[0]){if(0>t7.indexOf(t))throw Error(`@supabase/auth-js: Parameter scope must be one of ${t7.join(", ")}`);try{return await t1(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tc(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await t1(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:t6})}catch(e){if(tc(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=v(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await t1(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:t4,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(tc(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await t1(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:t6})}catch(e){if(tc(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},h=await t1(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(r=null==(t=null==e?void 0:e.page)?void 0:t.toString())?r:"",per_page:null!=(i=null==(s=null==e?void 0:e.perPage)?void 0:s.toString())?i:""},xform:t9});if(h.error)throw h.error;let c=await h.json(),u=null!=(n=h.headers.get("x-total-count"))?n:0,d=null!=(o=null==(a=h.headers.get("link"))?void 0:a.split(","))?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},c),l),error:null}}catch(e){if(tc(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){tV(e);try{return await t1(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:t6})}catch(e){if(tc(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){tV(e);try{return await t1(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:t6})}catch(e){if(tc(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){tV(e);try{return await t1(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:t6})}catch(e){if(tc(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){tV(e.userId);try{let{data:t,error:r}=await t1(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(tc(e))return{data:null,error:e};throw e}}async _deleteFactor(e){tV(e.userId),tV(e.id);
24try{return{data:await t1(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(tc(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},h=await t1(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(r=null==(t=null==e?void 0:e.page)?void 0:t.toString())?r:"",per_page:null!=(i=null==(s=null==e?void 0:e.perPage)?void 0:s.toString())?i:""},xform:t9});if(h.error)throw h.error;let c=await h.json(),u=null!=(n=h.headers.get("x-total-count"))?n:0,d=null!=(o=null==(a=h.headers.get("link"))?void 0:a.split(","))?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},c),l),error:null}}catch(e){if(tc(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await t1(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tc(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await t1(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tc(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await t1(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tc(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await t1(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tc(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await t1(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tc(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return(null==e?void 0:e.type)&&(t.type=e.type),await t1(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>{var t;return{data:{providers:null!=(t=null==e?void 0:e.providers)?t:[]},error:null}}})}catch(e){if(tc(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await t1(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tc(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await t1(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tc(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await t1(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tc(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await t1(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tc(e))return{data:null,error:e};throw e}}}function rt(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}let rr={debug:!!(globalThis&&tN()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class rs extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class ri extends rs{}async function rn(e,t,r){let s;rr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let i=new globalThis.AbortController;t>0&&(s=setTimeout(()=>{i.abort(),rr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t)),await Promise.resolve();try{return await globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:i.signal}
24,async i=>{if(i){clearTimeout(s),rr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,i.name);try{return await r()}finally{rr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,i.name)}}if(0===t)throw rr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new ri(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(rr.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"),clearTimeout(s),await r()})}catch(n){if(t>0&&clearTimeout(s),(null==n?void 0:n.name)==="AbortError"&&t>0)if(i.signal.aborted)return rr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",e),console.warn(`@supabase/gotrue-js: Lock "${e}" was not released within ${t}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,{mode:"exclusive",steal:!0},async t=>{if(!t)return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r();rr.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",e,t.name);try{return await r()}finally{rr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",e,t.name)}}));else throw rr.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",e),new ri(`Lock "${e}" was released because another request stole it`);throw n}}function ra(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}class ro extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!=(i=null!=s?s:r instanceof Error?r.name:void 0)?i:"Unknown Error",this.code=t}}class rl extends ro{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}let rh=new class{createNewAbortSignal(){if(this.controller){let e=Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function rc(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function ru(){var e,t;return!!(tI()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null==(e=null==navigator?void 0:navigator.credentials)?void 0:e.create)&&"function"==typeof(null==(t=null==navigator?void 0:navigator.credentials)?void 0:t.get))}async function rd(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new rl("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new rl("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function({error:e,options:t}){var r,s,i;let{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new ro({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if((null==(r=n.authenticatorSelection)?void 0:r.requireResidentKey)===!0)return new ro({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});else if("conditional"===t.mediation&&(null==(s=n.authenticatorSelection)?void 0:s.userVerification)==="required")return new ro({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});else if((null==(i=n.authenticatorSelection)?void 0:i.userVerification)==="required")return new ro({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else if("InvalidStateError"===e.name)return new ro({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});else if("NotAllowedError"===e.name)return new ro({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if("NotSupportedError"===e.name)return new ro(0===n.pubKeyCredParams.filter(e=>"public-key"===e.type).length?{message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}:{message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});else if("SecurityError"===e.name){let t=window.location.hostname;if(!rc(t))return new ro({message:`${window.location.hostname}
24 is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new ro({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new ro({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new ro({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new ro({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}({error:t,options:e})}}}async function rp(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new rl("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new rl("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new ro({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("NotAllowedError"===e.name)return new ro({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if("SecurityError"===e.name){let t=window.location.hostname;if(!rc(t))return new ro({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new ro({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new ro({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new ro({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}({error:t,options:e})}}}let rf={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},rg={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function rm(...e){let t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(let i of e)if(i)for(let e in i){let n=i[e];if(void 0!==n)if(Array.isArray(n))s[e]=n;else if(r(n))s[e]=n;else if(t(n)){let r=s[e];t(r)?s[e]=rm(r,n):s[e]=rm(n)}else s[e]=n}return s}class ry{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var n,a,o,l,h;try{let{data:c,error:u}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!c)return{data:null,error:u};let d=null!=s?s:rh.createNewAbortSignal();if("create"===c.webauthn.type){let{user:e}=c.webauthn.credential_options.publicKey;if(!e.name)if(r)e.name=`${e.id}:${r}`;else{let t=(await this.client.getUser()).data.user,r=(null==(n=null==t?void 0:t.user_metadata)?void 0:n.name)||(null==t?void 0:t.email)||(null==t?void 0:t.id)||"User";e.name=`${e.id}:${r}`}e.displayName||(e.displayName=e.name)}switch(c.webauthn.type){case"create":{let t=(a=c.webauthn.credential_options.publicKey,o=null==i?void 0:i.create,rm(rf,a,o||{})),{data:r,error:s}=await rd({publicKey:t,signal:d});if(r)return{data:{factorId:e,challengeId:c.id,webauthn:{type:c.webauthn.type,credential_response:r}},error:null};return{data:null,error:s}}case"request":{let t=(l=c.webauthn.credential_options.publicKey,h=null==i?void 0:i.request,rm(rg,l,h||{})),{data:r,error:s}=await rp(Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:t,signal:d}));if(r)return{data:{factorId:e,challengeId:c.id,webauthn:{type:c.webauthn.type,credential_response:r}},error:null};return{data:null,error:s}}}}catch(e){if(tc(e))return{data:null,error:e};return{data:null,error:new td("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t="u">typeof window?window.location.hostname:void 0,rpOrigins:r="u">typeof window?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new th("rpId is required for WebAuthn authentication")};try{if(!ru())return{data:null,error:new td("Browser does not support WebAuthn",null)};let{data:n,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!n)return{data:null,error:a};let{webauthn:o}=n;return this._verify({factorId:e,challengeId:n.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:r,credential_response:o.credential_response}})}catch(e){if(tc(e))return{data:null,error:e};return{data:null,error:new td("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t="u">typeof window?window.location.hostname:void 0,rpOrigins:r="u">typeof window?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new th("rpId is required for WebAuthn registration")};try{if(!ru())return{data:null,error:new td("Browser does not support WebAuthn",null)};let{data:n,error:a}=await this._enroll({friendlyName:e});if(!n)return await this.client.mfa.listFactors().then(t=>{var r;return null==(r=t.data)?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};let{data:o,error:l}=await this._challenge({factorId:n.id,friendlyName:n.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});if(!o)return{data:null,error:l};return this._verify({factorId:n.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}})}catch(e){if(tc(e))return{data:null,error:e};return{data:null,error:new td("Unexpected error in register",e)}}}}if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"u">typeof self&&(self.globalThis=self)}let rb={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:tn,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function rw(e,t,r){return await r()}let rv={};class r_{get jwks(){var e,t;return null!=(t=null==(e=rv[this.storageKey])?void 0:e.jwks)?t:{keys:[]}}set jwks(e){rv[this.storageKey]=Object.assign(Object.assign({},rv[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!=(t=null==(e=rv[this.storageKey])?void 0:e.cachedAt)?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){rv[this.storageKey]=Object.assign(Object.assign({},rv[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},rb),e);if(this.storageKey=i.storageKey,this.instanceID=null!=(t=r_.nextInstanceID[this.storageKey])?t:0,r_.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,"function"==typeof i.debug&&(this.logger=i.debug),this.instanceID>0&&tI()){const e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new re({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=tU(i.fetch),this.lock=i.lock||rw,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&tI()&&(null==(r=null==globalThis?void 0:globalThis.navigator)?void 0:r.locks)?this.lock=rn:this.lock=rw,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new r
24y(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:tN()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=rt(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=rt(this.memoryStorage)),tI()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null==(s=this.broadcastChannel)||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug("#broadcastChannel","error",e)}})}i.skipAutoInitialize||this.initialize().catch(e=>{this._debug("#initialize()","error",e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ti}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(tI()&&(t=function(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),tI()&&this.detectSessionInUrl&&"none"!==r){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){(this._debug("#_initialize()","error detecting session from URL",i),tc(i)&&"AuthImplicitGrantRedirectError"===i.name)&&(null==(e=i.details)||e.code);return{error:i}}let{session:n,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",n,"redirect type",a),await this._saveSession(n),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){if(tc(e))return this._returnResult({error:e});return this._returnResult({error:new td("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let{data:i,error:n}=await t1(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!=(r=null==(t=null==e?void 0:e.options)?void 0:t.data)?r:{},gotrue_meta_security:{captcha_token:null==(s=null==e?void 0:e.options)?void 0:s.captchaToken}},xform:t8});if(n||!i)return this._returnResult({data:{user:null,session:null},error:n});let a=i.session,o=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:o,session:a},error:null})}catch(e){if(tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,s;try{let i;if("email"in e){let{email:r,password:s,options:n}=e,a=null,o=null;"pkce"===this.flowType&&([a,o]=await tJ(this.storage,this.storageKey)),i=await t1(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==n?void 0:n.emailRedirectTo,body:{email:r,password:s,data:null!=(t=null==n?void 0:n.data)?t:{},gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:a,code_challenge_method:o},xform:t8})}else if("phone"in e){let{phone:t,password:n,options:a}=e;i=await t1(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!=(r=null==a?void 0:a.data)?r:{},channel:null!=(s=null==a?void 0:a.channel)?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:t8})}else throw new ty("You must provide either an email or phone number and a password");let{data:n,error:a}=i;if(a||!n)return await tB(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let o=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(e){if(await tB(this.storage,`${this.storageKey}-code-verifier`),tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){let{email:r,password:s,options:i}=e;t=await t1(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:t5})}else if("phone"in e){let{phone:r,password:s,options:i}=e;t=await t1(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:t5})}else throw new ty("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let e=new tm;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:null==(t=e.options)?void 0:t.redirectTo,scopes:null==(r=e.options)?void 0:r.scopes,queryParams:null==(s=e.options)?void 0:s.queryParams,skipBrowserRedirect:null==(i=e.options)?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,n,a,o,l,h,c,u,d;let p,f;if("message"in e)p=e.message,f=e.signature;else{let c,{chain:u,wallet:g,statement:m,options:y}=e;if(tI())if("object"==typeof g)c=g;else{let e=window;if("ethereum"in e&&"object"==typeof e.ethereum&&"request"in e.ethereum&&"function"==typeof e.ethereum.request)c=e.ethereum;else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof g||!(null==y?void 0:y.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");c=g}let b=new URL(null!=(t=null==y?void 0:y.url)?t:window.location.href),w=await c.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!w||0===w.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let v=ra(w[0]),_=null==(r=null==y?void 0:y.signInWithEthereum)?void 0:r.chainId;_||(_=parseInt(await c.request({method:"eth_chainId"}),16)),p=function(e){var t;let{chainId:r,domain:s,expirationTime:i,issuedAt:n=new Date,nonce:a,notBefore:o,requestId:l,resources:h,scheme:c,uri:u,version:d}=e;if(!Number.isInteger(r))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!u)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null==(t=e.statement)?void 0:t.includes("\n"))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let p=ra(e.address),f=c?`${c}://${s}`:s,g=e.statement?`${e.statement} 25`:"",m=`${f} wants you to sign in with your Ethereum account: 26${p} 27 28${g}`,y=`URI: ${u} 29Version: ${d}
30Chain ID: ${r}${a?` 31Nonce: ${a}`:""} 32Issued At: ${n.toISOString()}`;if(i&&(y+=` 33Expiration Time: ${i.toISOString()}`),o&&(y+=` 34Not Before: ${o.toISOString()}`),l&&(y+=` 35Request ID: ${l}`),h){let e="\nResources:";for(let t of h){if(!t||"string"!=typeof t)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=` 36- ${t}`}y+=e}return`${m} 37${y}`}({domain:b.host,address:v,statement:m,uri:b.href,version:"1",chainId:_,nonce:null==(s=null==y?void 0:y.signInWithEthereum)?void 0:s.nonce,issuedAt:null!=(n=null==(i=null==y?void 0:y.signInWithEthereum)?void 0:i.issuedAt)?n:new Date,expirationTime:null==(a=null==y?void 0:y.signInWithEthereum)?void 0:a.expirationTime,notBefore:null==(o=null==y?void 0:y.signInWithEthereum)?void 0:o.notBefore,requestId:null==(l=null==y?void 0:y.signInWithEthereum)?void 0:l.requestId,resources:null==(h=null==y?void 0:y.signInWithEthereum)?void 0:h.resources}),f=await c.request({method:"personal_sign",params:[(d=p,"0x"+Array.from(new TextEncoder().encode(d),e=>e.toString(16).padStart(2,"0")).join("")),v]})}try{let{data:t,error:r}=await t1(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:f},(null==(c=e.options)?void 0:c.captchaToken)?{gotrue_meta_security:{captcha_token:null==(u=e.options)?void 0:u.captchaToken}}:null),xform:t8});if(r)throw r;if(!t||!t.session||!t.user){let e=new tm;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,s,i,n,a,o,l,h,c,u,d;let p,f;if("message"in e)p=e.message,f=e.signature;else{let u,{chain:d,wallet:g,statement:m,options:y}=e;if(tI())if("object"==typeof g)u=g;else{let e=window;if("solana"in e&&"object"==typeof e.solana&&("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))u=e.solana;else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof g||!(null==y?void 0:y.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");u=g}let b=new URL(null!=(t=null==y?void 0:y.url)?t:window.location.href);if("signIn"in u&&u.signIn){let e,t=await u.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},null==y?void 0:y.signInWithSolana),{version:"1",domain:b.host,uri:b.href}),m?{statement:m}:null));if(Array.isArray(t)&&t[0]&&"object"==typeof t[0])e=t[0];else if(t&&"object"==typeof t&&"signedMessage"in t&&"signature"in t)e=t;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in e&&"signature"in e&&("string"==typeof e.signedMessage||e.signedMessage instanceof Uint8Array)&&e.signature instanceof Uint8Array)p="string"==typeof e.signedMessage?e.signedMessage:new TextDecoder().decode(e.signedMessage),f=e.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in u)||"function"!=typeof u.signMessage||!("publicKey"in u)||"object"!=typeof u||!u.publicKey||!("toBase58"in u.publicKey)||"function"!=typeof u.publicKey.toBase58)throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${b.host} wants you to sign in with your Solana account:`,u.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${b.href}`,`Issued At: ${null!=(s=null==(r=null==y?void 0:y.signInWithSolana)?void 0:r.issuedAt)?s:new Date().toISOString()}`,...(null==(i=null==y?void 0:y.signInWithSolana)?void 0:i.notBefore)?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...(null==(n=null==y?void 0:y.signInWithSolana)?void 0:n.expirationTime)?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...(null==(a=null==y?void 0:y.signInWithSolana)?void 0:a.chainId)?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...(null==(o=null==y?void 0:y.signInWithSolana)?void 0:o.nonce)?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...(null==(l=null==y?void 0:y.signInWithSolana)?void 0:l.requestId)?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...(null==(c=null==(h=null==y?void 0:y.signInWithSolana)?void 0:h.resources)?void 0:c.length)?["Resources",...y.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");let e=await u.signMessage(new TextEncoder().encode(p),"utf8");if(!e||!(e instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");f=e}}try{let{data:t,error:r}=await t1(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:t$(f)},(null==(u=e.options)?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null==(d=e.options)?void 0:d.captchaToken}}:null),xform:t8});if(r)throw r;if(!t||!t.session||!t.user){let e=new tm;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let t=await tD(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new tv;let{data:t,error:i}=await t1(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:t8});if(await tB(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!t||!t.session||!t.user){let e=new tm;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=s?s:null}),error:i})}catch(e){if(await tB(this.storage,`${this.storageKey}-code-verifier`),tc(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:n}=e,{data:a,error:o}=await t1(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:n,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:t8});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!a||!a.session||!a.user){let e=new tm;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:o})}catch(e){if(tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,s,i,n;try{if("email"in e){let{email:s,options:i}=e,n=null,a=null;"pkce"===this.flowType&&([n,a]=await tJ(this.storage,this.storageKey));let{error:o}=await t1(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!=(t=null==i?void 0:i.data)?t:{},create_user:null==(r=null==i?void 0:i.shouldCreateUser)||r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:a},redirectTo:null==i?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){let{phone:t,options:r}=e,{data:a,error:o}=await t1(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!=(s=null==r?void 0:r.data)?s:{},create_user:null==(i=null==r?void 0:r.shouldCreateUser)||i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!=(n=null==r?void 0:r.channel)?n:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new ty("You must provide either an email or phone number.")}catch(e){if(await tB(this.storage,`${this.storageKey}-code-verifier`),tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=null==(t=e.options)?void 0:t.redirectTo,i=null==(r=e.options)?void 0:r.captchaToken);let{data:n,error:a}=await t1(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:t8});if(a)throw a;if(!n)throw Error("An error occurred on token verification.");let o=n.session,l=n.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(e){if(tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,s,i,n;try{let a=null,o=null;"pkce"===this.flowType&&([a,o]=await tJ(this.storage,this.storageKey));let l=await t1(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!=(r=null==(t=e.options)?void 0:t.redirectTo)?r:void 0}),(null==(s=null==e?void 0:e.options)?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:o}),headers:this.headers,xform:t3});return(null==(i=l.data)?void 0:i.url)&&tI()&&!(null==(n=e.options)?void 0:n.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await tB(this.storage,`${this.storageKey}-code-verifier`),tc(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new tf;let{error:s}=await t1(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:s,options:i}=e,{error:n}=await t1(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:n})}if("phone"in e){let{phone:r,type:s,options:i}=e,{data:n,error:a}=await t1(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:a})}throw new ty("You must provide either an email or phone number and a type")}catch(e){if(tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,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(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let t=null,r=await tD(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),null!==r&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not val
37id"),await this._removeSession())),!t)return{data:{session:null},error:null};let s=!!t.expires_at&&1e3*t.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",t.expires_at),!s){if(this.userStorage){let e=await tD(this.userStorage,this.storageKey+"-user");(null==e?void 0:e.user)?t.user=e.user:t.user=tY()}if(this.storage.isServer&&t.user&&!t.user.__isUserNotAvailableProxy){var e;let r={value:this.suppressGetSessionWarning};t.user=(e=t.user,new Proxy(e,{get:(e,t,s)=>{if("__isInsecureUserWarningProxy"===t)return!0;if("symbol"==typeof t){let r=t.toString();if("Symbol(Symbol.toPrimitive)"===r||"Symbol(Symbol.toStringTag)"===r||"Symbol(util.inspect.custom)"===r||"Symbol(nodejs.util.inspect.custom)"===r)return Reflect.get(e,t,s)}return r.value||"string"!=typeof t||(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),r.value=!0),Reflect.get(e,t,s)}})),r.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:t},error:null}}let{data:i,error:n}=await this._callRefreshToken(t.refresh_token);if(n)return this._returnResult({data:{session:null},error:n});return this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{if(e)return await t1(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:t6});return await this._useSession(async e=>{var t,r,s;let{data:i,error:n}=e;if(n)throw n;return(null==(t=i.session)?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await t1(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!=(s=null==(r=i.session)?void 0:r.access_token)?s:void 0,xform:t6}):{data:{user:null},error:new tf}})}catch(e){if(tc(e))return tg(e)&&(await this._removeSession(),await tB(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new tf;let n=s.session,a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await tJ(this.storage,this.storageKey));let{data:l,error:h}=await t1(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:n.access_token,xform:t6});if(h)throw h;return n.user=l.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),this._returnResult({data:{user:n.user},error:null})})}catch(e){if(await tB(this.storage,`${this.storageKey}-code-verifier`),tc(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new tf;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:n}=tH(e.access_token);if(n.exp&&(s=(r=n.exp)<=t),s){let{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:s,error:n}=await this._getUser(e.access_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});i={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(tc(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:s,error:i}=t;if(i)throw i;e=null!=(r=s.session)?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new tf;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!tI())throw new tb("No browser detected.");
37if(e.error||e.error_description||e.error_code)throw new tb(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new tw("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new tb("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new tw("No code detected.");let{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;let s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:t.session,redirectType:null},error:null}}let{provider_token:r,provider_refresh_token:s,access_token:i,refresh_token:n,expires_in:a,expires_at:o,token_type:l}=e;if(!i||!a||!n||!l)throw new tb("No session defined in URL");let h=Math.round(Date.now()/1e3),c=parseInt(a),u=h+c;o&&(u=parseInt(o));let d=u-h;1e3*d<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${c}s`);let p=u-c;h-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,h):h-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,u,h);let{data:f,error:g}=await this._getUser(i);if(g)throw g;let m={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:c,expires_at:u,refresh_token:n,token_type:l,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:m,redirectType:e.type},error:null})}catch(e){if(tc(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await tD(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i&&!tg(i))return this._returnResult({error:i});let n=null==(r=s.session)?void 0:r.access_token;if(n){let{error:t}=await this.admin.signOut(n,e);if(t&&!(tc(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status||403===t.status)||tg(t)))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await tB(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=Symbol("auth-callback"),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:s},error:i}=t;if(i)throw i;await (null==(r=this.stateChangeEmitters.get(e))?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await (null==(s=this.stateChangeEmitters.get(e))?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await tJ(this.storage,this.storageKey,!0));try{return await t1(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await tB(this.storage,`${this.storageKey}-code-verifier`),tc(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!=(e=t.user.identities)?e:[]},error:null})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:r,error:s}=await this._useSession(async t=>{var r,s,i,n,a;let{data:o,error:l}=t;if(l)throw l;let h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null==(r=e.options)?void 0:r.redirectTo,scopes:null==(s=e.options)?void 0:s.scopes,queryParams:null==(i=e.options)?void 0:i.queryParams,skipBrowserRedirect:!0});return await t1(this.fetch,"GET",h,{headers:this.headers,jwt:null!=(a=null==(n=o.session)?void 0:n.access_token)?a:void 0})});if(s)throw s;return!tI()||(null==(t=e.options)?void 0:t.skipBrowserRedirect)||window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(tc(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:n,provider:a,token:o,access_token:l,nonce:h}=e,{data:c,error:u}=await t1(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!=(r=null==i?void 0:i.access_token)?r:void 0,body:{provider:a,id_token:o,access_token:l,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:t8});if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user)return this._returnResult({data:{user:null,session:null},error:new tm});return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("USER_UPDATED",c.session)),this._returnResult({data:c,error:u})}catch(e){if(await tB(this.storage,`${this.storageKey}-code-verifier`),tc(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)throw n;
37return await t1(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!=(s=null==(r=i.session)?void 0:r.access_token)?s:void 0})})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{var r,s;let i=Date.now();return await (r=async r=>(r>0&&await tM(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await t1(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:t8})),s=(e,t)=>{let r=200*Math.pow(2,e);return t&&tk(t)&&Date.now()+r-i<3e4},new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{let t=await r(i);if(!s(i,null,t))return void e(t)}catch(e){if(!s(i,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),tc(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),tI()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;let r="#_recoverAndRefresh()";this._debug(r,"begin");try{let s=await tD(this.storage,this.storageKey);if(s&&this.userStorage){let t=await tD(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!t&&(t={user:s.user},await tL(this.userStorage,this.storageKey+"-user",t)),s.user=null!=(e=null==t?void 0:t.user)?e:tY()}else if(s&&!s.user&&!s.user){let e=await tD(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await tB(this.storage,this.storageKey+"-user"),await tL(this.storage,this.storageKey,s)):s.user=tY()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),null!==s&&await this._removeSession();return}let i=(null!=(t=s.expires_at)?t:1/0)*1e3-Date.now()<9e4;if(this._debug(r,`session has${i?"":" not"} expired with margin of 90000s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),tk(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{let{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){this._debug(r,"error",e),console.error(e);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new tf;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new tq;let{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new tf;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);let s={data:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),tc(e)){let r={data:null,error:e};return tk(e)||await this._removeSession(),null==(t=this.refreshingDeferred)||t.resolve(r),r}throw null==(r=this.refreshingDeferred)||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(i),s.length>0){for(let e=0;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await tB(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await tL(this.userStorage,this.storageKey+"-user",{user:t.user});let e=Object.assign({},t);delete e.user;let s=tX(e);await tL(this.storage,this.storageKey,s)}else{let e=tX(t);await tL(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await tB(this.storage,this.storageKey),await tB(this.storage,this.storageKey+"-code-verifier"),await tB(this.storage,this.storageKey+"-user"),this.userStorage&&await tB(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&tI()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}
37catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _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:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof rs)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!tI()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"!==document.visibilityState?this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"):await this._recoverAndRefresh()}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){let[e,t]=await tJ(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(null==r?void 0:r.queryParams){let e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await t1(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token})})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)return this._returnResult({data:null,error:n});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:l}=await t1(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:null==(r=null==i?void 0:i.session)?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===o.type&&(null==(s=null==o?void 0:o.totp)?void 0:s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r,s,i;let{data:n,error:a}=t;if(a)return this._returnResult({data:null,error:a});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?(s=e.webauthn.credential_response,"toJSON"in s&&"function"==typeof s.toJSON?s.toJSON():{id:s.id,rawId:s.id,response:{attestationObject:t$(new Uint8Array(s.response.attestationObject)),clientDataJSON:t$(new Uint8Array(s.response.clientDataJSON))},type:"public-key",clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:null!=(i=s.authenticatorAttachment)?i:void 0}):function(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();let r=e.getClientExtensionResults(),s=e.response;
37return{id:e.id,rawId:e.id,response:{authenticatorData:t$(new Uint8Array(s.authenticatorData)),clientDataJSON:t$(new Uint8Array(s.clientDataJSON)),signature:t$(new Uint8Array(s.signature)),userHandle:s.userHandle?t$(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:h}=await t1(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:null==(r=null==n?void 0:n.session)?void 0:r.access_token});return h?this._returnResult({data:null,error:h}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:h}))})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let n=await t1(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token});if(n.error)return n;let{data:a}=n;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:function(e){if(!e)throw Error("Credential creation options are required");if("u">typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:s}=e,i=v(e,["challenge","user","excludeCredentials"]),n=tP(t).buffer,a=Object.assign(Object.assign({},r),{id:tP(r.id).buffer}),o=Object.assign(Object.assign({},i),{challenge:n,user:a});if(s&&s.length>0){o.excludeCredentials=Array(s.length);for(let e=0;e<s.length;e++){let t=s[e];o.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:tP(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:function(e){if(!e)throw Error("Credential request options are required");if("u">typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,s=v(e,["challenge","allowCredentials"]),i=tP(t).buffer,n=Object.assign(Object.assign({},s),{challenge:i});if(r&&r.length>0){n.allowCredentials=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e];n.allowCredentials[e]=Object.assign(Object.assign({},t),{id:tP(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return n}(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[]};for(let r of null!=(e=null==t?void 0:t.factors)?e:[])s.all.push(r),"verified"===r.status&&s[r.factor_type].push(r);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:s}=tH(e),i=null;s.aal&&(i=s.aal);let n=i,{data:{user:a},error:o}=await this.getUser(e);if(o)return this._returnResult({data:null,error:o});(null!=(r=null==(t=null==a?void 0:a.factors)?void 0:t.filter(e=>"verified"===e.status))?r:[]).length>0&&(n="aal2");let l=s.amr||[];return{data:{currentLevel:i,nextLevel:n,currentAuthenticationMethods:l},error:null}}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:n},error:a}
37=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:o}=tH(n.access_token),l=null;o.aal&&(l=o.aal);let h=l;return(null!=(i=null==(s=n.user.factors)?void 0:s.filter(e=>"verified"===e.status))?i:[]).length>0&&(h="aal2"),{data:{currentLevel:l,nextLevel:h,currentAuthenticationMethods:o.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await t1(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new tf})})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new tf});let n=await t1(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return n.data&&n.data.redirect_url&&tI()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(n.data.redirect_url),n})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new tf});let n=await t1(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return n.data&&n.data.redirect_url&&tI()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(n.data.redirect_url),n})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await t1(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new tf})})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await t1(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new tf})})}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;let s=Date.now();if((r=this.jwks.keys.find(t=>t.kid===e))&&this.jwks_cached_at+6e5>s)return r;let{data:i,error:n}=await t1(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(n)throw n;return i.keys&&0!==i.keys.length&&(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(t=>t.kid===e))?r:null}async getClaims(e,t={}){try{var r;let s,i=e;if(!i){let{data:e,error:t}
37=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});i=e.session.access_token}let{header:n,payload:a,signature:o,raw:{header:l,payload:h}}=tH(i);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}(a.exp);let c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks);if(!c){let{error:e}=await this.getUser(i);if(e)throw e;return{data:{claims:a,header:n,signature:o},error:null}}let u=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw Error("Invalid alg claim")}}(n.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,(r=`${l}.${h}`,s=[],!function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)return t(e);if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}(s,t)}}(r,e=>s.push(e)),new Uint8Array(s))))throw new tT("Invalid JWT signature");return{data:{claims:a,header:n,signature:o},error:null}}catch(e){if(tc(e))return this._returnResult({data:null,error:e});throw e}}}r_.nextInstanceID={};let rk=r_,rS="";rS="u">typeof Deno?"deno":"u">typeof document?"web":"u">typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";let rT={headers:{"X-Client-Info":`supabase-js-${rS}/2.101.1`}},rE={schema:"public"},rA={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},rO={};function rR(e){return(rR="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function rC(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function rj(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?rC(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=rR(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=rR(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==rR(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rC(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var rP=class extends rk{constructor(e){super(e)}},r$=class{constructor(e,t,r){var s,i,n;this.supabaseUrl=e,this.supabaseKey=t;const a=function(e){let t=null==e?void 0:e.trim();if(!t)throw Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(t.endsWith("/")?t:t+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(e);if(!t)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const o=`sb-${a.hostname.split(".")[0]}-auth-token`,l=function(e,t){var r,s;let{db:i,auth:n,realtime:a,global:o}=e,{db:l,auth:h,realtime:c,global:u}=t,d={db:rj(rj({},l),i),auth:rj(rj({},h),n),realtime:rj(rj({},c),a),storage:{},global:rj(rj(rj({},u),o),{},{headers:rj(rj({},null!=(r=null==u?void 0:u.headers)?r:{}),null!=(s=null==o?void 0:o.headers)?s:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:rE,realtime:rO,auth:rj(rj({},rA),{},{storageKey:o}),global:rT});this.storageKey=null!=(s=l.auth.storageKey)?s:"",this.headers=null!=(i=l.global.headers)?i:{},l.accessToken?(this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!=(n=l.auth)?n:{},this.headers,l.global.fetch),this.fetch=((e,t,r)=>{let s=r?(...e)=>r(...e):(...e)=>fetch(...e),i=Headers;return async(r,n)=>{var a;let o=null!=(a=await t())?a:e,l=new i(null==n?void 0:n.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${o}`),s(r,rj(rj({},n),{},{headers:l}))}})(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(rj({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new P(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new ts(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new _(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}
37channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();let{data:r}=await this.auth.getSession();return null!=(e=null==(t=r.session)?void 0:t.access_token)?e:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:n,flowType:a,lock:o,debug:l,throwOnError:h},c,u){let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new rP({url:this.authUrl.href,headers:rj(rj({},d),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,flowType:a,lock:o,debug:l,throwOnError:h,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new eE(this.realtimeUrl.href,rj(rj({},e),{},{params:rj(rj({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){("TOKEN_REFRESHED"===e||"SIGNED_IN"===e)&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}};(function(){if("u">typeof window)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(null==t)return!1;let r=t.match(/^v(\d+)\./);return!!r&&18>=parseInt(r[1],10)})()&&console.warn("â ï¸ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");let rI="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),rx=" \n\r=".split(""),rN=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<rx.length;t+=1)e[rx[t].charCodeAt(0)]=-2;for(let t=0;t<rI.length;t+=1)e[rI[t].charCodeAt(0)]=t;return e})();function rU(e){let t=[],r=0,s=0;if(function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)return t(e);if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}(s,t)}}(e,e=>{for(r=r<<8|e,s+=8;s>=6;){let e=r>>s-6&63;t.push(rI[e]),s-=6}}),s>0)for(r<<=6-s,s=6;s>=6;){let e=r>>s-6&63;t.push(rI[e]),s-=6}return t.join("")}function rL(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i=0,n=0;for(let t=0;t<e.length;t+=1){let a=rN[e.charCodeAt(t)];if(a>-1)for(i=i<<6|a,n+=6;n>=8;)(function(e,t,r){if(0===t.utf8seq){if(e<=127)return r(e);for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}})(i>>n-8&255,s,r),n-=8;else if(-2===a)continue;else throw Error(`Invalid Base64-URL character "${e.at(t)}" at position ${t}`)}return t.join("")}var rD=e.i(9156);function rB(){return"u">typeof window&&void 0!==window.document}rD.parse,rD.serialize;let rq={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4},rH=/^(.*)[.](0|[1-9][0-9]*)$/;function rM(e,t){if(e===t)return!0;let r=e.match(rH);return!!r&&r[1]===t}function rW(e,t,r){let s=r??3180,i=encodeURIComponent(t);if(i.length<=s)return[{name:e,value:t}];let n=[];for(;i.length>0;){let e=i.slice(0,s),t=e.lastIndexOf("%");t>s-3&&(e=e.slice(0,t));let r="";for(;e.length>0;)try{r=decodeURIComponent(e);break}catch(t){if(t instanceof URIError&&"%"===e.at(-3)&&e.length>3)e=e.slice(0,e.length-3);else throw t}n.push(r),i=i.slice(e.length)}return n.map((t,r)=>({name:`${e}.${r}`,value:t}))}async function rK(e,t){let r=await t(e);if(r)return r;let s=[];for(let r=0;;r++){let i=`${e}.${r}`,n=await t(i);if(!n)break;s.push(n)}return s.length>0?s.join(""):null}let rF="base64-";async function rJ({getAll:e,setAll:t,setItems:r,removedItems:s},i){let n=i.cookieEncoding,a=i.cookieOptions??null,o=await e([...r?Object.keys(r):[],...s?Object.keys(s):[]]),l=o?.map(({name:e})=>e)||[],h=Object.keys(s).flatMap(e=>l.filter(t=>rM(t,e))),c=Object.keys(r).flatMap(e=>{let t=new Set(l.filter(t=>rM(t,e))),s=r[e];"base64url"===n&&(s=rF+rU(s));let i=rW(e,s);
37return i.forEach(e=>{t.delete(e.name)}),h.push(...t),i}),u={...rq,...a,maxAge:0},d={...rq,...a,maxAge:rq.maxAge};delete u.name,delete d.name,await t([...h.map(e=>({name:e,value:"",options:u})),...c.map(({name:e,value:t})=>({name:e,value:t,options:d}))],{"Cache-Control":"private, no-cache, no-store, must-revalidate, max-age=0",Expires:"0",Pragma:"no-cache"})}if(void 0!==g.default&&g.default.env?.npm_package_name){let e=g.default.env.npm_package_name;["@supabase/auth-helpers-nextjs","@supabase/auth-helpers-react","@supabase/auth-helpers-remix","@supabase/auth-helpers-sveltekit"].includes(e)&&console.warn(` 38ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 39â â ï¸ IMPORTANT: Package Consolidation Notice â 40â â 41â The ${e.padEnd(35)} package name is deprecated. â 42â â 43â You are now using @supabase/ssr - a unified solution for all frameworks. â 44â â 45â The auth-helpers packages have been consolidated into @supabase/ssr â 46â to provide better maintenance and consistent APIs across frameworks. â 47â â 48â Please update your package.json to use @supabase/ssr directly: â 49â npm uninstall ${e.padEnd(42)} â 50â npm install @supabase/ssr â 51â â 52â For more information, visit: â 53â https://supabase.com/docs/guides/auth/server-side â 54ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 55 `)}e.s(["createClient",0,function(){let e="https://vungsrzxburyebfndzor.supabase.co".trim(),t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZ1bmdzcnp4YnVyeWViZm5kem9yIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzUyOTgwMjksImV4cCI6MjA5MDg3NDAyOX0.rXwTu6QLMeIRGOWIXOoOcdaNA3tWF3b9vymDMGq3FGQ".trim();return e&&t?function(e,t){let s=rB();if(s&&r)return r;if(!e||!t)throw Error(`@supabase/ssr: Your project's URL and API key are required to create a Supabase client! 56 57Check your Supabase project's API settings to find these values 58 59https://supabase.com/dashboard/project/_/settings/api`);let{storage:i}=function(e,t){let r,s,i=e.cookies??null,n=e.cookieEncoding,a={},o={};if(i)if("get"in i){let e=async e=>{let t=e.flatMap(e=>[e,...Array.from({length:5}).map((t,r)=>`${e}.${r}`)]),r=[];for(let e=0;e<t.length;e+=1){let s=await i.get(t[e]);(s||"string"==typeof s)&&r.push({name:t[e],value:s})}return r};if(r=async t=>await e(t),"set"in i&&"remove"in i)s=async e=>{for(let t=0;t<e.length;t+=1){let{name:r,value:s,options:n}=e[t];s?await i.set(r,s,n):await i.remove(r,n)}};else if(t)s=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness. Consider switching to the getAll and setAll cookie methods instead of get, set and remove which are deprecated and can be difficult to use correctly.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring a getAll and setAll cookie method (deprecated: alternatively both get, set and remove can be used)")}else if("getAll"in i)if(r=async()=>await i.getAll(),"setAll"in i)s=i.setAll;else if(t)s=async()=>{console.warn("@supabase/ssr: createServerClient was configured without the setAll cookie method, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for c
59orrectness.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring both getAll and setAll cookie methods (deprecated: alternatively both get, set and remove can be used)");else throw Error(`@supabase/ssr: ${t?"createServerClient":"createBrowserClient"} requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).${rB()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""}`);else if(!t&&rB())r=()=>{let e;return Object.keys(e=(0,rD.parse)(document.cookie)).map(t=>({name:t,value:e[t]??""}))},s=e=>{e.forEach(({name:e,value:t,options:r})=>{document.cookie=(0,rD.serialize)(e,t,r)})};else if(t)throw Error("@supabase/ssr: createServerClient must be initialized with cookie options that specify getAll and setAll functions (deprecated, not recommended: alternatively use get, set and remove)");else r=()=>[],s=()=>{throw Error("@supabase/ssr: createBrowserClient in non-browser runtimes (including Next.js pre-rendering mode) was not initialized cookie options that specify getAll and setAll functions (deprecated: alternatively use get, set and remove), but they were needed")};return t?{getAll:r,setAll:s,setItems:a,removedItems:o,storage:{isServer:!0,getItem:async e=>{if("string"==typeof a[e])return a[e];if(o[e])return null;let t=await r([e]),s=await rK(e,async e=>{let r=t?.find(({name:t})=>t===e)||null;return r?r.value:null});if(!s)return null;let i=s;return"string"==typeof s&&s.startsWith(rF)&&(i=rL(s.substring(rF.length))),i},setItem:async(t,i)=>{t.endsWith("-code-verifier")&&await rJ({getAll:r,setAll:s,setItems:{[t]:i},removedItems:{}},{cookieOptions:e?.cookieOptions??null,cookieEncoding:n}),a[t]=i,delete o[t]},removeItem:async e=>{delete a[e],o[e]=!0}}}:{getAll:r,setAll:s,setItems:a,removedItems:o,storage:{isServer:!1,getItem:async e=>{let t=await r([e]),s=await rK(e,async e=>{let r=t?.find(({name:t})=>t===e)||null;return r?r.value:null});if(!s)return null;let i=s;return s.startsWith(rF)&&(i=rL(s.substring(rF.length))),i},setItem:async(t,i)=>{let a=await r([t]),o=new Set((a?.map(({name:e})=>e)||[]).filter(e=>rM(e,t))),l=i;"base64url"===n&&(l=rF+rU(i));let h=rW(t,l);h.forEach(({name:e})=>{o.delete(e)});let c={...rq,...e?.cookieOptions,maxAge:0},u={...rq,...e?.cookieOptions,maxAge:rq.maxAge};delete c.name,delete u.name;let d=[...[...o].map(e=>({name:e,value:"",options:c})),...h.map(({name:e,value:t})=>({name:e,value:t,options:u}))];d.length>0&&await s(d,{})},removeItem:async t=>{let i=await r([t]),n=(i?.map(({name:e})=>e)||[]).filter(e=>rM(e,t)),a={...rq,...e?.cookieOptions,maxAge:0};delete a.name,n.length>0&&await s(n.map(e=>({name:e,value:"",options:a})),{})}}}}({...void 0,cookieEncoding:(void 0)??"base64url"},!1),n=new r$(e,t,{...void 0,global:{...void 0,headers:{...void 0,"X-Client-Info":"supabase-ssr/0.10.0 createBrowserClient"}},auth:{...void 0,...null,flowType:"pkce",autoRefreshToken:rB(),detectSessionInUrl:rB(),persistSession:!0,storage:i,...null}});return s&&(r=n),n}(e,t):null}],90615)},45636,e=>{"use strict";var t=e.i(18050),r=e.i(71645);let s=(0,r.createContext)("en");e.s(["LocaleProvider",0,function({locale:e,children:r}){return(0,t.jsx)(s.Provider,{value:e,children:r})},"useLocale",0,function(){return(0,r.useContext)(s)}])}]);
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.