@zeno-cms/sdk 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +353 -0
- package/dist/angular.d.mts +78 -0
- package/dist/angular.d.ts +78 -0
- package/dist/angular.js +8 -0
- package/dist/angular.js.map +1 -0
- package/dist/angular.mjs +2 -0
- package/dist/angular.mjs.map +1 -0
- package/dist/chunk-4ROHQDX7.mjs +8 -0
- package/dist/chunk-4ROHQDX7.mjs.map +1 -0
- package/dist/index.d.mts +206 -0
- package/dist/index.d.ts +206 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/dist/react.d.mts +80 -0
- package/dist/react.d.ts +80 -0
- package/dist/react.js +8 -0
- package/dist/react.js.map +1 -0
- package/dist/react.mjs +2 -0
- package/dist/react.mjs.map +1 -0
- package/dist/svelte.d.mts +73 -0
- package/dist/svelte.d.ts +73 -0
- package/dist/svelte.js +8 -0
- package/dist/svelte.js.map +1 -0
- package/dist/svelte.mjs +2 -0
- package/dist/svelte.mjs.map +1 -0
- package/dist/vue.d.mts +72 -0
- package/dist/vue.d.ts +72 -0
- package/dist/vue.js +8 -0
- package/dist/vue.js.map +1 -0
- package/dist/vue.mjs +2 -0
- package/dist/vue.mjs.map +1 -0
- package/dist/zeno.min.js +50 -0
- package/dist/zeno.min.js.map +1 -0
- package/package.json +114 -0
package/dist/zeno.min.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
var ZenoSDK=(function(exports){'use strict';function ee(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(r);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(r,s[n])&&(t[s[n]]=r[s[n]]);return t}function Wt(r,e,t,s){function n(i){return i instanceof t?i:new t(function(a){a(i);})}return new(t||(t=Promise))(function(i,a){function o(u){try{c(s.next(u));}catch(f){a(f);}}function l(u){try{c(s.throw(u));}catch(f){a(f);}}function c(u){u.done?i(u.value):n(u.value).then(o,l);}c((s=s.apply(r,e||[])).next());})}var Ht=r=>r?(...e)=>r(...e):(...e)=>fetch(...e);var ge=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s;}},Oe=class extends ge{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e);}},_e=class extends ge{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e);}},ye=class extends ge{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e);}},Re;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2";})(Re||(Re={}));var xe=class{constructor(e,{headers:t={},customFetch:s,region:n=Re.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=Ht(s);}setAuth(e){this.headers.Authorization=`Bearer ${e}`;}invoke(e){return Wt(this,arguments,void 0,function*(t,s={}){var n;let i,a;try{let{headers:o,method:l,body:c,signal:u,timeout:f}=s,d={},{region:h}=s;h||(h=this.region);let p=new URL(`${this.url}/${t}`);h&&h!=="any"&&(d["x-region"]=h,p.searchParams.set("forceFunctionRegion",h));let g;c&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",g=c):typeof c=="string"?(d["Content-Type"]="text/plain",g=c):typeof FormData<"u"&&c instanceof FormData?g=c:(d["Content-Type"]="application/json",g=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?g=JSON.stringify(c):g=c;let _=u;f&&(a=new AbortController,i=setTimeout(()=>a.abort(),f),u?(_=a.signal,u.addEventListener("abort",()=>a.abort())):_=a.signal);let y=yield this.fetch(p.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),o),body:g,signal:_}).catch(P=>{throw new Oe(P)}),m=y.headers.get("x-relay-error");if(m&&m==="true")throw new _e(y);if(!y.ok)throw new ye(y);let v=((n=y.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),S;return v==="application/json"?S=yield y.json():v==="application/octet-stream"||v==="application/pdf"?S=yield y.blob():v==="text/event-stream"?S=y:v==="multipart/form-data"?S=yield y.formData():S=yield y.text(),{data:S,error:null,response:y}}catch(o){return {data:null,error:o,response:o instanceof ye||o instanceof _e?o.context:void 0}}finally{i&&clearTimeout(i);}})}};var Jt=class extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.code=r.code;}},Zr=class{constructor(r){var e,t,s;this.shouldThrowOnError=false,this.method=r.method,this.url=r.url,this.headers=new Headers(r.headers),this.schema=r.schema,this.body=r.body,this.shouldThrowOnError=(e=r.shouldThrowOnError)!==null&&e!==void 0?e:false,this.signal=r.signal,this.isMaybeSingle=(t=r.isMaybeSingle)!==null&&t!==void 0?t:false,this.urlLengthLimit=(s=r.urlLengthLimit)!==null&&s!==void 0?s:8e3,r.fetch?this.fetch=r.fetch:this.fetch=fetch;}throwOnError(){return this.shouldThrowOnError=true,this}setHeader(r,e){return this.headers=new Headers(this.headers),this.headers.set(r,e),this}then(r,e){var t=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let s=this.fetch,n=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let a=null,o=null,l=null,c=i.status,u=i.statusText;if(i.ok){var f,d;if(t.method!=="HEAD"){var h;let y=await i.text();y===""||(t.headers.get("Accept")==="text/csv"||t.headers.get("Accept")&&(!((h=t.headers.get("Accept"))===null||h===void 0)&&h.includes("application/vnd.pgrst.plan+text"))?o=y:o=JSON.parse(y));}let g=(f=t.headers.get("Prefer"))===null||f===void 0?void 0:f.match(/count=(exact|planned|estimated)/),_=(d=i.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");g&&_&&_.length>1&&(l=parseInt(_[1])),t.isMaybeSingle&&t.method==="GET"&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,l=null,c=406,u="Not Acceptable"):o.length===1?o=o[0]:o=null);}else {var p;let g=await i.text();try{a=JSON.parse(g),Array.isArray(a)&&i.status===404&&(o=[],a=null,c=200,u="OK");}catch{i.status===404&&g===""?(c=204,u="No Content"):a={message:g};}if(a&&t.isMaybeSingle&&(!(a==null||(p=a.details)===null||p===void 0)&&p.includes("0 rows"))&&(a=null,c=200,u="OK"),a&&t.shouldThrowOnError)throw new Jt(a)}return {error:a,data:o,count:l,status:c,statusText:u}});return this.shouldThrowOnError||(n=n.catch(i=>{var a;let o="",l="",c="",u=i?.cause;if(u){var f,d,h,p;let y=(f=u?.message)!==null&&f!==void 0?f:"",m=(d=u?.code)!==null&&d!==void 0?d:"";o=`${(h=i?.name)!==null&&h!==void 0?h:"FetchError"}: ${i?.message}`,o+=`
|
|
2
|
+
|
|
3
|
+
Caused by: ${(p=u?.name)!==null&&p!==void 0?p:"Error"}: ${y}`,m&&(o+=` (${m})`),u?.stack&&(o+=`
|
|
4
|
+
${u.stack}`);}else {var g;o=(g=i?.stack)!==null&&g!==void 0?g:"";}let _=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",_>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${_} 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.`)):(u?.name==="HeadersOverflowError"||u?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",_>this.urlLengthLimit&&(l+=`. Your request URL is ${_} 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:`${(a=i?.name)!==null&&a!==void 0?a:"FetchError"}: ${i?.message}`,details:o,hint:l,code:c},data:null,count:null,status:0,statusText:""}})),n.then(r,e)}returns(){return this}overrideTypes(){return this}},Xr=class extends Zr{select(r){let e=false,t=(r??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",t),this.headers.append("Prefer","return=representation"),this}order(r,{ascending:e=true,nullsFirst:t,foreignTable:s,referencedTable:n=s}={}){let i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${r}.${e?"asc":"desc"}${t===void 0?"":t?".nullsfirst":".nullslast"}`),this}limit(r,{foreignTable:e,referencedTable:t=e}={}){let s=typeof t>"u"?"limit":`${t}.limit`;return this.url.searchParams.set(s,`${r}`),this}range(r,e,{foreignTable:t,referencedTable:s=t}={}){let n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${r}`),this.url.searchParams.set(i,`${e-r+1}`),this}abortSignal(r){return this.signal=r,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=true,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:r=false,verbose:e=false,settings:t=false,buffers:s=false,wal:n=false,format:i="text"}={}){var a;let o=[r?"analyze":null,e?"verbose":null,t?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(r){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${r}`),this}},Gt=new RegExp("[,()]"),me=class extends Xr{eq(r,e){return this.url.searchParams.append(r,`eq.${e}`),this}neq(r,e){return this.url.searchParams.append(r,`neq.${e}`),this}gt(r,e){return this.url.searchParams.append(r,`gt.${e}`),this}gte(r,e){return this.url.searchParams.append(r,`gte.${e}`),this}lt(r,e){return this.url.searchParams.append(r,`lt.${e}`),this}lte(r,e){return this.url.searchParams.append(r,`lte.${e}`),this}like(r,e){return this.url.searchParams.append(r,`like.${e}`),this}likeAllOf(r,e){return this.url.searchParams.append(r,`like(all).{${e.join(",")}}`),this}likeAnyOf(r,e){return this.url.searchParams.append(r,`like(any).{${e.join(",")}}`),this}ilike(r,e){return this.url.searchParams.append(r,`ilike.${e}`),this}ilikeAllOf(r,e){return this.url.searchParams.append(r,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(r,e){return this.url.searchParams.append(r,`ilike(any).{${e.join(",")}}`),this}regexMatch(r,e){return this.url.searchParams.append(r,`match.${e}`),this}regexIMatch(r,e){return this.url.searchParams.append(r,`imatch.${e}`),this}is(r,e){return this.url.searchParams.append(r,`is.${e}`),this}isDistinct(r,e){return this.url.searchParams.append(r,`isdistinct.${e}`),this}in(r,e){let t=Array.from(new Set(e)).map(s=>typeof s=="string"&&Gt.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(r,`in.(${t})`),this}notIn(r,e){let t=Array.from(new Set(e)).map(s=>typeof s=="string"&&Gt.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(r,`not.in.(${t})`),this}contains(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cs.{${e.join(",")}}`):this.url.searchParams.append(r,`cs.${JSON.stringify(e)}`),this}containedBy(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cd.{${e.join(",")}}`):this.url.searchParams.append(r,`cd.${JSON.stringify(e)}`),this}rangeGt(r,e){return this.url.searchParams.append(r,`sr.${e}`),this}rangeGte(r,e){return this.url.searchParams.append(r,`nxl.${e}`),this}rangeLt(r,e){return this.url.searchParams.append(r,`sl.${e}`),this}rangeLte(r,e){return this.url.searchParams.append(r,`nxr.${e}`),this}rangeAdjacent(r,e){return this.url.searchParams.append(r,`adj.${e}`),this}overlaps(r,e){return typeof e=="string"?this.url.searchParams.append(r,`ov.${e}`):this.url.searchParams.append(r,`ov.{${e.join(",")}}`),this}textSearch(r,e,{config:t,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");let i=t===void 0?"":`(${t})`;return this.url.searchParams.append(r,`${n}fts${i}.${e}`),this}match(r){return Object.entries(r).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`);}),this}not(r,e,t){return this.url.searchParams.append(r,`not.${e}.${t}`),this}or(r,{foreignTable:e,referencedTable:t=e}={}){let s=t?`${t}.or`:"or";return this.url.searchParams.append(s,`(${r})`),this}filter(r,e,t){return this.url.searchParams.append(r,`${e}.${t}`),this}},Qr=class{constructor(r,{headers:e={},schema:t,fetch:s,urlLengthLimit:n=8e3}){this.url=r,this.headers=new Headers(e),this.schema=t,this.fetch=s,this.urlLengthLimit=n;}cloneRequestState(){return {url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(r,e){let{head:t=false,count:s}=e??{},n=t?"HEAD":"GET",i=false,a=(r??"*").split("").map(c=>/\s/.test(c)&&!i?"":(c==='"'&&(i=!i),c)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),s&&l.append("Prefer",`count=${s}`),new me({method:n,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(r,{count:e,defaultToNull:t=true}={}){var s;let n="POST",{url:i,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),t||a.append("Prefer","missing=default"),Array.isArray(r)){let o=r.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(o.length>0){let l=[...new Set(o)].map(c=>`"${c}"`);i.searchParams.set("columns",l.join(","));}}return new me({method:n,url:i,headers:a,schema:this.schema,body:r,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(r,{onConflict:e,ignoreDuplicates:t=false,count:s,defaultToNull:n=true}={}){var i;let a="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${t?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&l.append("Prefer",`count=${s}`),n||l.append("Prefer","missing=default"),Array.isArray(r)){let c=r.reduce((u,f)=>u.concat(Object.keys(f)),[]);if(c.length>0){let u=[...new Set(c)].map(f=>`"${f}"`);o.searchParams.set("columns",u.join(","));}}return new me({method:a,url:o,headers:l,schema:this.schema,body:r,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(r,{count:e}={}){var t;let s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new me({method:s,url:n,headers:i,schema:this.schema,body:r,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:r}={}){var e;let t="DELETE",{url:s,headers:n}=this.cloneRequestState();return r&&n.append("Prefer",`count=${r}`),new me({method:t,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Pe(r){"@babel/helpers - typeof";return Pe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Pe(r)}function es(r,e){if(Pe(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(Pe(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(r)}function ts(r){var e=es(r,"string");return Pe(e)=="symbol"?e:e+""}function rs(r,e,t){return (e=ts(e))in r?Object.defineProperty(r,e,{value:t,enumerable:true,configurable:true,writable:true}):r[e]=t,r}function zt(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(r,n).enumerable})),t.push.apply(t,s);}return t}function Je(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?zt(Object(t),true).forEach(function(s){rs(r,s,t[s]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):zt(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s));});}return r}var Yt=class Zt{constructor(e,{headers:t={},schema:s,fetch:n,timeout:i,urlLengthLimit:a=8e3}={}){this.url=e,this.headers=new Headers(t),this.schemaName=s,this.urlLengthLimit=a;let o=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(l,c)=>{let u=new AbortController,f=setTimeout(()=>u.abort(),i),d=c?.signal;if(d){if(d.aborted)return clearTimeout(f),o(l,c);let h=()=>{clearTimeout(f),u.abort();};return d.addEventListener("abort",h,{once:true}),o(l,Je(Je({},c),{},{signal:u.signal})).finally(()=>{clearTimeout(f),d.removeEventListener("abort",h);})}return o(l,Je(Je({},c),{},{signal:u.signal})).finally(()=>clearTimeout(f))}:this.fetch=o;}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Qr(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Zt(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,t={},{head:s=false,get:n=false,count:i}={}){var a;let o,l=new URL(`${this.url}/rpc/${e}`),c,u=h=>h!==null&&typeof h=="object"&&(!Array.isArray(h)||h.some(u)),f=s&&Object.values(t).some(u);f?(o="POST",c=t):s||n?(o=s?"HEAD":"GET",Object.entries(t).filter(([h,p])=>p!==void 0).map(([h,p])=>[h,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([h,p])=>{l.searchParams.append(h,p);})):(o="POST",c=t);let d=new Headers(this.headers);return f?d.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&d.set("Prefer",`count=${i}`),new me({method:o,url:l,headers:d,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};var vt=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return {type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return {type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return {type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return {type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return {type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let t=globalThis.process;if(t){let s=t.versions;if(s&&s.node){let n=s.node,i=parseInt(n.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
5
|
+
import ws from "ws"
|
|
6
|
+
new 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+=`
|
|
7
|
+
|
|
8
|
+
Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){let s=this.getWebSocketConstructor();return new s(e,t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return false}}},wt=vt;var Xt="2.96.0";var Qt=`realtime-js/${Xt}`,er="1.0.0",bt="2.0.0",Et=bt;var Ie=1e4,tr=1e3,rr=100,H;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed";})(H||(H={}));var I;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving";})(I||(I={}));var L;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token";})(L||(L={}));var Ye;(function(r){r.websocket="websocket";})(Ye||(Ye={}));var Y;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed";})(Y||(Y={}));var je=class{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=e??[];}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return t(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer((t=e.payload)===null||t===void 0?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,s;let n=(s=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var t,s;let n=(s=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&s!==void 0?s:{},a=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(e,t,s){var n,i;let a=e.topic,o=(n=e.ref)!==null&&n!==void 0?n:"",l=(i=e.join_ref)!==null&&i!==void 0?i:"",c=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},f=Object.keys(u).length===0?"":JSON.stringify(u);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(f.length>255)throw new Error(`metadata length ${f.length} exceeds maximum of 255`);let d=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+o.length+a.length+c.length+f.length,h=new ArrayBuffer(this.HEADER_LENGTH+d),p=new DataView(h),g=0;p.setUint8(g++,this.KINDS.userBroadcastPush),p.setUint8(g++,l.length),p.setUint8(g++,o.length),p.setUint8(g++,a.length),p.setUint8(g++,c.length),p.setUint8(g++,f.length),p.setUint8(g++,t),Array.from(l,y=>p.setUint8(g++,y.charCodeAt(0))),Array.from(o,y=>p.setUint8(g++,y.charCodeAt(0))),Array.from(a,y=>p.setUint8(g++,y.charCodeAt(0))),Array.from(c,y=>p.setUint8(g++,y.charCodeAt(0))),Array.from(f,y=>p.setUint8(g++,y.charCodeAt(0)));var _=new Uint8Array(h.byteLength+s.byteLength);return _.set(new Uint8Array(h),0),_.set(new Uint8Array(s),h.byteLength),_.buffer}decode(e,t){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return t(s)}if(typeof e=="string"){let s=JSON.parse(e),[n,i,a,o,l]=s;return t({join_ref:n,ref:i,topic:a,event:o,payload:l})}return t({})}_binaryDecode(e){let t=new DataView(e),s=t.getUint8(0),n=new TextDecoder;if(s===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,n)}_decodeUserBroadcast(e,t,s){let n=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),l=this.HEADER_LENGTH+4,c=s.decode(e.slice(l,l+n));l=l+n;let u=s.decode(e.slice(l,l+i));l=l+i;let f=s.decode(e.slice(l,l+a));l=l+a;let d=e.slice(l,e.byteLength),h=o===this.JSON_ENCODING?JSON.parse(s.decode(d)):d,p={type:this.BROADCAST_EVENT,event:u,payload:h};return a>0&&(p.meta=JSON.parse(f)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||((t=e?.constructor)===null||t===void 0?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>t.includes(s)))}};var te=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t;}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0;}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback();},this.timerCalc(this.tries+1));}};var T;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange";})(T||(T={}));var kt=(r,e,t={})=>{var s;let n=(s=t.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((i,a)=>(i[a]=ss(a,r,e,n),i),{}):{}},ss=(r,e,t,s)=>{let n=e.find(o=>o.name===r),i=n?.type,a=t[r];return i&&!s.includes(i)?sr(i,a):St(a)},sr=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return os(e,t)}switch(r){case T.bool:return ns(e);case T.float4:case T.float8:case T.int2:case T.int4:case T.int8:case T.numeric:case T.oid:return is(e);case T.json:case T.jsonb:return as(e);case T.timestamp:return ls(e);case T.abstime:case T.date:case T.daterange:case T.int4range:case T.int8range:case T.money:case T.reltime:case T.text:case T.time:case T.timestamptz:case T.timetz:case T.tsrange:case T.tstzrange:return St(e);default:return St(e)}},St=r=>r,ns=r=>{switch(r){case "t":return true;case "f":return false;default:return r}},is=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},as=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r},os=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let i,a=r.slice(1,t);try{i=JSON.parse("["+a+"]");}catch{i=a?a.split(","):[];}return i.map(o=>sr(e,o))}return r},ls=r=>typeof r=="string"?r.replace(" ","T"):r,Ze=r=>{let e=new URL(r);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var re=class{constructor(e,t,s={},n=Ie){this.channel=e,this.event=t,this.payload=s,this.timeout=n,this.sent=false,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null;}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=false,this.send();}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=true,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}));}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e);}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t);};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{});},this.timeout);}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t});}destroy(){this._cancelRefEvent(),this._cancelTimeout();}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{});}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0;}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t));}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Tt;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave";})(Tt||(Tt={}));var ve=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=false,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,n,i,a),this.pendingDiffs.forEach(l=>{this.state=r.syncDiff(this.state,l,i,a);}),this.pendingDiffs=[],o();}),this.channel._on(s.diff,{},n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=r.syncDiff(this.state,n,i,a),o());}),this.onJoin((n,i,a)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:i,newPresences:a});}),this.onLeave((n,i,a)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:i,leftPresences:a});}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"});});}static syncState(e,t,s,n){let i=this.cloneDeep(e),a=this.transformState(t),o={},l={};return this.map(i,(c,u)=>{a[c]||(l[c]=u);}),this.map(a,(c,u)=>{let f=i[c];if(f){let d=u.map(_=>_.presence_ref),h=f.map(_=>_.presence_ref),p=u.filter(_=>h.indexOf(_.presence_ref)<0),g=f.filter(_=>d.indexOf(_.presence_ref)<0);p.length>0&&(o[c]=p),g.length>0&&(l[c]=g);}else o[c]=u;}),this.syncDiff(i,{joins:o,leaves:l},s,n)}static syncDiff(e,t,s,n){let{joins:i,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),n||(n=()=>{}),this.map(i,(o,l)=>{var c;let u=(c=e[o])!==null&&c!==void 0?c:[];if(e[o]=this.cloneDeep(l),u.length>0){let f=e[o].map(h=>h.presence_ref),d=u.filter(h=>f.indexOf(h.presence_ref)<0);e[o].unshift(...d);}s(o,u,l);}),this.map(a,(o,l)=>{let c=e[o];if(!c)return;let u=l.map(f=>f.presence_ref);c=c.filter(f=>u.indexOf(f.presence_ref)<0),e[o]=c,n(o,c,l),c.length===0&&delete e[o];}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let n=e[s];return "metas"in n?t[s]=n.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[s]=n,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e;}onLeave(e){this.caller.onLeave=e;}onSync(e){this.caller.onSync=e;}inPendingSyncState(){return !this.joinRef||this.joinRef!==this.channel._joinRef()}};var At;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE";})(At||(At={}));var we;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system";})(we||(we={}));var V;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR";})(V||(V={}));var be=class r{constructor(e,t={config:{}},s){var n,i;if(this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=I.closed,this.joinedOnce=false,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:false,self:false},presence:{key:"",enabled:false},private:false},t.config),this.timeout=this.socket.timeout,this.joinPush=new re(this,L.join,this.params,this.timeout),this.rejoinTimer=new te(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=I.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[];}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=I.closed,this.socket._remove(this);}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=I.errored,this.rejoinTimer.scheduleTimeout());}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=I.errored,this.rejoinTimer.scheduleTimeout());}),this.joinPush.receive("error",a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=I.errored,this.rejoinTimer.scheduleTimeout());}),this._on(L.reply,{},(a,o)=>{this._trigger(this._replyEventName(o),a);}),this.presence=new ve(this),this.broadcastEndpointURL=Ze(this.socket.endPoint),this.private=this.params.config.private||false,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===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 s,n,i;if(this.socket.isConnected()||this.socket.connect(),this.state==I.closed){let{config:{broadcast:a,presence:o,private:l}}=this.params,c=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(h=>h.filter))!==null&&n!==void 0?n:[],u=!!this.bindings[we.PRESENCE]&&this.bindings[we.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===true,f={},d={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this._onError(h=>e?.(V.CHANNEL_ERROR,h)),this._onClose(()=>e?.(V.CLOSED)),this.updateJoinPayload(Object.assign({config:d},f)),this.joinedOnce=true,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:h})=>{var p;if(this.socket._isManualToken()||this.socket.setAuth(),h===void 0){e?.(V.SUBSCRIBED);return}else {let g=this.bindings.postgres_changes,_=(p=g?.length)!==null&&p!==void 0?p:0,y=[];for(let m=0;m<_;m++){let v=g[m],{filter:{event:S,schema:P,table:k,filter:A}}=v,F=h&&h[m];if(F&&F.event===S&&r.isFilterValueEqual(F.schema,P)&&r.isFilterValueEqual(F.table,k)&&r.isFilterValueEqual(F.filter,A))y.push(Object.assign(Object.assign({},v),{id:F.id}));else {this.unsubscribe(),this.state=I.errored,e?.(V.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e(V.SUBSCRIBED);return}}).receive("error",h=>{this.state=I.errored,e?.(V.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")));}).receive("timeout",()=>{e?.(V.TIMED_OUT);});}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this.state===I.joined&&e===we.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,s)}async httpSend(e,t,s={}){var n;if(t==null)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 a={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(o.status===202)return {success:true};let l=o.statusText;try{let c=await o.json();l=c.error||c.message||l;}catch{}return Promise.reject(new Error(l))}async send(e,t={}){var s,n;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:a}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=c.body)===null||n===void 0?void 0:n.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,o,l;let c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"));})}updateJoinPayload(e){this.joinPush.updatePayload(e);}unsubscribe(e=this.timeout){this.state=I.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(L.close,"leave",this._joinRef());};this.joinPush.destroy();let s=null;return new Promise(n=>{s=new re(this,L.leave,{},e),s.receive("ok",()=>{t(),n("ok");}).receive("timeout",()=>{t(),n("timed out");}).receive("error",()=>{n("error");}),s.send(),this._canPush()||s.trigger("ok",{});}).finally(()=>{s?.destroy();})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=I.closed,this.bindings={};}async _fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(i),a}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw `tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new re(this,e,t,s);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>rr){let t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload));}}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var n,i;let a=e.toLocaleLowerCase(),{close:o,error:l,leave:c,join:u}=L;if(s&&[o,l,c,u].indexOf(a)>=0&&s!==this._joinRef())return;let d=this._onMessage(a,t,s);if(t&&!d)throw "channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(h=>{var p,g,_;return ((p=h.filter)===null||p===void 0?void 0:p.event)==="*"||((_=(g=h.filter)===null||g===void 0?void 0:g.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===a}).map(h=>h.callback(d,s)):(i=this.bindings[a])===null||i===void 0||i.filter(h=>{var p,g,_,y,m,v;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in h){let S=h.id,P=(p=h.filter)===null||p===void 0?void 0:p.event;return S&&((g=t.ids)===null||g===void 0?void 0:g.includes(S))&&(P==="*"||P?.toLocaleLowerCase()===((_=t.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else {let S=(m=(y=h?.filter)===null||y===void 0?void 0:y.event)===null||m===void 0?void 0:m.toLocaleLowerCase();return S==="*"||S===((v=t?.event)===null||v===void 0?void 0:v.toLocaleLowerCase())}else return h.type.toLocaleLowerCase()===a}).map(h=>{if(typeof d=="object"&&"ids"in d){let p=d.data,{schema:g,table:_,commit_timestamp:y,type:m,errors:v}=p;d=Object.assign(Object.assign({},{schema:g,table:_,commit_timestamp:y,eventType:m,new:{},old:{},errors:v}),this._getPayloadRecords(p));}h.callback(d,s);});}_isClosed(){return this.state===I.closed}_isJoined(){return this.state===I.joined}_isJoining(){return this.state===I.joining}_isLeaving(){return this.state===I.leaving}_replyEventName(e){return `chan_reply_${e}`}_on(e,t,s){let n=e.toLocaleLowerCase(),i={type:n,filter:t,callback:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(n=>{var i;return !(((i=n.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===s&&r.isEqual(n.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return false;for(let s in e)if(e[s]!==t[s])return false;return true}static isFilterValueEqual(e,t){return (e??void 0)===(t??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin();}_onClose(e){this._on(L.close,{},e);}_onError(e){this._on(L.error,{},t=>e(t));}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=I.joining,this.joinPush.resend(e));}_getPayloadRecords(e){let t={new:{},old:{}};return (e.type==="INSERT"||e.type==="UPDATE")&&(t.new=kt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=kt(e.columns,e.old_record)),t}};var Ot=()=>{},Xe={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},us=[1e3,2e3,5e3,1e4],hs=1e4,ds=`
|
|
9
|
+
addEventListener("message", (e) => {
|
|
10
|
+
if (e.data.event === "start") {
|
|
11
|
+
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
12
|
+
}
|
|
13
|
+
});`,Ee=class{constructor(e,t){var s;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=false,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=Ie,this.transport=null,this.heartbeatIntervalMs=Xe.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Ot,this.ref=0,this.reconnectTimer=null,this.vsn=Et,this.logger=Ot,this.conn=null,this.sendBuffer=[],this.serializer=new je,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=false,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=n=>n?(...i)=>n(...i):(...i)=>fetch(...i),!(!((s=t?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Ye.websocket}`,this.httpEndpoint=Ze(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch);}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=wt.createWebSocket(this.endpointURL());}catch(e){this._setConnectionState("disconnected");let t=e.message;throw t.includes("Node.js")?new Error(`${t}
|
|
14
|
+
|
|
15
|
+
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
16
|
+
|
|
17
|
+
Option 1: Use Node.js 22+ which has native WebSocket support
|
|
18
|
+
Option 2: Install and provide the "ws" package:
|
|
19
|
+
|
|
20
|
+
npm install ws
|
|
21
|
+
|
|
22
|
+
import ws from "ws"
|
|
23
|
+
const client = new RealtimeClient(url, {
|
|
24
|
+
...options,
|
|
25
|
+
transport: ws
|
|
26
|
+
})`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers();}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",true),this.conn){let s=setTimeout(()=>{this._setConnectionState("disconnected");},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected");},typeof this.conn.close=="function"&&(e?this.conn.close(e,t??""):this.conn.close()),this._teardownConnection();}else this._setConnectionState("disconnected");}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,s){this.logger(e,t,s);}connectionState(){switch(this.conn&&this.conn.readyState){case H.connecting:return Y.Connecting;case H.open:return Y.Open;case H.closing:return Y.Closing;default:return Y.Closed}}isConnected(){return this.connectionState()===Y.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){let s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{let i=new be(`realtime:${e}`,t,this);return this.channels.push(i),i}}push(e){let{topic:t,event:s,payload:n,ref:i}=e,a=()=>{this.encode(e,o=>{var l;(l=this.conn)===null||l===void 0||l.send(o);});};this.log("push",`${t} ${s} (${i})`,n),this.isConnected()?a():this.sendBuffer.push(a);}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise;}finally{this._authPromise=null;}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected");}catch(t){this.log("error","error in heartbeat callback",t);}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout");}catch(t){this.log("error","error in heartbeat callback",t);}this._wasManualDisconnect=false,(e=this.conn)===null||e===void 0||e.close(tr,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout();},Xe.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent");}catch(t){this.log("error","error in heartbeat callback",t);}this._setAuthSafely("heartbeat");}onHeartbeat(e){this.heartbeatCallback=e;}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[]);}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe());}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic);}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply"&&t.ref&&t.ref===this.pendingHeartbeatRef){let c=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error",c);}catch(u){this.log("error","error in heartbeat callback",u);}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null;}let{topic:s,event:n,payload:i,ref:a}=t,o=a?`(${a})`:"",l=i.status||"";this.log("receive",`${l} ${s} ${n} ${o}`.trim(),i),this.channels.filter(c=>c._isMember(s)).forEach(c=>c._trigger(n,i,a)),this._triggerStateCallbacks("message",t);});}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset());}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect");}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===H.open&&this._onConnOpen());}_teardownConnection(){if(this.conn){if(this.conn.readyState===H.open||this.conn.readyState===H.connecting)try{this.conn.close();}catch(e){this.log("error","Error closing connection",e);}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null;}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown());}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer();}).catch(t=>{this.log("error","error waiting for auth on connect",t),this.flushSendBuffer();}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open");}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this._terminateWorker();},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&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);}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e);}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error");}catch(t){this.log("error","error in heartbeat callback",t);}}_triggerChanError(){this.channels.forEach(e=>e._trigger(L.error));}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",n=new URLSearchParams(t);return `${e}${s}${n}`}_workerObjectUrl(e){let t;if(e)t=e;else {let s=new Blob([ds],{type:"application/javascript"});t=URL.createObjectURL(s);}return t}_setConnectionState(e,t=false){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=false:e==="disconnecting"&&(this._wasManualDisconnect=t);}async _performAuth(e=null){let t,s=false;if(e)t=e,s=true;else if(this.accessToken)try{t=await this.accessToken();}catch(n){this.log("error","Error fetching access token from callback",n),t=this.accessTokenValue;}else t=this.accessTokenValue;s?this._manuallySetToken=true:this.accessToken&&(this._manuallySetToken=false),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(n=>{let i={access_token:t,version:Qt};t&&n.updateJoinPayload(i),n.joinedOnce&&n._isJoined()&&n._push(L.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);});}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(t);}catch(n){this.log("error",`error in ${e} callback`,n);}});}catch(s){this.log("error",`error triggering ${e} callbacks`,s);}}_setupReconnectionTimer(){this.reconnectTimer=new te(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect();},Xe.RECONNECT_DELAY);},this.reconnectAfterMs);}_initializeOptions(e){var t,s,n,i,a,o,l,c,u,f,d,h;switch(this.transport=(t=e?.transport)!==null&&t!==void 0?t:null,this.timeout=(s=e?.timeout)!==null&&s!==void 0?s:Ie,this.heartbeatIntervalMs=(n=e?.heartbeatIntervalMs)!==null&&n!==void 0?n:Xe.HEARTBEAT_INTERVAL,this.worker=(i=e?.worker)!==null&&i!==void 0?i:false,this.accessToken=(a=e?.accessToken)!==null&&a!==void 0?a:null,this.heartbeatCallback=(o=e?.heartbeatCallback)!==null&&o!==void 0?o:Ot,this.vsn=(l=e?.vsn)!==null&&l!==void 0?l:Et,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(c=e?.reconnectAfterMs)!==null&&c!==void 0?c:(p=>us[p-1]||hs),this.vsn){case er:this.encode=(u=e?.encode)!==null&&u!==void 0?u:((p,g)=>g(JSON.stringify(p))),this.decode=(f=e?.decode)!==null&&f!==void 0?f:((p,g)=>g(JSON.parse(p)));break;case bt:this.encode=(d=e?.encode)!==null&&d!==void 0?d:this.serializer.encode.bind(this.serializer),this.decode=(h=e?.decode)!==null&&h!==void 0?h:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl;}}};var Ce=class extends Error{constructor(r,e){super(r),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===true;}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function fs(r,e,t){let s=new URL(e,r);if(t)for(let[n,i]of Object.entries(t))i!==void 0&&s.searchParams.set(n,i);return s.toString()}async function ps(r){return !r||r.type==="none"?{}:r.type==="bearer"?{Authorization:`Bearer ${r.token}`}:r.type==="header"?{[r.name]:r.value}:r.type==="custom"?await r.getHeaders():{}}function gs(r){let e=r.fetchImpl??globalThis.fetch;return {async request({method:t,path:s,query:n,body:i,headers:a}){let o=fs(r.baseUrl,s,n),l=await ps(r.auth),c=await e(o,{method:t,headers:{...i?{"Content-Type":"application/json"}:{},...l,...a},body:i?JSON.stringify(i):void 0}),u=await c.text(),f=(c.headers.get("content-type")||"").includes("application/json"),d=f&&u?JSON.parse(u):u;if(!c.ok){let h=f?d:void 0,p=h?.error;throw new Ce(p?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:p?.type,icebergCode:p?.code,details:h})}return {status:c.status,headers:c.headers,data:d}}}}function Qe(r){return r.join("")}var _s=class{constructor(r,e=""){this.client=r,this.prefix=e;}async listNamespaces(r){let e=r?{parent:Qe(r.namespace)}:void 0;return (await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(r,e){let t={namespace:r.namespace,properties:e?.properties};return (await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:t})).data}async dropNamespace(r){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Qe(r.namespace)}`});}async loadNamespaceMetadata(r){return {properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qe(r.namespace)}`})).data.properties}}async namespaceExists(r){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Qe(r.namespace)}`}),!0}catch(e){if(e instanceof Ce&&e.status===404)return false;throw e}}async createNamespaceIfNotExists(r,e){try{return await this.createNamespace(r,e)}catch(t){if(t instanceof Ce&&t.status===409)return;throw t}}};function Se(r){return r.join("")}var ys=class{constructor(r,e="",t){this.client=r,this.prefix=e,this.accessDelegation=t;}async listTables(r){return (await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Se(r.namespace)}/tables`})).data.identifiers}async createTable(r,e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Se(r.namespace)}/tables`,body:e,headers:t})).data.metadata}async updateTable(r,e){let t=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Se(r.namespace)}/tables/${r.name}`,body:e});return {"metadata-location":t.data["metadata-location"],metadata:t.data.metadata}}async dropTable(r,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Se(r.namespace)}/tables/${r.name}`,query:{purgeRequested:String(e?.purge??false)}});}async loadTable(r){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Se(r.namespace)}/tables/${r.name}`,headers:e})).data.metadata}async tableExists(r){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Se(r.namespace)}/tables/${r.name}`,headers:e}),!0}catch(t){if(t instanceof Ce&&t.status===404)return false;throw t}}async createTableIfNotExists(r,e){try{return await this.createTable(r,e)}catch(t){if(t instanceof Ce&&t.status===409)return await this.loadTable({namespace:r.namespace,name:e.name});throw t}}},nr=class{constructor(r){let e="v1";r.catalogName&&(e+=`/${r.catalogName}`);let t=r.baseUrl.endsWith("/")?r.baseUrl:`${r.baseUrl}/`;this.client=gs({baseUrl:t,auth:r.auth,fetchImpl:r.fetch}),this.accessDelegation=r.accessDelegation?.join(","),this.namespaceOps=new _s(this.client,e),this.tableOps=new ys(this.client,e,this.accessDelegation);}async listNamespaces(r){return this.namespaceOps.listNamespaces(r)}async createNamespace(r,e){return this.namespaceOps.createNamespace(r,e)}async dropNamespace(r){await this.namespaceOps.dropNamespace(r);}async loadNamespaceMetadata(r){return this.namespaceOps.loadNamespaceMetadata(r)}async listTables(r){return this.tableOps.listTables(r)}async createTable(r,e){return this.tableOps.createTable(r,e)}async updateTable(r,e){return this.tableOps.updateTable(r,e)}async dropTable(r,e){await this.tableOps.dropTable(r,e);}async loadTable(r){return this.tableOps.loadTable(r)}async namespaceExists(r){return this.namespaceOps.namespaceExists(r)}async tableExists(r){return this.tableOps.tableExists(r)}async createNamespaceIfNotExists(r,e){return this.namespaceOps.createNamespaceIfNotExists(r,e)}async createTableIfNotExists(r,e){return this.tableOps.createTableIfNotExists(r,e)}};var tt=class extends Error{constructor(r,e="storage",t,s){super(r),this.__isStorageError=true,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=t,this.statusCode=s;}};function rt(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var et=class extends tt{constructor(r,e,t,s="storage"){super(r,s,e,t),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=t;}toJSON(){return {name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},lr=class extends tt{constructor(r,e,t="storage"){super(r,t),this.name=t==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e;}};var ms=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),vs=r=>{if(typeof r!="object"||r===null)return false;let e=Object.getPrototypeOf(r);return (e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)},Rt=r=>{if(Array.isArray(r))return r.map(t=>Rt(t));if(typeof r=="function"||r!==Object(r))return r;let e={};return Object.entries(r).forEach(([t,s])=>{let n=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=Rt(s);}),e},ws=r=>!r||typeof r!="string"||r.length===0||r.length>100||r.trim()!==r||r.includes("/")||r.includes("\\")?false:/^[\w!.\*'() &$@=;:+,?-]+$/.test(r);function Ue(r){"@babel/helpers - typeof";return Ue=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ue(r)}function bs(r,e){if(Ue(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(Ue(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(r)}function Es(r){var e=bs(r,"string");return Ue(e)=="symbol"?e:e+""}function Ss(r,e,t){return (e=Es(e))in r?Object.defineProperty(r,e,{value:t,enumerable:true,configurable:true,writable:true}):r[e]=t,r}function ir(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(r,n).enumerable})),t.push.apply(t,s);}return t}function E(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ir(Object(t),true).forEach(function(s){Ss(r,s,t[s]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):ir(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s));});}return r}var ar=r=>{var e;return r.msg||r.message||r.error_description||(typeof r.error=="string"?r.error:(e=r.error)===null||e===void 0?void 0:e.message)||JSON.stringify(r)},ks=async(r,e,t,s)=>{if(r&&typeof r=="object"&&"status"in r&&"ok"in r&&typeof r.status=="number"&&!t?.noResolveJson){let n=r,i=n.status||500;if(typeof n.json=="function")n.json().then(a=>{let o=a?.statusCode||a?.code||i+"";e(new et(ar(a),i,o,s));}).catch(()=>{if(s==="vectors"){let a=i+"";e(new et(n.statusText||`HTTP ${i} error`,i,a,s));}else {let a=i+"";e(new et(n.statusText||`HTTP ${i} error`,i,a,s));}});else {let a=i+"";e(new et(n.statusText||`HTTP ${i} error`,i,a,s));}}else e(new lr(ar(r),r,s));},Ts=(r,e,t,s)=>{let n={method:r,headers:e?.headers||{}};return r==="GET"||r==="HEAD"||!s?E(E({},n),t):(vs(s)?(n.headers=E({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(s)):n.body=s,e?.duplex&&(n.duplex=e.duplex),E(E({},n),t))};async function $e(r,e,t,s,n,i,a){return new Promise((o,l)=>{r(t,Ts(e,s,n,i)).then(c=>{if(!c.ok)throw c;if(s?.noResolveJson)return c;if(a==="vectors"){let u=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return {};if(!u||!u.includes("application/json"))return {}}return c.json()}).then(c=>o(c)).catch(c=>ks(c,l,s,a));})}function cr(r="storage"){return {get:async(e,t,s,n)=>$e(e,"GET",t,s,n,void 0,r),post:async(e,t,s,n,i)=>$e(e,"POST",t,n,i,s,r),put:async(e,t,s,n,i)=>$e(e,"PUT",t,n,i,s,r),head:async(e,t,s,n)=>$e(e,"HEAD",t,E(E({},s),{},{noResolveJson:true}),n,void 0,r),remove:async(e,t,s,n,i)=>$e(e,"DELETE",t,n,i,s,r)}}var As=cr("storage"),{get:Le,post:K,put:xt,head:Os,remove:Pt}=As,N=cr("vectors"),ke=class{constructor(r,e={},t,s="storage"){this.shouldThrowOnError=false,this.url=r,this.headers=e,this.fetch=ms(t),this.namespace=s;}throwOnError(){return this.shouldThrowOnError=true,this}setHeader(r,e){return this.headers=E(E({},this.headers),{},{[r]:e}),this}async handleOperation(r){var e=this;try{return {data:await r(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(rt(t))return {data:null,error:t};throw t}}},Rs=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e;}then(r,e){return this.execute().then(r,e)}async execute(){var r=this;try{return {data:(await r.downloadFn()).body,error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(rt(e))return {data:null,error:e};throw e}}},ur;ur=Symbol.toStringTag;var xs=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e,this[ur]="BlobDownloadBuilder",this.promise=null;}asStream(){return new Rs(this.downloadFn,this.shouldThrowOnError)}then(r,e){return this.getPromise().then(r,e)}catch(r){return this.getPromise().catch(r)}finally(r){return this.getPromise().finally(r)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var r=this;try{return {data:await(await r.downloadFn()).blob(),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(rt(e))return {data:null,error:e};throw e}}},Ps={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},or={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:false},Is=class extends ke{constructor(r,e={},t,s){super(r,e,s,"storage"),this.bucketId=t;}async uploadOrUpdate(r,e,t,s){var n=this;return n.handleOperation(async()=>{let i,a=E(E({},or),s),o=E(E({},n.headers),r==="POST"&&{"x-upsert":String(a.upsert)}),l=a.metadata;typeof Blob<"u"&&t instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",t)):typeof FormData<"u"&&t instanceof FormData?(i=t,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=t,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),s?.headers&&(o=E(E({},o),s.headers));let c=n._removeEmptyFolders(e),u=n._getFinalPath(c),f=await(r=="PUT"?xt:K)(n.fetch,`${n.url}/object/${u}`,i,E({headers:o},a?.duplex?{duplex:a.duplex}:{}));return {path:c,id:f.Id,fullPath:f.Key}})}async upload(r,e,t){return this.uploadOrUpdate("POST",r,e,t)}async uploadToSignedUrl(r,e,t,s){var n=this;let i=n._removeEmptyFolders(r),a=n._getFinalPath(i),o=new URL(n.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),n.handleOperation(async()=>{let l,c=E({upsert:or.upsert},s),u=E(E({},n.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&t instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",t)):typeof FormData<"u"&&t instanceof FormData?(l=t,l.append("cacheControl",c.cacheControl)):(l=t,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType),{path:i,fullPath:(await xt(n.fetch,o.toString(),l,{headers:u})).Key}})}async createSignedUploadUrl(r,e){var t=this;return t.handleOperation(async()=>{let s=t._getFinalPath(r),n=E({},t.headers);e?.upsert&&(n["x-upsert"]="true");let i=await K(t.fetch,`${t.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(t.url+i.url),o=a.searchParams.get("token");if(!o)throw new tt("No token returned by API");return {signedUrl:a.toString(),path:r,token:o}})}async update(r,e,t){return this.uploadOrUpdate("PUT",r,e,t)}async move(r,e,t){var s=this;return s.handleOperation(async()=>await K(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:r,destinationKey:e,destinationBucket:t?.destinationBucket},{headers:s.headers}))}async copy(r,e,t){var s=this;return s.handleOperation(async()=>({path:(await K(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:r,destinationKey:e,destinationBucket:t?.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(r,e,t){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(r),i=await K(s.fetch,`${s.url}/object/sign/${n}`,E({expiresIn:e},t?.transform?{transform:t.transform}:{}),{headers:s.headers}),a=t?.download?`&download=${t.download===true?"":t.download}`:"";return {signedUrl:encodeURI(`${s.url}${i.signedURL}${a}`)}})}async createSignedUrls(r,e,t){var s=this;return s.handleOperation(async()=>{let n=await K(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:r},{headers:s.headers}),i=t?.download?`&download=${t.download===true?"":t.download}`:"";return n.map(a=>E(E({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${i}`):null}))})}download(r,e,t){let s=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),i=n?`?${n}`:"",a=this._getFinalPath(r),o=()=>Le(this.fetch,`${this.url}/${s}/${a}${i}`,{headers:this.headers,noResolveJson:true},t);return new xs(o,this.shouldThrowOnError)}async info(r){var e=this;let t=e._getFinalPath(r);return e.handleOperation(async()=>Rt(await Le(e.fetch,`${e.url}/object/info/${t}`,{headers:e.headers})))}async exists(r){var e=this;let t=e._getFinalPath(r);try{return await Os(e.fetch,`${e.url}/object/${t}`,{headers:e.headers}),{data:!0,error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(rt(s)&&s instanceof lr){let n=s.originalError;if([400,404].includes(n?.status))return {data:false,error:s}}throw s}}getPublicUrl(r,e){let t=this._getFinalPath(r),s=[],n=e?.download?`download=${e.download===true?"":e.download}`:"";n!==""&&s.push(n);let i=typeof e?.transform<"u"?"render/image":"object",a=this.transformOptsToQueryString(e?.transform||{});a!==""&&s.push(a);let o=s.join("&");return o!==""&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${t}${o}`)}}}async remove(r){var e=this;return e.handleOperation(async()=>await Pt(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:r},{headers:e.headers}))}async list(r,e,t){var s=this;return s.handleOperation(async()=>{let n=E(E(E({},Ps),e),{},{prefix:r||""});return await K(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},t)})}async listV2(r,e){var t=this;return t.handleOperation(async()=>{let s=E({},r);return await K(t.fetch,`${t.url}/object/list-v2/${t.bucketId}`,s,{headers:t.headers},e)})}encodeMetadata(r){return JSON.stringify(r)}toBase64(r){return typeof Buffer<"u"?Buffer.from(r).toString("base64"):btoa(r)}_getFinalPath(r){return `${this.bucketId}/${r.replace(/^\/+/,"")}`}_removeEmptyFolders(r){return r.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(r){let e=[];return r.width&&e.push(`width=${r.width}`),r.height&&e.push(`height=${r.height}`),r.resize&&e.push(`resize=${r.resize}`),r.format&&e.push(`format=${r.format}`),r.quality&&e.push(`quality=${r.quality}`),e.join("&")}},js="2.96.0",Ne={"X-Client-Info":`storage-js/${js}`},Cs=class extends ke{constructor(r,e={},t,s){let n=new URL(r);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let i=n.href.replace(/\/$/,""),a=E(E({},Ne),e);super(i,a,t,"storage");}async listBuckets(r){var e=this;return e.handleOperation(async()=>{let t=e.listBucketOptionsToQueryString(r);return await Le(e.fetch,`${e.url}/bucket${t}`,{headers:e.headers})})}async getBucket(r){var e=this;return e.handleOperation(async()=>await Le(e.fetch,`${e.url}/bucket/${r}`,{headers:e.headers}))}async createBucket(r,e={public:false}){var t=this;return t.handleOperation(async()=>await K(t.fetch,`${t.url}/bucket`,{id:r,name:r,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}))}async updateBucket(r,e){var t=this;return t.handleOperation(async()=>await xt(t.fetch,`${t.url}/bucket/${r}`,{id:r,name:r,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}))}async emptyBucket(r){var e=this;return e.handleOperation(async()=>await K(e.fetch,`${e.url}/bucket/${r}/empty`,{},{headers:e.headers}))}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await Pt(e.fetch,`${e.url}/bucket/${r}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(r){let e={};return r&&("limit"in r&&(e.limit=String(r.limit)),"offset"in r&&(e.offset=String(r.offset)),r.search&&(e.search=r.search),r.sortColumn&&(e.sortColumn=r.sortColumn),r.sortOrder&&(e.sortOrder=r.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},$s=class extends ke{constructor(r,e={},t){let s=r.replace(/\/$/,""),n=E(E({},Ne),e);super(s,n,t,"storage");}async createBucket(r){var e=this;return e.handleOperation(async()=>await K(e.fetch,`${e.url}/bucket`,{name:r},{headers:e.headers}))}async listBuckets(r){var e=this;return e.handleOperation(async()=>{let t=new URLSearchParams;r?.limit!==void 0&&t.set("limit",r.limit.toString()),r?.offset!==void 0&&t.set("offset",r.offset.toString()),r?.sortColumn&&t.set("sortColumn",r.sortColumn),r?.sortOrder&&t.set("sortOrder",r.sortOrder),r?.search&&t.set("search",r.search);let s=t.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Le(e.fetch,n,{headers:e.headers})})}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await Pt(e.fetch,`${e.url}/bucket/${r}`,{},{headers:e.headers}))}from(r){var e=this;if(!ws(r))throw new tt("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 t=new nr({baseUrl:this.url,catalogName:r,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(t,{get(n,i){let a=n[i];return typeof a!="function"?a:async(...o)=>{try{return {data:await a.apply(n,o),error:null}}catch(l){if(s)throw l;return {data:null,error:l}}}}})}},Us=class extends ke{constructor(r,e={},t){let s=r.replace(/\/$/,""),n=E(E({},Ne),{},{"Content-Type":"application/json"},e);super(s,n,t,"vectors");}async createIndex(r){var e=this;return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/CreateIndex`,r,{headers:e.headers})||{})}async getIndex(r,e){var t=this;return t.handleOperation(async()=>await N.post(t.fetch,`${t.url}/GetIndex`,{vectorBucketName:r,indexName:e},{headers:t.headers}))}async listIndexes(r){var e=this;return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/ListIndexes`,r,{headers:e.headers}))}async deleteIndex(r,e){var t=this;return t.handleOperation(async()=>await N.post(t.fetch,`${t.url}/DeleteIndex`,{vectorBucketName:r,indexName:e},{headers:t.headers})||{})}},Ls=class extends ke{constructor(r,e={},t){let s=r.replace(/\/$/,""),n=E(E({},Ne),{},{"Content-Type":"application/json"},e);super(s,n,t,"vectors");}async putVectors(r){var e=this;if(r.vectors.length<1||r.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/PutVectors`,r,{headers:e.headers})||{})}async getVectors(r){var e=this;return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/GetVectors`,r,{headers:e.headers}))}async listVectors(r){var e=this;if(r.segmentCount!==void 0){if(r.segmentCount<1||r.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(r.segmentIndex!==void 0&&(r.segmentIndex<0||r.segmentIndex>=r.segmentCount))throw new Error(`segmentIndex must be between 0 and ${r.segmentCount-1}`)}return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/ListVectors`,r,{headers:e.headers}))}async queryVectors(r){var e=this;return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/QueryVectors`,r,{headers:e.headers}))}async deleteVectors(r){var e=this;if(r.keys.length<1||r.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/DeleteVectors`,r,{headers:e.headers})||{})}},Ns=class extends ke{constructor(r,e={},t){let s=r.replace(/\/$/,""),n=E(E({},Ne),{},{"Content-Type":"application/json"},e);super(s,n,t,"vectors");}async createBucket(r){var e=this;return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:r},{headers:e.headers})||{})}async getBucket(r){var e=this;return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:r},{headers:e.headers}))}async listBuckets(r={}){var e=this;return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/ListVectorBuckets`,r,{headers:e.headers}))}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await N.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:r},{headers:e.headers})||{})}},Ds=class extends Ns{constructor(r,e={}){super(r,e.headers||{},e.fetch);}from(r){return new Bs(this.url,this.headers,r,this.fetch)}async createBucket(r){var e=()=>super.createBucket,t=this;return e().call(t,r)}async getBucket(r){var e=()=>super.getBucket,t=this;return e().call(t,r)}async listBuckets(r={}){var e=()=>super.listBuckets,t=this;return e().call(t,r)}async deleteBucket(r){var e=()=>super.deleteBucket,t=this;return e().call(t,r)}},Bs=class extends Us{constructor(r,e,t,s){super(r,e,s),this.vectorBucketName=t;}async createIndex(r){var e=()=>super.createIndex,t=this;return e().call(t,E(E({},r),{},{vectorBucketName:t.vectorBucketName}))}async listIndexes(r={}){var e=()=>super.listIndexes,t=this;return e().call(t,E(E({},r),{},{vectorBucketName:t.vectorBucketName}))}async getIndex(r){var e=()=>super.getIndex,t=this;return e().call(t,t.vectorBucketName,r)}async deleteIndex(r){var e=()=>super.deleteIndex,t=this;return e().call(t,t.vectorBucketName,r)}index(r){return new qs(this.url,this.headers,this.vectorBucketName,r,this.fetch)}},qs=class extends Ls{constructor(r,e,t,s,n){super(r,e,n),this.vectorBucketName=t,this.indexName=s;}async putVectors(r){var e=()=>super.putVectors,t=this;return e().call(t,E(E({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(r){var e=()=>super.getVectors,t=this;return e().call(t,E(E({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(r={}){var e=()=>super.listVectors,t=this;return e().call(t,E(E({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(r){var e=()=>super.queryVectors,t=this;return e().call(t,E(E({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(r){var e=()=>super.deleteVectors,t=this;return e().call(t,E(E({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},hr=class extends Cs{constructor(r,e={},t,s){super(r,e,t,s);}from(r){return new Is(this.url,this.headers,r,this.fetch)}get vectors(){return new Ds(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new $s(this.url+"/iceberg",this.headers,this.fetch)}};var st="2.96.0";var se=30*1e3,nt=3,it=nt*se,dr="http://localhost:9999",fr="supabase.auth.token";var pr={"X-Client-Info":`gotrue-js/${st}`};var De="X-Supabase-Api-Version",It={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},gr=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,_r=600*1e3;var Z=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=true,this.name="AuthError",this.status=t,this.code=s;}};function w(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var at=class extends Z{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s;}};function yr(r){return w(r)&&r.name==="AuthApiError"}var B=class extends Z{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t;}},M=class extends Z{constructor(e,t,s,n){super(e,s,n),this.name=t,this.status=s;}},$=class extends M{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0);}};function lt(r){return w(r)&&r.name==="AuthSessionMissingError"}var G=class extends M{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0);}},ne=class extends M{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0);}},ie=class extends M{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t;}toJSON(){return {name:this.name,message:this.message,status:this.status,details:this.details}}};function mr(r){return w(r)&&r.name==="AuthImplicitGrantRedirectError"}var Be=class extends M{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}}},ot=class extends M{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");}};var Te=class extends M{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0);}};function ct(r){return w(r)&&r.name==="AuthRetryableFetchError"}var qe=class extends M{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s;}};var ae=class extends M{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt");}};var ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),vr=`
|
|
27
|
+
\r=`.split(""),Fs=(()=>{let r=new Array(128);for(let e=0;e<r.length;e+=1)r[e]=-1;for(let e=0;e<vr.length;e+=1)r[vr[e].charCodeAt(0)]=-2;for(let e=0;e<ut.length;e+=1)r[ut[e].charCodeAt(0)]=e;return r})();function wr(r,e,t){if(r!==null)for(e.queue=e.queue<<8|r,e.queuedBits+=8;e.queuedBits>=6;){let s=e.queue>>e.queuedBits-6&63;t(ut[s]),e.queuedBits-=6;}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let s=e.queue>>e.queuedBits-6&63;t(ut[s]),e.queuedBits-=6;}}function br(r,e,t){let s=Fs[r];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else {if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function jt(r){let e=[],t=a=>{e.push(String.fromCodePoint(a));},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{Vs(a,s,t);};for(let a=0;a<r.length;a+=1)br(r.charCodeAt(a),n,i);return e.join("")}function Ks(r,e){if(r<=127){e(r);return}else if(r<=2047){e(192|r>>6),e(128|r&63);return}else if(r<=65535){e(224|r>>12),e(128|r>>6&63),e(128|r&63);return}else if(r<=1114111){e(240|r>>18),e(128|r>>12&63),e(128|r>>6&63),e(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function Ms(r,e){for(let t=0;t<r.length;t+=1){let s=r.charCodeAt(t);if(s>55295&&s<=56319){let n=(s-55296)*1024&65535;s=(r.charCodeAt(t+1)-56320&65535|n)+65536,t+=1;}Ks(s,e);}}function Vs(r,e,t){if(e.utf8seq===0){if(r<=127){t(r);return}for(let s=1;s<6;s+=1)if((r>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=r&31;else if(e.utf8seq===3)e.codepoint=r&15;else if(e.utf8seq===4)e.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1;}else if(e.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|r&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint);}}function X(r){let e=[],t={queue:0,queuedBits:0},s=n=>{e.push(n);};for(let n=0;n<r.length;n+=1)br(r.charCodeAt(n),t,s);return new Uint8Array(e)}function Er(r){let e=[];return Ms(r,t=>e.push(t)),new Uint8Array(e)}function z(r){let e=[],t={queue:0,queuedBits:0},s=n=>{e.push(n);};return r.forEach(n=>wr(n,t,s)),wr(null,t,s),e.join("")}function Sr(r){return Math.round(Date.now()/1e3)+r}function kr(){return Symbol("auth-callback")}var j=()=>typeof window<"u"&&typeof document<"u",oe={tested:false,writable:false},ht=()=>{if(!j())return false;try{if(typeof globalThis.localStorage!="object")return !1}catch{return false}if(oe.tested)return oe.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),oe.tested=!0,oe.writable=!0;}catch{oe.tested=true,oe.writable=false;}return oe.writable};function Tr(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((n,i)=>{e[i]=n;});}catch{}return t.searchParams.forEach((s,n)=>{e[n]=s;}),e}var dt=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),Ar=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",le=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t));},Q=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},C=async(r,e)=>{await r.removeItem(e);},Fe=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t;});}};Fe.promiseConstructor=Promise;function Ke(r){let e=r.split(".");if(e.length!==3)throw new ae("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!gr.test(e[s]))throw new ae("JWT not in base64url format");return {header:JSON.parse(jt(e[0])),payload:JSON.parse(jt(e[1])),signature:X(e[2]),raw:{header:e[0],payload:e[1]}}}async function Or(r){return await new Promise(e=>{setTimeout(()=>e(null),r);})}function Rr(r,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{let a=await r(i);if(!e(i,null,a)){s(a);return}}catch(a){if(!e(i,a)){n(a);return}}})();})}function Ws(r){return ("0"+r.toString(16)).substr(-2)}function Hs(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,n="";for(let i=0;i<56;i++)n+=t.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,Ws).join("")}async function Gs(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function zs(r){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;let t=await Gs(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ce(r,e,t=false){let s=Hs(),n=s;t&&(n+="/PASSWORD_RECOVERY"),await le(r,`${e}-code-verifier`,n);let i=await zs(s);return [i,s===i?"plain":"s256"]}var Js=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function xr(r){let e=r.headers.get(De);if(!e||!e.match(Js))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Pr(r){if(!r)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(r<=e)throw new Error("JWT has expired")}function Ir(r){switch(r){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 new Error("Invalid alg claim")}}var Ys=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ue(r){if(!Ys.test(r))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ft(){let r={};return new Proxy(r,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return true;if(typeof t=="symbol"){let s=t.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new 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 new 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 new 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 jr(r,e){return new Proxy(r,{get:(t,s,n)=>{if(s==="__isInsecureUserWarningProxy")return true;if(typeof s=="symbol"){let i=s.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,s,n)}return !e.value&&typeof s=="string"&&(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."),e.value=true),Reflect.get(t,s,n)}})}function Ct(r){return JSON.parse(JSON.stringify(r))}var he=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Zs=[502,503,504];async function Cr(r){var e;if(!Ar(r))throw new Te(he(r),0);if(Zs.includes(r.status))throw new Te(he(r),r.status);let t;try{t=await r.json();}catch(i){throw new B(he(i),i)}let s,n=xr(r);if(n&&n.getTime()>=It["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new qe(he(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new $}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",true))throw new qe(he(t),r.status,t.weak_password.reasons);throw new at(he(t),r.status||500,s)}var Xs=(r,e,t,s)=>{let n={method:r,headers:e?.headers||{}};return r==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),t))};async function b(r,e,t,s){var n;let i=Object.assign({},s?.headers);i[De]||(i[De]=It["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);let a=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(a.redirect_to=s.redirectTo);let o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await Qs(r,e,t+o,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function Qs(r,e,t,s,n,i){let a=Xs(e,s,n,i),o;try{o=await r(t,Object.assign({},a));}catch(l){throw console.error(l),new Te(he(l),0)}if(o.ok||await Cr(o),s?.noResolveJson)return o;try{return await o.json()}catch(l){await Cr(l);}}function q(r){var e;let t=null;en(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Sr(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return {data:{session:t,user:s},error:null}}function $t(r){let e=q(r);return !e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",true)&&(e.data.weak_password=r.weak_password),e}function W(r){var e;return {data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function $r(r){return {data:r,error:null}}function Ur(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:i}=r,a=ee(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:i},l=Object.assign({},a);return {data:{properties:o,user:l},error:null}}function Ut(r){return r}function en(r){return r.access_token&&r.refresh_token&&r.expires_in}var pt=["global","local","others"];var de=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=dt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)};}async signOut(e,t=pt[0]){if(pt.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${pt.join(", ")}`);try{return await b(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(w(s))return {data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await b(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:W})}catch(s){if(w(s))return {data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=ee(e,["options"]),n=Object.assign(Object.assign({},s),t);return "newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await b(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Ur,redirectTo:t?.redirectTo})}catch(t){if(w(t))return {data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await b(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:W})}catch(t){if(w(t))return {data:{user:null},error:t};throw t}}async listUsers(e){var t,s,n,i,a,o,l;try{let c={nextPage:null,lastPage:0,total:0},u=await b(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Ut});if(u.error)throw u.error;let f=await u.json(),d=(a=u.headers.get("x-total-count"))!==null&&a!==void 0?a:0,h=(l=(o=u.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(p=>{let g=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(p.split(";")[1].split("=")[1]);c[`${_}Page`]=g;}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},f),c),error:null}}catch(c){if(w(c))return {data:{users:[]},error:c};throw c}}async getUserById(e){ue(e);try{return await b(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:W})}catch(t){if(w(t))return {data:{user:null},error:t};throw t}}async updateUserById(e,t){ue(e);try{return await b(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:W})}catch(s){if(w(s))return {data:{user:null},error:s};throw s}}async deleteUser(e,t=false){ue(e);try{return await b(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:W})}catch(s){if(w(s))return {data:{user:null},error:s};throw s}}async _listFactors(e){ue(e.userId);try{let{data:t,error:s}=await b(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return {data:t,error:s}}catch(t){if(w(t))return {data:null,error:t};throw t}}async _deleteFactor(e){ue(e.userId),ue(e.id);try{return {data:await b(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return {data:null,error:t};throw t}}async _listOAuthClients(e){var t,s,n,i,a,o,l;try{let c={nextPage:null,lastPage:0,total:0},u=await b(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Ut});if(u.error)throw u.error;let f=await u.json(),d=(a=u.headers.get("x-total-count"))!==null&&a!==void 0?a:0,h=(l=(o=u.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(p=>{let g=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(p.split(";")[1].split("=")[1]);c[`${_}Page`]=g;}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},f),c),error:null}}catch(c){if(w(c))return {data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await b(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return {data:null,error:t};throw t}}async _getOAuthClient(e){try{return await b(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return {data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await b(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(w(s))return {data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await b(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return {data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await b(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return {data:null,error:t};throw t}}};function Lt(r={}){return {getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t;},removeItem:e=>{delete r[e];}}}var fe={debug:!!(globalThis&&ht()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Me=class extends Error{constructor(e){super(e),this.isAcquireTimeout=true;}},Ve=class extends Me{};async function Nt(r,e,t){fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;e>0&&setTimeout(()=>{s.abort(),fe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r);},e),await Promise.resolve();try{return await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async n=>{if(n){fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,n.name);try{return await t()}finally{fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,n.name);}}else {if(e===0)throw fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Ve(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(fe.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "));}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i);}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}catch(n){throw n?.name==="AbortError"?new Ve(`Acquiring an exclusive Navigator LockManager lock "${r}" timed out waiting ${e}ms`):n}}function Lr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__;}catch{typeof self<"u"&&(self.globalThis=self);}}function Dt(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))throw new Error(`@supabase/auth-js: Address "${r}" is invalid.`);return r.toLowerCase()}function Nr(r){return parseInt(r,16)}function Dr(r){let e=new TextEncoder().encode(r);return "0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function Br(r){var e;let{chainId:t,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:l,resources:c,scheme:u,uri:f,version:d}=r;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(d!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(!((e=r.statement)===null||e===void 0)&&e.includes(`
|
|
28
|
+
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${r.statement}`)}let h=Dt(r.address),p=u?`${u}://${s}`:s,g=r.statement?`${r.statement}
|
|
29
|
+
`:"",_=`${p} wants you to sign in with your Ethereum account:
|
|
30
|
+
${h}
|
|
31
|
+
|
|
32
|
+
${g}`,y=`URI: ${f}
|
|
33
|
+
Version: ${d}
|
|
34
|
+
Chain ID: ${t}${a?`
|
|
35
|
+
Nonce: ${a}`:""}
|
|
36
|
+
Issued At: ${i.toISOString()}`;if(n&&(y+=`
|
|
37
|
+
Expiration Time: ${n.toISOString()}`),o&&(y+=`
|
|
38
|
+
Not Before: ${o.toISOString()}`),l&&(y+=`
|
|
39
|
+
Request ID: ${l}`),c){let m=`
|
|
40
|
+
Resources:`;for(let v of c){if(!v||typeof v!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${v}`);m+=`
|
|
41
|
+
- ${v}`;}y+=m;}return `${_}
|
|
42
|
+
${y}`}var O=class extends Error{constructor({message:e,code:t,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=true,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t;}},pe=class extends O{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t;}};function qr({error:r,options:e}){var t,s,n;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new O({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===true)return new O({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new O({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new O({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else {if(r.name==="InvalidStateError")return new O({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new O({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new O({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new O({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){let a=window.location.hostname;if(Bt(a)){if(i.rp.id!==a)return new O({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new O({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new O({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new O({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new O({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}function Fr({error:r,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new O({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else {if(r.name==="NotAllowedError")return new O({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){let s=window.location.hostname;if(Bt(s)){if(t.rpId!==s)return new O({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new O({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new O({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new O({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}var qt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t);}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0;}}},tn=new qt;function Mr(r){if(!r)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(r);let{challenge:e,user:t,excludeCredentials:s}=r,n=ee(r,["challenge","user","excludeCredentials"]),i=X(e).buffer,a=Object.assign(Object.assign({},t),{id:X(t.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){let c=s[l];o.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:X(c.id).buffer,type:c.type||"public-key",transports:c.transports});}}return o}function Vr(r){if(!r)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(r);let{challenge:e,allowCredentials:t}=r,s=ee(r,["challenge","allowCredentials"]),n=X(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(t&&t.length>0){i.allowCredentials=new Array(t.length);for(let a=0;a<t.length;a++){let o=t[a];i.allowCredentials[a]=Object.assign(Object.assign({},o),{id:X(o.id).buffer,type:o.type||"public-key",transports:o.transports});}}return i}function Wr(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();let t=r;return {id:r.id,rawId:r.id,response:{attestationObject:z(new Uint8Array(r.response.attestationObject)),clientDataJSON:z(new Uint8Array(r.response.clientDataJSON))},type:"public-key",clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Hr(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();let t=r,s=r.getClientExtensionResults(),n=r.response;return {id:r.id,rawId:r.id,response:{authenticatorData:z(new Uint8Array(n.authenticatorData)),clientDataJSON:z(new Uint8Array(n.clientDataJSON)),signature:z(new Uint8Array(n.signature)),userHandle:n.userHandle?z(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Bt(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}function Kr(){var r,e;return !!(j()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((r=navigator?.credentials)===null||r===void 0?void 0:r.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function rn(r){try{let e=await navigator.credentials.create(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new pe("Browser returned unexpected credential type",e)}:{data:null,error:new pe("Empty credential response",e)}}catch(e){return {data:null,error:qr({error:e,options:r})}}}async function sn(r){try{let e=await navigator.credentials.get(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new pe("Browser returned unexpected credential type",e)}:{data:null,error:new pe("Empty credential response",e)}}catch(e){return {data:null,error:Fr({error:e,options:r})}}}var nn={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:false,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},an={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function gt(...r){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),t=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(let n of r)if(n)for(let i in n){let a=n[i];if(a!==void 0)if(Array.isArray(a))s[i]=a;else if(t(a))s[i]=a;else if(e(a)){let o=s[i];e(o)?s[i]=gt(o,a):s[i]=gt(a);}else s[i]=a;}return s}function on(r,e){return gt(nn,r,e||{})}function ln(r,e){return gt(an,r,e||{})}var _t=class{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:s,signal:n},i){var a;try{let{data:o,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!o)return {data:null,error:l};let c=n??tn.createNewAbortSignal();if(o.webauthn.type==="create"){let{user:u}=o.webauthn.credential_options.publicKey;if(!u.name){let f=s;if(f)u.name=`${u.id}:${f}`;else {let h=(await this.client.getUser()).data.user,p=((a=h?.user_metadata)===null||a===void 0?void 0:a.name)||h?.email||h?.id||"User";u.name=`${u.id}:${p}`;}}u.displayName||(u.displayName=u.name);}switch(o.webauthn.type){case "create":{let u=on(o.webauthn.credential_options.publicKey,i?.create),{data:f,error:d}=await rn({publicKey:u,signal:c});return f?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:f}},error:null}:{data:null,error:d}}case "request":{let u=ln(o.webauthn.credential_options.publicKey,i?.request),{data:f,error:d}=await sn(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:u,signal:c}));return f?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:f}},error:null}:{data:null,error:d}}}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new B("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:t,webauthn:s}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!t)return {data:null,error:new Z("rpId is required for WebAuthn authentication")};try{if(!Kr())return {data:null,error:new B("Browser does not support WebAuthn",null)};let{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:s},signal:n},{request:i});if(!a)return {data:null,error:o};let{webauthn:l}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:l.type,rpId:t,rpOrigins:s,credential_response:l.credential_response}})}catch(a){return w(a)?{data:null,error:a}:{data:null,error:new B("Unexpected error in authenticate",a)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!t)return {data:null,error:new Z("rpId is required for WebAuthn registration")};try{if(!Kr())return {data:null,error:new B("Browser does not support WebAuthn",null)};let{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(u=>{var f;return (f=u.data)===null||f===void 0?void 0:f.all.find(d=>d.factor_type==="webauthn"&&d.friendly_name===e&&d.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:o};let{data:l,error:c}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:t,rpOrigins:s},signal:n},{create:i});return l?this._verify({factorId:a.id,challengeId:l.challengeId,webauthn:{rpId:t,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(a){return w(a)?{data:null,error:a}:{data:null,error:new B("Unexpected error in register",a)}}}};Lr();var cn={url:dr,storageKey:fr,autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,headers:pr,flowType:"implicit",debug:false,hasCustomAuthorizationHeader:false,throwOnError:false,lockAcquireTimeout:1e4};async function Gr(r,e,t){return await t()}var Ae={},yt=class r{get jwks(){var e,t;return (t=(e=Ae[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Ae[this.storageKey]=Object.assign(Object.assign({},Ae[this.storageKey]),{jwks:e});}get jwks_cached_at(){var e,t;return (t=(e=Ae[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ae[this.storageKey]=Object.assign(Object.assign({},Ae[this.storageKey]),{cachedAt:e});}constructor(e){var t,s,n;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=true,this.hasCustomAuthorizationHeader=false,this.suppressGetSessionWarning=false,this.lockAcquired=false,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},cn),e);if(this.storageKey=i.storageKey,this.instanceID=(t=r.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,r.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&j()){let a=`${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(a),this.logDebugMessages&&console.trace(a);}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new de({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=dt(i.fetch),this.lock=i.lock||Gr,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&&j()&&(!((s=globalThis?.navigator)===null||s===void 0)&&s.locks)?this.lock=Nt:this.lock=Gr,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 _t(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:ht()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Lt(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Lt(this.memoryStorage)),j()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey);}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a);}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1);}catch(o){this._debug("#broadcastChannel","error",o);}});}this.initialize().catch(a=>{this._debug("#initialize()","error",a);});}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return `GoTrueClient@${this.storageKey}:${this.instanceID} (${st}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t={},s="none";if(j()&&(t=Tr(window.location.href),this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce")),j()&&this.detectSessionInUrl&&s!=="none"){let{data:n,error:i}=await this._getSessionFromURL(t,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),mr(i)){let l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return {error:i}}return {error:i}}let{session:a,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a);},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new B("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end");}}async signInAnonymously(e){var t,s,n;try{let i=await b(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:q}),{data:a,error:o}=i;if(o||!a)return this._returnResult({data:{user:null,session:null},error:o});let l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,s,n;try{let i;if("email"in e){let{email:u,password:f,options:d}=e,h=null,p=null;this.flowType==="pkce"&&([h,p]=await ce(this.storage,this.storageKey)),i=await b(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:u,password:f,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:h,code_challenge_method:p},xform:q});}else if("phone"in e){let{phone:u,password:f,options:d}=e;i=await b(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:f,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(n=d?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:q});}else throw new ne("You must provide either an email or phone number and a password");let{data:a,error:o}=i;if(o||!a)return await C(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});let l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(await C(this.storage,`${this.storageKey}-code-verifier`),w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:a,options:o}=e;t=await b(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:$t});}else if("phone"in e){let{phone:i,password:a,options:o}=e;t=await b(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:$t});}else throw new ne("You must provide either an email or phone number and a password");let{data:s,error:n}=t;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){let i=new G;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?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 new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,s,n,i,a,o,l,c,u,f,d;let h,p;if("message"in e)h=e.message,p=e.signature;else {let{chain:g,wallet:_,statement:y,options:m}=e,v;if(j())if(typeof _=="object")v=_;else {let D=window;if("ethereum"in D&&typeof D.ethereum=="object"&&"request"in D.ethereum&&typeof D.ethereum.request=="function")v=D.ethereum;else throw new 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(typeof _!="object"||!m?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=_;}let S=new URL((t=m?.url)!==null&&t!==void 0?t:window.location.href),P=await v.request({method:"eth_requestAccounts"}).then(D=>D).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!P||P.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let k=Dt(P[0]),A=(s=m?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!A){let D=await v.request({method:"eth_chainId"});A=Nr(D);}let F={domain:S.host,address:k,statement:y,uri:S.href,version:"1",chainId:A,nonce:(n=m?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=m?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=m?.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=m?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=m?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=m?.signInWithEthereum)===null||u===void 0?void 0:u.resources};h=Br(F),p=await v.request({method:"personal_sign",params:[Dr(h),k]});}try{let{data:g,error:_}=await b(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:p},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(d=e.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:q});if(_)throw _;if(!g||!g.session||!g.user){let y=new G;return this._returnResult({data:{user:null,session:null},error:y})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:_})}catch(g){if(w(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var t,s,n,i,a,o,l,c,u,f,d,h;let p,g;if("message"in e)p=e.message,g=e.signature;else {let{chain:_,wallet:y,statement:m,options:v}=e,S;if(j())if(typeof y=="object")S=y;else {let k=window;if("solana"in k&&typeof k.solana=="object"&&("signIn"in k.solana&&typeof k.solana.signIn=="function"||"signMessage"in k.solana&&typeof k.solana.signMessage=="function"))S=k.solana;else throw new 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(typeof y!="object"||!v?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=y;}let P=new URL((t=v?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in S&&S.signIn){let k=await S.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v?.signInWithSolana),{version:"1",domain:P.host,uri:P.href}),m?{statement:m}:null)),A;if(Array.isArray(k)&&k[0]&&typeof k[0]=="object")A=k[0];else if(k&&typeof k=="object"&&"signedMessage"in k&&"signature"in k)A=k;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in A&&"signature"in A&&(typeof A.signedMessage=="string"||A.signedMessage instanceof Uint8Array)&&A.signature instanceof Uint8Array)p=typeof A.signedMessage=="string"?A.signedMessage:new TextDecoder().decode(A.signedMessage),g=A.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else {if(!("signMessage"in S)||typeof S.signMessage!="function"||!("publicKey"in S)||typeof S!="object"||!S.publicKey||!("toBase58"in S.publicKey)||typeof S.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${P.host} wants you to sign in with your Solana account:`,S.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${P.href}`,`Issued At: ${(n=(s=v?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=v?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${v.signInWithSolana.notBefore}`]:[],...!((a=v?.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${v.signInWithSolana.expirationTime}`]:[],...!((o=v?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${v.signInWithSolana.chainId}`]:[],...!((l=v?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((c=v?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((f=(u=v?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||f===void 0)&&f.length?["Resources",...v.signInWithSolana.resources.map(A=>`- ${A}`)]:[]].join(`
|
|
43
|
+
`);let k=await S.signMessage(new TextEncoder().encode(p),"utf8");if(!k||!(k instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=k;}}try{let{data:_,error:y}=await b(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:z(g)},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:q});if(y)throw y;if(!_||!_.session||!_.user){let m=new G;return this._returnResult({data:{user:null,session:null},error:m})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:y})}catch(_){if(w(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){let t=await Q(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(t??"").split("/");try{if(!s&&this.flowType==="pkce")throw new ot;let{data:i,error:a}=await b(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:q});if(await C(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){let o=new G;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:a})}catch(i){if(await C(this.storage,`${this.storageKey}-code-verifier`),w(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:t,provider:s,token:n,access_token:i,nonce:a}=e,o=await b(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:q}),{data:l,error:c}=o;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){let u=new G;return this._returnResult({data:{user:null,session:null},error:u})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,s,n,i,a;try{if("email"in e){let{email:o,options:l}=e,c=null,u=null;this.flowType==="pkce"&&([c,u]=await ce(this.storage,this.storageKey));let{error:f}=await b(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){let{phone:o,options:l}=e,{data:c,error:u}=await b(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(a=l?.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:u})}throw new ne("You must provide either an email or phone number.")}catch(o){if(await C(this.storage,`${this.storageKey}-code-verifier`),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var t,s;try{let n,i;"options"in e&&(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:a,error:o}=await b(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:q});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");let l=a.session,c=a.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(n){if(w(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var t,s,n,i,a;try{let o=null,l=null;this.flowType==="pkce"&&([o,l]=await ce(this.storage,this.storageKey));let c=await b(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:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:$r});return !((i=c.data)===null||i===void 0)&&i.url&&j()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(o){if(await C(this.storage,`${this.storageKey}-code-verifier`),w(o))return this._returnResult({data:null,error:o});throw o}}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:s}=e;if(s)throw s;if(!t)throw new $;let{error:n}=await b(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(w(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:s,type:n,options:i}=e,{error:a}=await b(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){let{phone:s,type:n,options:i}=e,{data:a,error:o}=await b(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a?.message_id},error:o})}throw new ne("You must provide either an email or phone number and a type")}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await n;}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s;}catch{}})()),await s;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length);}return await s}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!",new Error().stack);try{let e=null,t=await Q(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return {data:{session:null},error:null};let s=e.expires_at?e.expires_at*1e3-Date.now()<it:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){let a=await Q(this.userStorage,this.storageKey+"-user");a?.user?e.user=a.user:e.user=ft();}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let a={value:this.suppressGetSessionWarning};e.user=jr(e.user,a),a.value&&(this.suppressGetSessionWarning=!0);}return {data:{session:e},error:null}}let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},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=true),t}async _getUser(e){try{return e?await b(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:W}):await this._useSession(async t=>{var s,n,i;let{data:a,error:o}=t;if(o)throw o;return !(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new $}:await b(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:W})})}catch(t){if(w(t))return lt(t)&&(await this._removeSession(),await C(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:t});throw t}}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 s=>{let{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new $;let a=n.session,o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await ce(this.storage,this.storageKey));let{data:c,error:u}=await b(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:l}),jwt:a.access_token,xform:W});if(u)throw u;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(s){if(await C(this.storage,`${this.storageKey}-code-verifier`),w(s))return this._returnResult({data:{user:null},error:s});throw s}}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 $;let t=Date.now()/1e3,s=t,n=!0,i=null,{payload:a}=Ke(e.access_token);if(a.exp&&(s=a.exp,n=s<=t),n){let{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return {data:{user:null,session:null},error:null};i=o;}else {let{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i);}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}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 s;if(!e){let{data:a,error:o}=t;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0;}if(!e?.refresh_token)throw new $;let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!j())throw new ie("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ie(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case "implicit":if(this.flowType==="pkce")throw new Be("Not a valid PKCE flow url.");break;case "pkce":if(this.flowType==="implicit")throw new ie("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Be("No code detected.");let{data:m,error:v}=await this._exchangeCodeForSession(e.code);if(v)throw v;let S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:m.session,redirectType:null},error:null}}let{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:a,expires_in:o,expires_at:l,token_type:c}=e;if(!i||!o||!a||!c)throw new ie("No session defined in URL");let u=Math.round(Date.now()/1e3),f=parseInt(o),d=u+f;l&&(d=parseInt(l));let h=d-u;h*1e3<=se&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${f}s`);let p=d-f;u-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,d,u):u-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,d,u);let{data:g,error:_}=await this._getUser(i);if(_)throw _;let y={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:f,expires_at:d,refresh_token:a,token_type:c,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await Q(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 s;let{data:n,error:i}=t;if(i&&!lt(i))return this._returnResult({error:i});let a=(s=n.session)===null||s===void 0?void 0:s.access_token;if(a){let{error:o}=await this.admin.signOut(a,e);if(o&&!(yr(o)&&(o.status===404||o.status===401||o.status===403)||lt(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await C(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=kr(),s={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,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t);})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,n;try{let{data:{session:i},error:a}=t;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i);}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i);}})}async resetPasswordForEmail(e,t={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await ce(this.storage,this.storageKey,true));try{return await b(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(await C(this.storage,`${this.storageKey}-code-verifier`),w(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return "token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:s,error:n}=await this._useSession(async i=>{var a,o,l,c,u;let{data:f,error:d}=i;if(d)throw d;let h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await b(this.fetch,"GET",h,{headers:this.headers,jwt:(u=(c=f.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return j()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var s;try{let{error:n,data:{session:i}}=t;if(n)throw n;let{options:a,provider:o,token:l,access_token:c,nonce:u}=e,f=await b(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:q}),{data:d,error:h}=f;return h?this._returnResult({data:{user:null,session:null},error:h}):!d||!d.session||!d.user?this._returnResult({data:{user:null,session:null},error:new G}):(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:h}))}catch(n){if(await C(this.storage,`${this.storageKey}-code-verifier`),w(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,n;let{data:i,error:a}=t;if(a)throw a;return await b(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await Rr(async n=>(n>0&&await Or(200*Math.pow(2,n-1)),this._debug(t,"refreshing attempt",n),await b(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:q})),(n,i)=>{let a=200*Math.pow(2,n);return i&&ct(i)&&Date.now()+a-s<se})}catch(s){if(this._debug(t,"error",s),w(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(t,"end");}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=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",s),j()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,t;let s="#_recoverAndRefresh()";this._debug(s,"begin");try{let n=await Q(this.storage,this.storageKey);if(n&&this.userStorage){let a=await Q(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await le(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a?.user)!==null&&e!==void 0?e:ft();}else if(n&&!n.user&&!n.user){let a=await Q(this.storage,this.storageKey+"-user");a&&a?.user?(n.user=a.user,await C(this.storage,this.storageKey+"-user"),await le(this.storage,this.storageKey,n)):n.user=ft();}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}let i=((t=n.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<it;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${it}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),ct(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()));}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:a,error:o}=await this._getUser(n.access_token);!o&&a?.user?(n.user=a.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification");}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a);}else await this._notifyAllSubscribers("SIGNED_IN",n);}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end");}}async _callRefreshToken(e){var t,s;if(!e)throw new $;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Fe;let{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new $;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let o={data:i.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(i){if(this._debug(n,"error",i),w(i)){let a={data:null,error:i};return ct(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(a),a}throw (s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end");}}async _notifyAllSubscribers(e,t,s=true){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,t);}catch(l){i.push(l);}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(n,"end");}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=true,await C(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),s=t.user&&t.user.__isUserNotAvailableProxy===true;if(this.userStorage){!s&&t.user&&await le(this.userStorage,this.storageKey+"-user",{user:t.user});let n=Object.assign({},t);delete n.user;let i=Ct(n);await le(this.storage,this.storageKey,i);}else {let n=Ct(t);await le(this.storage,this.storageKey,n);}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=false,await C(this.storage,this.storageKey),await C(this.storage,this.storageKey+"-code-verifier"),await C(this.storage,this.storageKey+"-user"),this.userStorage&&await C(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null);}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&j()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e);}catch(t){console.error("removing visibilitychange callback failed",t);}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),se);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick();},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&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:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/se);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${se}ms, refresh threshold is ${nt} ticks`),n<=nt&&await this._callRefreshToken(s.refresh_token);})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t);}}finally{this._debug("#_autoRefreshTokenTick()","end");}});}catch(e){if(e.isAcquireTimeout||e instanceof Me)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!j()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),false;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1);}catch(e){this._debug("#visibilityChangedCallback","error",e);}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0);}catch(e){console.error("_handleVisibilityChange",e);}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh();}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh();}async _getUrlForProvider(e,t,s){let n=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[i,a]=await ce(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});n.push(o.toString());}if(s?.queryParams){let i=new URLSearchParams(s.queryParams);n.push(i.toString());}return s?.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:n,error:i}=t;return i?this._returnResult({data:null,error:i}):await b(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,n;let{data:i,error:a}=t;if(a)return this._returnResult({data:null,error:a});let o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await b(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var s;let{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});let a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Wr(e.webauthn.credential_response):Hr(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:l}=await b(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:l}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var s;let{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});let a=await b(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;let{data:o}=a;if(o.type!=="webauthn")return {data:o,error:null};switch(o.webauthn.type){case "create":return {data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Mr(o.webauthn.credential_options.publicKey)})})}),error:null};case "request":return {data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Vr(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:s}=await this.getUser();if(s)return {data:null,error:s};let n={all:[],phone:[],totp:[],webauthn:[]};for(let i of (e=t?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return {data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,s,n,i;if(e)try{let{payload:h}=Ke(e),p=null;h.aal&&(p=h.aal);let g=p,{data:{user:_},error:y}=await this.getUser(e);if(y)return this._returnResult({data:null,error:y});((s=(t=_?.factors)===null||t===void 0?void 0:t.filter(S=>S.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(g="aal2");let v=h.amr||[];return {data:{currentLevel:p,nextLevel:g,currentAuthenticationMethods:v},error:null}}catch(h){if(w(h))return this._returnResult({data:null,error:h});throw h}let{data:{session:a},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return {data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=Ke(a.access_token),c=null;l.aal&&(c=l.aal);let u=c;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");let d=l.amr||[];return {data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:d},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:s},error:n}=t;return n?this._returnResult({data:null,error:n}):s?await b(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new $})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new $});let a=await b(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&j()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,t){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new $});let a=await b(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&j()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;return s?this._returnResult({data:null,error:s}):t?await b(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new $})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:s},error:n}=t;return n?this._returnResult({data:null,error:n}):s?(await b(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new $})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(o=>o.kid===e);if(s)return s;let n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+_r>n)return s;let{data:i,error:a}=await b(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return !i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,t={}){try{let s=e;if(!s){let{data:h,error:p}=await this.getSession();if(p||!h.session)return this._returnResult({data:null,error:p});s=h.session.access_token;}let{header:n,payload:i,signature:a,raw:{header:o,payload:l}}=Ke(s);t?.allowExpired||Pr(i.exp);let c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!c){let{error:h}=await this.getUser(s);if(h)throw h;return {data:{claims:i,header:n,signature:a},error:null}}let u=Ir(n.alg),f=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,f,a,Er(`${o}.${l}`)))throw new ae("Invalid JWT signature");return {data:{claims:i,header:n,signature:a},error:null}}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}};yt.nextInstanceID={};var Ft=yt;var un=Ft,Kt=un;var hn="2.96.0",We="";typeof Deno<"u"?We="deno":typeof document<"u"?We="web":typeof navigator<"u"&&navigator.product==="ReactNative"?We="react-native":We="node";var dn={"X-Client-Info":`supabase-js-${We}/${hn}`},fn={headers:dn},pn={schema:"public"},gn={autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,flowType:"implicit"},_n={};function He(r){"@babel/helpers - typeof";return He=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},He(r)}function yn(r,e){if(He(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(He(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(r)}function mn(r){var e=yn(r,"string");return He(e)=="symbol"?e:e+""}function vn(r,e,t){return (e=mn(e))in r?Object.defineProperty(r,e,{value:t,enumerable:true,configurable:true,writable:true}):r[e]=t,r}function zr(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(r,n).enumerable})),t.push.apply(t,s);}return t}function x(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?zr(Object(t),true).forEach(function(s){vn(r,s,t[s]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):zr(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s));});}return r}var wn=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),bn=()=>Headers,En=(r,e,t)=>{let s=wn(t),n=bn();return async(i,a)=>{var o;let l=(o=await e())!==null&&o!==void 0?o:r,c=new n(a?.headers);return c.has("apikey")||c.set("apikey",r),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),s(i,x(x({},a),{},{headers:c}))}};function Sn(r){return r.endsWith("/")?r:r+"/"}function kn(r,e){var t,s;let{db:n,auth:i,realtime:a,global:o}=r,{db:l,auth:c,realtime:u,global:f}=e,d={db:x(x({},l),n),auth:x(x({},c),i),realtime:x(x({},u),a),storage:{},global:x(x(x({},f),o),{},{headers:x(x({},(t=f?.headers)!==null&&t!==void 0?t:{}),(s=o?.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return r.accessToken?d.accessToken=r.accessToken:delete d.accessToken,d}function Tn(r){let e=r?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Sn(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var An=class extends Kt{constructor(r){super(r);}},On=class{constructor(r,e,t){var s,n;this.supabaseUrl=r,this.supabaseKey=e;let i=Tn(r);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let a=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:pn,realtime:_n,auth:x(x({},gn),{},{storageKey:a}),global:fn},l=kn(t??{},o);if(this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}});else {var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch);}this.fetch=En(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(x({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new Yt(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new hr(this.storageUrl.href,this.headers,this.fetch,t?.storage),l.accessToken||this._listenForAuthEvents();}get functions(){return new xe(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(r){return this.rest.from(r)}schema(r){return this.rest.schema(r)}rpc(r,e={},t={head:false,get:false,count:void 0}){return this.rest.rpc(r,e,t)}channel(r,e={config:{}}){return this.realtime.channel(r,e)}getChannels(){return this.realtime.getChannels()}removeChannel(r){return this.realtime.removeChannel(r)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var r=this,e,t;if(r.accessToken)return await r.accessToken();let{data:s}=await r.auth.getSession();return (e=(t=s.session)===null||t===void 0?void 0:t.access_token)!==null&&e!==void 0?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:s,userStorage:n,storageKey:i,flowType:a,lock:o,debug:l,throwOnError:c},u,f){let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new An({url:this.authUrl.href,headers:x(x({},d),u),storageKey:i,autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:s,userStorage:n,flowType:a,lock:o,debug:l,throwOnError:c,fetch:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(h=>h.toLowerCase()==="authorization")})}_initRealtimeClient(r){return new Ee(this.realtimeUrl.href,x(x({},r),{},{params:x(x({},{apikey:this.supabaseKey}),r?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,e)=>{this._handleTokenChanged(r,"CLIENT",e?.access_token);})}_handleTokenChanged(r,e,t){(r==="TOKEN_REFRESHED"||r==="SIGNED_IN")&&this.changedAccessToken!==t?(this.changedAccessToken=t,this.realtime.setAuth(t)):r==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0);}},Jr=(r,e,t)=>new On(r,e,t);function Rn(){if(typeof window<"u")return false;let r=globalThis.process;if(!r)return false;let e=r.version;if(e==null)return false;let t=e.match(/^v(\d+)\./);return t?parseInt(t[1],10)<=18:false}Rn()&&console.warn("\u26A0\uFE0F Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var Mt={endpoint:"https://kvpowojjhuprhxdyzmml.supabase.co",publicKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt2cG93b2pqaHVwcmh4ZHl6bW1sIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTI3ODEwNzAsImV4cCI6MjA2ODM1NzA3MH0.cCPzDNdfTb3WBtYL79GBlw4hfypl4tjnqu7XfEvdKBg"};function R(r,e=null,t){let s=null;return e&&(typeof e=="string"?s=e:e instanceof Error?s=e.message:typeof e=="object"&&e!==null&&"message"in e&&(s=String(e.message))),{data:r,error:s,meta:{...t,timestamp:new Date().toISOString()}}}var Vt=class{constructor(e={}){this.projectId=null;this.isValidated=false;this.resolvedDefaultLocale=null;let t=e.apiKey||this.getEnvApiKey();if(!t)throw new Error("Missing API key. Provide it via config.apiKey or set an environment variable: ZENO_API_KEY, VITE_ZENO_API_KEY, NEXT_PUBLIC_ZENO_API_KEY, or PUBLIC_ZENO_API_KEY.");let s=this.parseApiKey(t);this.apiKey=t,this.projectSlug=s.projectSlug,this.apiToken=s.token,this.configDefaultLocale=e.defaultLocale,this.supabase=Jr(Mt.endpoint,Mt.publicKey,{auth:{persistSession:false,autoRefreshToken:false}});}getEnvApiKey(){let e=["ZENO_API_KEY","NEXT_PUBLIC_ZENO_API_KEY","VITE_ZENO_API_KEY","PUBLIC_ZENO_API_KEY"],t=["ZENO_API_KEY","VITE_ZENO_API_KEY","PUBLIC_ZENO_API_KEY","NEXT_PUBLIC_ZENO_API_KEY"];if(typeof process<"u"&&process.env){for(let s of e)if(process.env[s])return process.env[s]}try{let s=undefined;if(s){for(let n of t)if(s[n])return s[n]}}catch{}}parseApiKey(e){if(!e.startsWith("zeno_"))throw new Error("Invalid API key format. Expected: zeno_<projectSlug>_<token>");let t=e.slice(5),s=t.indexOf("_");if(s===-1)throw new Error("Invalid API key format. Expected: zeno_<projectSlug>_<token>");let n=t.slice(0,s),i=t.slice(s+1);if(!n||!i)throw new Error("Invalid API key format. Expected: zeno_<projectSlug>_<token>");return {projectSlug:n,token:i}}async getDefaultLocale(){if(this.configDefaultLocale)return this.configDefaultLocale;if(this.resolvedDefaultLocale)return this.resolvedDefaultLocale;try{let e=await this.resolveProjectId(),{data:t}=await this.supabase.from("project_locales").select("locale_code").eq("project_id",e).eq("is_default",!0).single();if(t?.locale_code)return this.resolvedDefaultLocale=t.locale_code,t.locale_code}catch{}return this.resolvedDefaultLocale="en","en"}async resolveProjectId(){if(this.projectId&&this.isValidated)return this.projectId;let{data:e,error:t}=await this.supabase.rpc("validate_sdk_api_key",{p_project_slug:this.projectSlug,p_token:this.apiToken});if(t)throw new Error("API key validation failed: "+t.message);let s=e?.[0];if(!s||!s.is_valid)throw new Error(s?.error_message||"Invalid API key or project not found");return this.projectId=s.project_id,this.isValidated=true,s.project_id}async getProject(){try{let e=await this.resolveProjectId(),{data:t,error:s}=await this.supabase.from("projects").select("id, name, description, slug, status, created_at, updated_at").eq("id",e).single();return R(t,s)}catch(e){return R(null,e)}}async getCollections(e={}){try{let t=await this.resolveProjectId(),{page:s=1,limit:n=50,sortBy:i="created_at",sortOrder:a="desc"}=e,o=(s-1)*n,{count:l}=await this.supabase.from("collections").select("*",{count:"exact",head:!0}).eq("project_id",t),{data:c,error:u}=await this.supabase.from("collections").select("id, name, slug, description, fields, created_at, updated_at").eq("project_id",t).order(i,{ascending:a==="asc"}).range(o,o+n-1),f=c?.map(d=>({...d,fields:typeof d.fields=="string"?JSON.parse(d.fields):d.fields}));return R(f,u,{total:l||0,page:s,limit:n,totalPages:Math.ceil((l||0)/n)})}catch(t){return R(null,t)}}async getCollection(e){try{let t=await this.resolveProjectId(),{data:s,error:n}=await this.supabase.from("collections").select("id, name, slug, description, fields, created_at, updated_at").eq("project_id",t).eq("slug",e).single(),i=s?{...s,fields:typeof s.fields=="string"?JSON.parse(s.fields):s.fields}:null;return R(i,n)}catch(t){return R(null,t)}}async getEntries(e,t={}){try{let s=await this.resolveProjectId(),{page:n=1,limit:i=50,sortBy:a="created_at",sortOrder:o="desc",status:l,search:c,locale:u,fallback_locale:f,dateFrom:d,dateTo:h,dateField:p}=t,g=f||await this.getDefaultLocale(),_=(n-1)*i,y=this.supabase.from("entries").select(`
|
|
44
|
+
id, data, status, collection_id, project_id, created_at, updated_at,
|
|
45
|
+
collections ( id, name, slug )
|
|
46
|
+
`).eq("project_id",s);if(e){let{data:U}=await this.supabase.from("collections").select("id").eq("project_id",s).eq("slug",e).single();if(!U)return R(null,"Collection not found");y=y.eq("collection_id",U.id);}l&&(y=y.eq("status",l)),c&&(y=y.textSearch("data",c)),d&&(y=p?y.gte(`data->${p}`,d):y.gte("created_at",d)),h&&(y=p?y.lte(`data->${p}`,h):y.lte("created_at",h));let m=this.supabase.from("entries").select("*",{count:"exact",head:!0}).eq("project_id",s);if(e){let{data:U}=await this.supabase.from("collections").select("id").eq("project_id",s).eq("slug",e).single();U&&(m=m.eq("collection_id",U.id));}l&&(m=m.eq("status",l)),c&&(m=m.textSearch("data",c)),d&&(m=p?m.gte(`data->${p}`,d):m.gte("created_at",d)),h&&(m=p?m.lte(`data->${p}`,h):m.lte("created_at",h));let{count:v}=await m,{data:S,error:P}=await y.order(a,{ascending:o==="asc"}).range(_,_+i-1);if(P)throw P;let A=(S??[]).map(U=>({...U,collections:Array.isArray(U.collections)?U.collections[0]:U.collections})),F=A,D=!1;if(u&&A.length>0)try{let U=A.map(Ge=>Ge.id),mt=await this.supabase.rpc("get_localized_entries_batch",{entry_uuids:U,locale:u,fallback_locale:g});if(mt.data&&mt.data.length>0){let Ge=new Map;for(let J of mt.data)Ge.set(J.entry_id,{data:J.data,locale_code:J.locale_code,is_fallback:J.is_fallback});F=A.map(J=>{let ze=Ge.get(J.id);return ze?(ze.is_fallback&&(D=!0),{...J,data:ze.data,locale_code:ze.locale_code}):J});}}catch{}let{data:Yr}=await this.supabase.from("project_locales").select("locale_code").eq("project_id",s).eq("is_active",!0);return R(F,null,{total:v||0,page:n,limit:i,totalPages:Math.ceil((v||0)/i),locale:u||g,fallback_used:D,available_locales:Yr?.map(U=>U.locale_code)||[]})}catch(s){return R(null,s)}}async getEntry(e,t={}){try{let s=await this.resolveProjectId(),{locale:n,fallback_locale:i}=t,a=i||await this.getDefaultLocale(),{data:o,error:l}=await this.supabase.from("entries").select(`
|
|
47
|
+
id, data, status, collection_id, project_id, created_at, updated_at,
|
|
48
|
+
collections ( id, name, slug, fields )
|
|
49
|
+
`).eq("project_id",s).eq("id",e).single();if(l)throw l;let c=o,u=c?{...c,collections:Array.isArray(c.collections)?c.collections[0]:c.collections}:null,f=u,d=!1;if(n&&u)try{let p=await this.supabase.rpc("get_localized_entry",{entry_uuid:e,locale:n,fallback_locale:a});if(p.data?.[0]){let g=p.data[0];g.locale_code!==n&&(d=!0),f={...u,data:g.data,locale_code:g.locale_code};}}catch{}let{data:h}=await this.supabase.from("project_locales").select("locale_code").eq("project_id",s).eq("is_active",!0);return R(f,null,{locale:n||a,fallback_used:d,available_locales:h?.map(p=>p.locale_code)||[]})}catch(s){return R(null,s)}}async getAssets(e={}){try{let t=await this.resolveProjectId(),{page:s=1,limit:n=50,sortBy:i="created_at",sortOrder:a="desc",mimeType:o}=e,l=(s-1)*n,c=this.supabase.from("assets").select("id, filename, original_filename, mime_type, size_bytes, metadata, created_at").eq("project_id",t);o&&(c=c.like("mime_type",`${o}%`));let u=this.supabase.from("assets").select("*",{count:"exact",head:!0}).eq("project_id",t);o&&(u=u.like("mime_type",`${o}%`));let{count:f}=await u,{data:d,error:h}=await c.order(i,{ascending:a==="asc"}).range(l,l+n-1);return R(d,h,{total:f||0,page:s,limit:n,totalPages:Math.ceil((f||0)/n)})}catch(t){return R(null,t)}}async getAssetUrl(e){try{let t=await this.resolveProjectId(),{data:s,error:n}=await this.supabase.from("assets").select("storage_path").eq("project_id",t).eq("id",e).single();if(n||!s)return R(null,"Asset not found");let{data:i,error:a}=await this.supabase.storage.from("assets").createSignedUrl(s.storage_path,3600);return a?R(null,a):R({downloadUrl:i.signedUrl,expiresIn:3600})}catch(t){return R(null,t)}}async sendEmail(e){try{let t=await fetch(`${Mt.endpoint}/functions/v1/api/email/send`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json();return t.ok?R(s.data):R(null,s.error||"Email sending failed")}catch(t){return R(null,t)}}async getLocales(){try{let e=await this.resolveProjectId(),{data:t,error:s}=await this.supabase.from("project_locales").select("locale_code, locale_name, locale_native_name, is_default").eq("project_id",e).eq("is_active",!0).order("is_default",{ascending:!1}).order("locale_name",{ascending:!0});if(s)throw s;let n=t?.map(i=>({code:i.locale_code,name:i.locale_name,native_name:i.locale_native_name,is_default:i.is_default}))||[];return R(n)}catch(e){return R(null,e)}}async health(){return R({status:"healthy",version:"1.0.0"})}};if(typeof window!=="undefined"){window.ZenoCMS=ZenoSDK.ZenoCMS;}exports.ZenoCMS=Vt;return exports;})({});//# sourceMappingURL=zeno.min.js.map
|
|
50
|
+
//# sourceMappingURL=zeno.min.js.map
|