(()=>{var T={supabaseUrl:"https://bennrweioxvkxsxnpzxt.supabase.co",supabaseAnonKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImJlbm5yd2Vpb3h2a3hzeG5wenh0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTQ2MzYyOTQsImV4cCI6MjAzMDIxMjI5NH0.Twwq4ddb8x2p6-8Qz14o68E5GNrirkUvwl-c0tf2py0"};function rs(t,e){return async function(s){let n=e.getState().status==="authenticated"&&e.getState().user?.id,i=()=>{if(!n||s?.aborted||e.getState().status!=="authenticated"||e.getState().user?.id!==n||!e.getShopbyAccessToken())throw new Error("Community account changed")};i();let o=new Set;for(let a=0;a<5e4;a+=500){i();let l=t.from("shopby_member_blocks").select("blocked_member_no").eq("blocker_id",n).order("blocked_member_no",{ascending:!0}).range(a,a+499);s&&(l=l.abortSignal(s));let{data:c,error:u}=await l;if(i(),u||!Array.isArray(c)||c.some(h=>!Number.isSafeInteger(h.blocked_member_no)||h.blocked_member_no<1))throw new Error("Community block list unavailable");if(c.forEach(h=>o.add(h.blocked_member_no)),c.length<500)return[...o]}throw new Error("Community block list incomplete")}}var fr="/pages/sign-in/signup-consent.html",be=Object.freeze({privacyVersion:"1.0",serviceVersion:"1.0",privacyUrl:"https://hellogreency.notion.site/7776189a124e4ecc9c395a1326990cfb",serviceUrl:"https://hellogreency.notion.site/5be8b478d1154e6783a464e96b73b5ab?pvs=74"}),jt="hellogreency-signup-invite-v1",Bn=10080*60*1e3,qn=/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/;function dr(t){if(typeof t!="string"||t.length>100)return null;let e=t.trim().toUpperCase();return qn.test(e)?e:null}function pr(t){return{invite_invalid:"\uCD08\uB300 \uCF54\uB4DC\uB97C \uD655\uC778\uD574 \uC8FC\uC138\uC694. \uCE5C\uAD6C\uC5D0\uAC8C \uBC1B\uC740 6\uC790\uB9AC \uCF54\uB4DC\uB97C \uC785\uB825\uD560 \uC218 \uC788\uC5B4\uC694.",invite_self:"\uB0B4 \uCD08\uB300 \uCF54\uB4DC\uB294 \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC5B4\uC694. \uCE5C\uAD6C\uC758 \uCF54\uB4DC\uB97C \uC785\uB825\uD574 \uC8FC\uC138\uC694.",invite_ineligible:"\uAE30\uC874 \uD68C\uC6D0\uC740 \uC2E0\uADDC\uAC00\uC785 \uCD08\uB300 \uD61C\uD0DD \uB300\uC0C1\uC774 \uC544\uB2C8\uC5D0\uC694.",referral_already_accepted:"\uC774\uBBF8 \uCD08\uB300 \uD61C\uD0DD\uC774 \uC5F0\uACB0\uB41C \uACC4\uC815\uC774\uC5D0\uC694.",referral_closed:"\uAC00\uC785\uC774 \uC644\uB8CC\uB41C \uB4A4\uC5D0\uB294 \uCD08\uB300 \uCF54\uB4DC\uB97C \uCD94\uAC00\uD560 \uC218 \uC5C6\uC5B4\uC694.",consent_required:"\uD544\uC218 \uC57D\uAD00 \uB450 \uD56D\uBAA9\uC5D0 \uB3D9\uC758\uD574 \uC8FC\uC138\uC694.",terms_version_changed:"\uC57D\uAD00\uC774 \uBCC0\uACBD\uB418\uC5C8\uC5B4\uC694. \uC0C8\uB85C\uACE0\uCE68 \uD6C4 \uB2E4\uC2DC \uD655\uC778\uD574 \uC8FC\uC138\uC694.",signup_unavailable:"\uAC00\uC785 \uC815\uBCF4\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694. \uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",session_changed:"\uB85C\uADF8\uC778 \uACC4\uC815\uC774 \uBCC0\uACBD\uB410\uC5B4\uC694. \uC0C8\uB85C\uACE0\uCE68 \uD6C4 \uB2E4\uC2DC \uD655\uC778\uD574 \uC8FC\uC138\uC694.",browser_storage_unavailable:"\uCD08\uB300 \uCF54\uB4DC\uB97C \uBCF4\uAD00\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694. \uAC00\uC785\uD560 \uB54C \uC9C1\uC811 \uC785\uB825\uD574 \uC8FC\uC138\uC694."}[t]||"\uAC00\uC785 \uCC98\uB9AC\uB97C \uC644\uB8CC\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694. \uC785\uB825\uD55C \uB0B4\uC6A9\uC744 \uD655\uC778\uD558\uACE0 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694."}function q(t){let e=new Error(pr(t));return e.code=t,e}function ss({supabaseUrl:t,anonKey:e,storage:r,fetcher:s=fetch,now:n=Date.now}){function i(){try{r.removeItem(jt)}catch{}}function o(){try{let d=JSON.parse(r.getItem(jt));return!d||!dr(d.code)||!Number.isFinite(d.receivedAt)||d.receivedAt>n()||n()-d.receivedAt>=Bn||d.userId!==null&&typeof d.userId!="string"?(i(),null):d}catch{return i(),null}}function a(d){let p=new URL(d).searchParams.getAll("invite");if(!p.length)return;let g=p.length===1?dr(p[0]):null;if(!g){i();return}try{r.setItem(jt,JSON.stringify({code:g,receivedAt:n(),userId:null}))}catch{throw q("browser_storage_unavailable")}}function l(d){let p=o();if(!p)return"";if(p.userId&&p.userId!==d)return i(),"";if(!p.userId)try{r.setItem(jt,JSON.stringify({...p,userId:d}))}catch{return i(),""}return p.code}function c(d){let p=o();p?.userId&&p.userId!==d&&i()}async function u(d,p,g,_){let w;try{w=await s(`${t}/rest/v1/rpc/${d}`,{method:"POST",headers:{apikey:e,Authorization:`Bearer ${g}`,"Content-Type":"application/json"},body:JSON.stringify(p),signal:_,redirect:"error",credentials:"omit"})}catch{throw q("signup_unavailable")}let y;try{y=await w.json()}catch{throw q("signup_unavailable")}if(!w.ok)throw q(["invite_invalid","invite_self","invite_ineligible","consent_required","terms_version_changed"].includes(y?.message)?y.message:"signup_unavailable");if(!y||typeof y.needs_consent!="boolean"||typeof y.can_set_referral!="boolean"||!["none","accepted","skipped","legacy"].includes(y.referral_status)||y.privacy_version!==be.privacyVersion||y.service_version!==be.serviceVersion)throw q("signup_unavailable");return y}async function h({token:d,user:p,signal:g}){c(p.id);let _=await u("signup_status",{},d,g),w=o(),y=!!w&&(!w.userId||w.userId===p.id),m=null;return!_.can_set_referral&&y&&(m=_.referral_status==="legacy"?"invite_ineligible":_.referral_status==="accepted"?"referral_already_accepted":"referral_closed"),_.can_set_referral||i(),{..._,code:_.can_set_referral?l(p.id):"",referral_notice:m}}async function f({token:d,user:p,privacy:g,service:_,code:w,signal:y}){if(!g||!_)throw q("consent_required");let m=w?.trim()?dr(w):null;if(w?.trim()&&!m)throw q("invite_invalid");let E=await u("signup_complete",{p_privacy_agreed:!0,p_service_agreed:!0,p_privacy_version:be.privacyVersion,p_service_version:be.serviceVersion,p_invite_code:m},d,y);if(E.completed!==!0||E.needs_consent)throw q("signup_unavailable");let R=o();return(!R?.userId||R.userId===p.id)&&i(),E}return{capture:a,forUser:l,inspect:h,complete:f,clear:i,identityChanged:c}}function Se(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);nt?(...e)=>t(...e):(...e)=>fetch(...e);var je=class extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}toJSON(){return{name:this.name,message:this.message,context:this.context}}},et=class extends je{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Ne=class extends je{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ue=class extends je{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},tt;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(tt||(tt={}));var rt=class{constructor(e,{headers:r={},customFetch:s,region:n=tt.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=is(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return ns(this,arguments,void 0,function*(r,s={}){var n;let i,o;try{let{headers:a,method:l,body:c,signal:u,timeout:h}=s,f={},{region:d}=s;d||(d=this.region);let p=new URL(`${this.url}/${r}`);d&&d!=="any"&&(f["x-region"]=d,p.searchParams.set("forceFunctionRegion",d));let g,_=!!a&&Object.keys(a).some(b=>b.toLowerCase()==="content-type");c&&!_?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=c):typeof c=="string"?(f["Content-Type"]="text/plain",g=c):typeof FormData<"u"&&c instanceof FormData?g=c:(f["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 w=u;h&&(o=new AbortController,i=setTimeout(()=>o.abort(),h),u?(w=o.signal,u.addEventListener("abort",()=>o.abort())):w=o.signal);let y=yield this.fetch(p.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:g,signal:w}).catch(b=>{throw new et(b)}),m=y.headers.get("x-relay-error");if(m&&m==="true")throw new Ne(y);if(!y.ok)throw new Ue(y);let E=((n=y.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),R;return E==="application/json"?R=yield y.json():E==="application/octet-stream"||E==="application/pdf"?R=yield y.blob():E==="text/event-stream"?R=y:E==="multipart/form-data"?R=yield y.formData():R=yield y.text(),{data:R,error:null,response:y}}catch(a){return{data:null,error:a,response:a instanceof Ue||a instanceof Ne?a.context:void 0}}finally{i&&clearTimeout(i)}})}};var os=t=>Math.min(1e3*2**t,3e4),Mn=[520,503],us=["GET","HEAD","OPTIONS"],gr=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function as(t,e){return new Promise(r=>{if(e?.aborted){r();return}let s=setTimeout(()=>{e?.removeEventListener("abort",n),r()},t);function n(){clearTimeout(s),r()}e?.addEventListener("abort",n)})}function Fn(t,e,r,s){return!(!s||r>=3||!us.includes(t)||!Mn.includes(e))}var Hn=class{constructor(t){var e,r,s,n,i;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(s=t.shouldStripNulls)!==null&&s!==void 0?s:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,this.retryEnabled=(i=t.retry)!==null&&i!==void 0?i:!0,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(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"),this.shouldStripNulls){let o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let s=this.fetch,i=(async()=>{let o=0;for(;;){let c={};r.headers.forEach((h,f)=>{c[f]=h}),o>0&&(c["X-Retry-Count"]=String(o));let u;try{u=await s(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body,(h,f)=>typeof f=="bigint"?f.toString():f),signal:r.signal})}catch(h){if(h?.name==="AbortError"||h?.code==="ABORT_ERR"||!us.includes(r.method))throw h;if(r.retryEnabled&&o<3){let f=os(o);o++,await as(f,r.signal);continue}throw h}if(Fn(r.method,u.status,o,r.retryEnabled)){var a,l;let h=(a=(l=u.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&a!==void 0?a:null,f=h!==null?Math.max(0,parseInt(h,10)||0)*1e3:os(o);await u.text(),o++,await as(f,r.signal);continue}return await r.processResponse(u)}})();return this.shouldThrowOnError||(i=i.catch(o=>{var a;let l="",c="",u="",h=o?.cause;if(h){var f,d,p,g;let y=(f=h?.message)!==null&&f!==void 0?f:"",m=(d=h?.code)!==null&&d!==void 0?d:"";l=`${(p=o?.name)!==null&&p!==void 0?p:"FetchError"}: ${o?.message}`,l+=` Caused by: ${(g=h?.name)!==null&&g!==void 0?g:"Error"}: ${y}`,m&&(l+=` (${m})`),h?.stack&&(l+=` ${h.stack}`)}else{var _;l=(_=o?.stack)!==null&&_!==void 0?_:""}let w=this.url.toString().length;return o?.name==="AbortError"||o?.code==="ABORT_ERR"?(u="",c="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${w} 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.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",c="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(c+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(a=o?.name)!==null&&a!==void 0?a:"FetchError"}: ${o?.message}`,details:l,hint:c,code:u},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}async processResponse(t){var e=this;let r=null,s=null,n=null,i=t.status,o=t.statusText;if(t.ok){var a,l;if(e.method!=="HEAD"){var c;let f=await t.text();if(f!=="")if(e.headers.get("Accept")==="text/csv")s=f;else if(e.headers.get("Accept")&&(!((c=e.headers.get("Accept"))===null||c===void 0)&&c.includes("application/vnd.pgrst.plan+text")))s=f;else try{s=JSON.parse(f)}catch{if(r={message:f},s=null,e.shouldThrowOnError)throw new gr({message:f,details:"",hint:"",code:""})}}let u=(a=e.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),h=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");u&&h&&h.length>1&&(n=parseInt(h[1])),e.isMaybeSingle&&Array.isArray(s)&&(s.length>1?(r={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,i=406,o="Not Acceptable"):s.length===1?s=s[0]:s=null)}else{let u=await t.text();try{r=JSON.parse(u),Array.isArray(r)&&t.status===404&&(s=[],r=null,i=200,o="OK")}catch{t.status===404&&u===""?(i=204,o="No Content"):r={message:u}}if(r&&e.shouldThrowOnError)throw new gr(r)}return{success:r===null,error:r,data:s,count:n,status:i,statusText:o}}returns(){return this}overrideTypes(){return this}},Kn=class extends Hn{throwOnError(){return super.throwOnError()}select(t){let e=!1,r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){let i=n?`${n}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){let n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},ls=new RegExp("[,()]"),Le=class extends Kn{throwOnError(){return super.throwOnError()}eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&ls.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&ls.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Wn=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3,retry:i}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET",i=!1,o=(t??"*").split("").map(c=>/\s/.test(c)&&!i?"":(c==='"'&&(i=!i),c)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),s&&l.append("Prefer",`count=${s}`),new Le({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;let n="POST",{url:i,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){let l=[...new Set(a)].map(c=>`"${c}"`);i.searchParams.set("columns",l.join(","))}}return new Le({method:n,url:i,headers:o,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),s&&l.append("Prefer",`count=${s}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let c=t.reduce((u,h)=>u.concat(Object.keys(h)),[]);if(c.length>0){let u=[...new Set(c)].map(h=>`"${h}"`);a.searchParams.set("columns",u.join(","))}}return new Le({method:o,url:a,headers:l,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;let s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Le({method:s,url:n,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;let r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Le({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function st(t){"@babel/helpers - typeof";return st=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},st(t)}function Vn(t,e){if(st(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(st(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function zn(t){var e=Vn(t,"string");return st(e)=="symbol"?e:e+""}function Jn(t,e,r){return(e=zn(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function cs(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function Nt(t){for(var e=1;e0?this.fetch=(c,u)=>{let h=new AbortController,f=setTimeout(()=>h.abort(),i),d=u?.signal;if(d){if(d.aborted)return clearTimeout(f),l(c,u);let p=()=>{clearTimeout(f),h.abort()};return d.addEventListener("abort",p,{once:!0}),l(c,Nt(Nt({},u),{},{signal:h.signal})).finally(()=>{clearTimeout(f),d.removeEventListener("abort",p)})}return l(c,Nt(Nt({},u),{},{signal:h.signal})).finally(()=>clearTimeout(f))}:this.fetch=l,this.retry=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Wn(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new ds(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),c,u=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(u)),h=s&&Object.values(r).some(u);h?(a="POST",c=r):s||n?(a=s?"HEAD":"GET",Object.entries(r).filter(([d,p])=>p!==void 0).map(([d,p])=>[d,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([d,p])=>{l.searchParams.append(d,p)})):(a="POST",c=r);let f=new Headers(this.headers);return h?f.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&f.set("Prefer",`count=${i}`),new Le({method:a,url:l,headers:f,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};var yr=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};let r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};let s=typeof global<"u"?global:void 0;if(s&&typeof s.WebSocket<"u")return{type:"native",wsConstructor:s.WebSocket};if(typeof globalThis<"u"&&typeof r.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"&&r.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 n=globalThis.process;if(n){let i=n.versions;if(i&&i.node){let o=i.node,a=parseInt(o.replace(/^v/,"").split(".")[0]);return a>=22?typeof globalThis.WebSocket<"u"?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${a} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${a} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: import ws from "ws" 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.wsConstructor)return e.wsConstructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=` Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},mr=yr;var fs="2.109.0";var ps=`realtime-js/${fs}`,gs="1.0.0",_r="2.0.0",ys=_r;var ms=1e4;var _s=100;var se={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ut={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var nt={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var it=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,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;let n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;let n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},o=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,s){var n,i;let o=e.topic,a=(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):{},h=Object.keys(u).length===0?"":JSON.stringify(u);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);let f=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+h.length,d=new ArrayBuffer(this.HEADER_LENGTH+f),p=new DataView(d),g=0;p.setUint8(g++,this.KINDS.userBroadcastPush),p.setUint8(g++,l.length),p.setUint8(g++,a.length),p.setUint8(g++,o.length),p.setUint8(g++,c.length),p.setUint8(g++,h.length),p.setUint8(g++,r),Array.from(l,w=>p.setUint8(g++,w.charCodeAt(0))),Array.from(a,w=>p.setUint8(g++,w.charCodeAt(0))),Array.from(o,w=>p.setUint8(g++,w.charCodeAt(0))),Array.from(c,w=>p.setUint8(g++,w.charCodeAt(0))),Array.from(h,w=>p.setUint8(g++,w.charCodeAt(0)));var _=new Uint8Array(d.byteLength+s.byteLength);return _.set(new Uint8Array(d),0),_.set(new Uint8Array(s),d.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){let s=JSON.parse(e),[n,i,o,a,l]=s;return r({join_ref:n,ref:i,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;switch(s){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,n)}}_decodeUserBroadcast(e,r,s){let n=r.getUint8(1),i=r.getUint8(2),o=r.getUint8(3),a=r.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 h=s.decode(e.slice(l,l+o));l=l+o;let f=e.slice(l,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(s.decode(f)):f,p={type:this.BROADCAST_EVENT,event:u,payload:d};return o>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}};var P;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(P||(P={}));var vr=(t,e,r={})=>{var s;let n=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=Gn(o,t,e,n),i),{}):{}},Gn=(t,e,r,s)=>{let n=e.find(a=>a.name===t),i=n?.type,o=r[t];return i&&!s.includes(i)?ws(i,o):wr(o)},ws=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Zn(e,r)}switch(t){case P.bool:return Yn(e);case P.float4:case P.float8:case P.int2:case P.int4:case P.int8:case P.numeric:case P.oid:return Xn(e);case P.json:case P.jsonb:return Qn(e);case P.timestamp:return ei(e);case P.abstime:case P.date:case P.daterange:case P.int4range:case P.int8range:case P.money:case P.reltime:case P.text:case P.time:case P.timestamptz:case P.timetz:case P.tsrange:case P.tstzrange:return wr(e);default:return wr(e)}},wr=t=>t,Yn=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Xn=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Qn=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Zn=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i,o=t.slice(1,r);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>ws(e,a))}return t},ei=t=>typeof t=="string"?t.replace(" ","T"):t,Lt=t=>{let e=new URL(t);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 at=t=>typeof t=="function"?t:function(){return t},ri=typeof self<"u"?self:null,De=typeof window<"u"?window:null,ne=ri||De||globalThis,si="2.0.0",ni=1e4,ii=1e3,ie={connecting:0,open:1,closing:2,closed:3},V={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},ue={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},br={longpoll:"longpoll",websocket:"websocket"},oi={complete:4},Sr="base64url.bearer.phx.",$t=class{constructor(t,e,r,s){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},vs=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},ai=class{constructor(t,e,r){this.state=V.closed,this.topic=t,this.params=at(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new $t(this,ue.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new vs(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=V.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=V.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=V.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=V.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new $t(this,ue.leave,at({}),this.timeout).send(),this.state=V.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(ue.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=V.closed,this.bindings=[]}onClose(t){this.on(ue.close,t)}onError(t){return this.on(ue.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new $t(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=V.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(ue.close,"leave")},r=new $t(this,ue.leave,at({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=V.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let n=this.onMessage(t,e,r,s);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;ol.abort(),n);a.signal=l.signal}return ne.fetch(e,a).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>o&&o(c)).catch(c=>{c.name==="AbortError"&&i?i():o&&o(null)}),l}static xdomainRequest(t,e,r,s,n,i,o){return t.timeout=n,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);o&&o(a)},i&&(t.ontimeout=i),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,n,i,o,a){t.open(e,r,!0),t.timeout=i;for(let[l,c]of Object.entries(s))t.setRequestHeader(l,c);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===oi.complete&&a){let l=this.parseJSON(t.responseText);a(l)}},o&&(t.ontimeout=o),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=e?`${e}[${s}]`:s,i=t[s];typeof i=="object"?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},li=t=>{let e="",r=new Uint8Array(t),s=r.byteLength;for(let n=0;nthis.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+br.websocket),"$1/"+br.longpoll)}endpointURL(){return Bt.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=ie.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===ie.open||this.readyState===ie.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:n.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=ie.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=li(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(` `),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=ie.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,n){let i,o=()=>{this.reqs.delete(i),s()};i=Bt.request(t,this.endpointURL(),e,r,this.timeout,o,a=>{this.reqs.delete(i),this.isActive()&&n(a)}),this.reqs.add(i)}},bs=class ot{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=ot.syncState(this.state,n,i,o),this.pendingDiffs.forEach(l=>{this.state=ot.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel.on(s.diff,n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=ot.syncDiff(this.state,n,i,o),a())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return ot.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let i=this.clone(e),o={},a={};return this.map(i,(l,c)=>{r[l]||(a[l]=c)}),this.map(r,(l,c)=>{let u=i[l];if(u){let h=c.metas.map(g=>g.phx_ref),f=u.metas.map(g=>g.phx_ref),d=c.metas.filter(g=>f.indexOf(g.phx_ref)<0),p=u.metas.filter(g=>h.indexOf(g.phx_ref)<0);d.length>0&&(o[l]=c,o[l].metas=d),p.length>0&&(a[l]=this.clone(u),a[l].metas=p)}else o[l]=c}),this.syncDiff(i,{joins:o,leaves:a},s,n)}static syncDiff(e,r,s,n){let{joins:i,leaves:o}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(i,(a,l)=>{let c=e[a];if(e[a]=this.clone(l),c){let u=e[a].metas.map(f=>f.phx_ref),h=c.metas.filter(f=>u.indexOf(f.phx_ref)<0);e[a].metas.unshift(...h)}s(a,c,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let u=l.metas.map(h=>h.phx_ref);c.metas=c.metas.filter(h=>u.indexOf(h.phx_ref)<0),n(a,c,l),c.metas.length===0&&delete e[a]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Dt={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,n,i,o]=JSON.parse(t);return e({join_ref:r,ref:s,topic:n,event:i,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:n,payload:i}=t,o=this.META_LENGTH+e.length+r.length+n.length+s.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),l=new DataView(a),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,e.length),l.setUint8(c++,r.length),l.setUint8(c++,n.length),l.setUint8(c++,s.length),Array.from(e,h=>l.setUint8(c++,h.charCodeAt(0))),Array.from(r,h=>l.setUint8(c++,h.charCodeAt(0))),Array.from(n,h=>l.setUint8(c++,h.charCodeAt(0))),Array.from(s,h=>l.setUint8(c++,h.charCodeAt(0)));var u=new Uint8Array(a.byteLength+i.byteLength);return u.set(new Uint8Array(a),0),u.set(new Uint8Array(i),a.byteLength),u.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(o,o+s));o=o+s;let l=r.decode(t.slice(o,o+n));o=o+n;let c=r.decode(t.slice(o,o+i));o=o+i;let u=t.slice(o,t.byteLength);return{join_ref:a,ref:null,topic:l,event:c,payload:u}},decodeReply(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(a,a+s));a=a+s;let c=r.decode(t.slice(a,a+n));a=a+n;let u=r.decode(t.slice(a,a+i));a=a+i;let h=r.decode(t.slice(a,a+o));a=a+o;let f=t.slice(a,t.byteLength),d={status:h,response:f};return{join_ref:l,ref:c,topic:u,event:ue.reply,payload:d}},decodeBroadcast(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=this.HEADER_LENGTH+2,o=r.decode(t.slice(i,i+s));i=i+s;let a=r.decode(t.slice(i,i+n));i=i+n;let l=t.slice(i,t.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:l}}},Ss=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||ni,this.transport=e.transport||ne.WebSocket||$e,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=ne&&ne.sessionStorage}catch{}this.sessionStore=e.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=Dt.encode.bind(Dt),this.defaultDecoder=Dt.decode.bind(Dt),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==$e?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;De&&De.addEventListener&&(De.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),s=this.connectClock)}),De.addEventListener("pageshow",n=>{s===this.connectClock&&(s=null,this.connect())}),De.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,o)=>{console.log(`${n}: ${i}`,o)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=at(e.params||{}),this.endPoint=`${t}/${br.websocket}`,this.vsn=e.vsn||si,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new vs(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return $e}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Bt.appendParams(Bt.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=at(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==$e?this.connectWithFallback($e,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(n=>{n.ref===e&&(this.off([s]),t(Date.now()-r))});return!0}transportName(t){switch(t){case $e:return"LongPoll";default:return t.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Sr}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,n,i,o=this.transportName(t),a=l=>{this.log("transport",`falling back to ${o}...`,l),this.off([n,i]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),i=this.onError(l=>{this.log("transport","error",l),s&&!r&&(clearTimeout(this.fallbackTimer),a(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),ii,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();let s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===ie.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(ue.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case ie.connecting:return"connecting";case ie.open:return"open";case ie.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new ai(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:s,ref:n,join_ref:i}=t;this.log("push",`${e} ${r} (${i}, ${n})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:n,ref:i,join_ref:o}=e;if(i&&i===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",a)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${s} ${i&&"("+i+")"||""}`.trim(),n);for(let a=0;a{try{s(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};var lt=class t{constructor(e,r){let s=ui(r);this.presence=new bs(e.getChannel(),s),this.presence.onJoin((n,i,o)=>{let a=t.onJoinPayload(n,i,o);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,i,o)=>{let a=t.onLeavePayload(n,i,o);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=ci(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{let n=e[s];return r[s]=qt(n),r},{})}static onJoinPayload(e,r,s){let n=ks(r),i=qt(s);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,r,s){let n=ks(r),i=qt(s);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}};function qt(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function ci(t){return JSON.parse(JSON.stringify(t))}function ui(t){return t?.events&&{events:t.events}}function ks(t){return t?.metas?qt(t):[]}var kr;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(kr||(kr={}));var Be=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new lt(this.channel.channelAdapter,r)}};function Es(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){let e=t;if(typeof e.code=="number"){let r=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${r}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}var ct=class{constructor(e,r,s){let n=hi(s);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,s){let n;try{n=this.channel.push(e,r,s)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>_s){let i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===se.joined}isJoined(){return this.state===se.joined}isJoining(){return this.state===se.joining}isClosed(){return this.state===se.closed}isLeaving(){return this.state===se.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function hi(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var di=/[,()"\\]/,fi=t=>di.test(t)||t!==t.trim(),pi=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Ts=t=>{let e=t===null?"null":String(t);return fi(e)?pi(e):e},gi=t=>t===null?"null":String(t),yi=(t,e)=>{if(t==="in"){let r=Array.isArray(e)?e:[e];if(r.length===0)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(r)).map(n=>Ts(n)).join(",")})`}return t==="is"?`is.${gi(e)}`:`${t}.${Ts(e)}`},qe=class{constructor(){this.filters=[]}add(e,r,s,n=!1){let i=n?"not.":"";return this.filters.push(`${e}=${i}${yi(r,s)}`),this}eq(e,r){return this.add(e,"eq",r)}neq(e,r){return this.add(e,"neq",r)}gt(e,r){return this.add(e,"gt",r)}gte(e,r){return this.add(e,"gte",r)}lt(e,r){return this.add(e,"lt",r)}lte(e,r){return this.add(e,"lte",r)}in(e,r){return this.add(e,"in",r)}like(e,r){return this.add(e,"like",r)}ilike(e,r){return this.add(e,"ilike",r)}match(e,r){return this.add(e,"match",r)}imatch(e,r){return this.add(e,"imatch",r)}is(e,r){return this.add(e,"is",r)}isDistinct(e,r){return this.add(e,"isdistinct",r)}not(e,r,s){return this.add(e,r,s,!0)}build(){return this.filters.join(",")}toString(){return this.build()}};var Er;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Er||(Er={}));var ke;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(ke||(ke={}));var oe;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(oe||(oe={}));var Me=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new ct(this.socket.socketAdapter,e,this.params),this.presence=new Be(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Lt(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var s,n,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:o,presence:a,private:l}}=this.params,c=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(d=>d.filter))!==null&&n!==void 0?n:[],u=!!this.bindings[ke.PRESENCE]&&this.bindings[ke.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},f={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(d=>{e?.(oe.CHANNEL_ERROR,Es(d))}),this._onClose(()=>e?.(oe.CLOSED)),this.updateJoinPayload(Object.assign({config:f},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:d})=>{if(this.socket._isManualToken()||this.socket.setAuth(),d===void 0){e?.(oe.SUBSCRIBED);return}this._updatePostgresBindings(d,e)}).receive("error",d=>{this.state=se.errored;let p=Object.values(d).join(", ")||"error";e?.(oe.CHANNEL_ERROR,new Error(p,{cause:d}))}).receive("timeout",()=>{e?.(oe.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;let n=this.bindings.postgres_changes,i=(s=n?.length)!==null&&s!==void 0?s:0,o=[];for(let a=0;a{var o,a,l;let c=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.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.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),o}_on(e,r,s){let n=e.toLocaleLowerCase(),i=r?.filter;(i instanceof qe||typeof i=="object"&&i!==null&&typeof i.build=="function")&&(r=Object.assign(Object.assign({},r),{filter:i.build()}));let o=this.channelAdapter.on(e,s),a={type:n,filter:r,callback:s,ref:o};return this.bindings[n]?this.bindings[n].push(a):this.bindings[n]=[a],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var n,i,o,a,l,c,u;let h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,s))return!1;let f=(n=this.bindings[h])===null||n===void 0?void 0:n.find(d=>d.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in f){let d=f.id,p=(i=f.filter)===null||i===void 0?void 0:i.event;return d&&((o=r.ids)===null||o===void 0?void 0:o.includes(d))&&(p==="*"||p?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let d=(c=(l=f?.filter)===null||l===void 0?void 0:l.event)===null||c===void 0?void 0:c.toLocaleLowerCase();return d==="*"||d===((u=r?.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,r){let{close:s,error:n,leave:i,join:o}=Ut;return r&&[s,n,i,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:i,table:o,commit_timestamp:a,type:l,errors:c}=n;return Object.assign(Object.assign({},{schema:i,table:o,commit_timestamp:a,eventType:l,new:{},old:{},errors:c}),this._getPayloadRecords(n))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(let r in e.bindings)for(let s of e.bindings[r])this._on(s.type,s.filter,s.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=vr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=vr(e.columns,e.old_record)),r}};var ut=class{constructor(e,r){this.socket=new Ss(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,s,n=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{e(),i("ok")},r,s)})}push(e){this.socket.push(e)}log(e,r,s){this.socket.log(e,r,s)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==nt.connecting}isDisconnecting(){return this.socket.connectionState()==nt.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var As={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},_i=[1e3,2e3,5e3,1e4],wi=1e4;function vi(){let t=new Map;return{get length(){return t.size},clear(){t.clear()},getItem(e){return t.has(e)?t.get(e):null},key(e){var r;return(r=Array.from(t.keys())[e])!==null&&r!==void 0?r:null},removeItem(e){t.delete(e)},setItem(e,r){t.set(e,String(r))}}}function bi(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return vi()}var Si=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`,Fe=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var s;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new it,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=i=>i?(...o)=>i(...o):(...o)=>fetch(...o),!(!((s=r?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let n=this._initializeOptions(r);this.socketAdapter=new ut(e,n),this.httpEndpoint=Lt(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let r=e.message;throw r.includes("Node.js")?new Error(`${r} To use Realtime in Node.js, you need to provide a WebSocket implementation: Option 1: Use Node.js 22+ which has native WebSocket support Option 2: Install and provide the "ws" package: npm install ws import ws from "ws" const client = new RealtimeClient(url, { ...options, transport: ws })`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),r}async removeAllChannels(){let e=this.channels.map(async s=>{let n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return await this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}connectionState(){return this.socketAdapter.connectionState()||nt.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{let i=new Me(`realtime:${e}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(i),i}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let i={access_token:r,version:ps};r&&n.updateJoinPayload(i),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(Ut.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,s)}}_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=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.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)}_workerObjectUrl(e){let r;if(e)r=e;else{let s=new Blob([Si],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,i,o,a,l,c,u,h,f,d;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e?.accessToken)!==null&&s!==void 0?s:null;let p={};p.timeout=(n=e?.timeout)!==null&&n!==void 0?n:ms,p.heartbeatIntervalMs=(i=e?.heartbeatIntervalMs)!==null&&i!==void 0?i:As.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(o=e?.disconnectOnEmptyChannelsAfterMs)!==null&&o!==void 0?o:2*((a=e?.heartbeatIntervalMs)!==null&&a!==void 0?a:As.HEARTBEAT_INTERVAL),p.transport=(l=e?.transport)!==null&&l!==void 0?l:mr.getWebSocketConstructor(),p.params=e?.params,p.logger=e?.logger,p.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),p.sessionStorage=(c=e?.sessionStorage)!==null&&c!==void 0?c:bi(),p.reconnectAfterMs=(u=e?.reconnectAfterMs)!==null&&u!==void 0?u:(y=>_i[y-1]||wi);let g,_,w=(h=e?.vsn)!==null&&h!==void 0?h:ys;switch(w){case gs:g=(y,m)=>m(JSON.stringify(y)),_=(y,m)=>m(JSON.parse(y));break;case _r:g=this.serializer.encode.bind(this.serializer),_=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${p.vsn}`)}if(p.vsn=w,p.encode=(f=e?.encode)!==null&&f!==void 0?f:g,p.decode=(d=e?.decode)!==null&&d!==void 0?d:_,p.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,p.params=Object.assign(Object.assign({},p.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,p.autoSendHeartbeat=!this.worker}return p}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var ht=class extends Error{constructor(t,e){super(t),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")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function ki(t,e,r){let s=new URL(e,t);if(r)for(let[n,i]of Object.entries(r))i!==void 0&&s.searchParams.set(n,i);return s.toString()}async function Ei(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Ti(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:o}){let a=ki(t.baseUrl,s,n),l=await Ei(t.auth),c=await e(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),u=await c.text(),h=(c.headers.get("content-type")||"").includes("application/json"),f=h&&u?JSON.parse(u):u;if(!c.ok){let d=h?f:void 0,p=d?.error;throw new ht(p?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:p?.type,icebergCode:p?.code,details:d})}return{status:c.status,headers:c.headers,data:f}}}}function Mt(t){return t.join("")}var Ai=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:Mt(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Mt(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Mt(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Mt(t.namespace)}`}),!0}catch(e){if(e instanceof ht&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof ht&&r.status===409)return;throw r}}};function He(t){return t.join("")}var Ri=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof ht&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof ht&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Rs=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Ti({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new Ai(this.client,e),this.tableOps=new Ri(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function ft(t){"@babel/helpers - typeof";return ft=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},ft(t)}function Oi(t,e){if(ft(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(ft(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function xi(t){var e=Oi(t,"string");return ft(e)=="symbol"?e:e+""}function Ci(t,e,r){return(e=xi(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Os(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function k(t){for(var e=1;et?(...e)=>t(...e):(...e)=>fetch(...e),ji=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Ar=t=>{if(Array.isArray(t))return t.map(r=>Ar(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,s])=>{let n=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=Ar(s)}),e},Ni=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),xs=t=>{if(typeof t=="object"&&t!==null){let e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){let r=e.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(t)},Ui=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&"json"in t&&typeof t.json=="function"){let n=t,i=parseInt(String(n.status),10);Number.isFinite(i)||(i=500),n.json().then(o=>{let a=o?.statusCode||o?.code||i+"";e(new Ft(xs(o),i,a,s))}).catch(()=>{let o=i+"";e(new Ft(n.statusText||`HTTP ${i} error`,i,o,s))})}else e(new Ps(xs(t),t,s))},Li=(t,e,r,s)=>{let n={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!s)return k(k({},n),r);if(ji(s)){var i;let o=e?.headers||{},a;for(let[l,c]of Object.entries(o))l.toLowerCase()==="content-type"&&(a=c);n.headers=Ht(o,"Content-Type",(i=a)!==null&&i!==void 0?i:"application/json"),n.body=JSON.stringify(s)}else n.body=s;return e?.duplex&&(n.duplex=e.duplex),k(k({},n),r)};async function dt(t,e,r,s,n,i,o){return new Promise((a,l)=>{t(r,Li(e,s,n,i)).then(c=>{if(!c.ok)throw c;if(s?.noResolveJson)return c;if(o==="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=>a(c)).catch(c=>Ui(c,l,s,o))})}function Is(t="storage"){return{get:async(e,r,s,n)=>dt(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>dt(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>dt(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>dt(e,"HEAD",r,k(k({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>dt(e,"DELETE",r,n,i,s,t)}}var $i=Is("storage"),{get:pt,post:te,put:Rr,head:Di,remove:gt}=$i,J=Is("vectors"),Ke=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=Pi(e),this.fetch=Ii(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=Ht(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Wt(r))return{data:null,error:r};throw r}}},js;js=Symbol.toStringTag;var Bi=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[js]="StreamDownloadBuilder",this.promise=null}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Wt(e))return{data:null,error:e};throw e}}},Ns;Ns=Symbol.toStringTag;var qi=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Ns]="BlobDownloadBuilder",this.promise=null}asStream(){return new Bi(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Wt(e))return{data:null,error:e};throw e}}},Tr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Cs={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Mi=class extends Ke{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var n=this;return n.handleOperation(async()=>{let i,o=k(k({},Cs),s),a=k(k({},n.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;if(typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),s?.headers)for(let[f,d]of Object.entries(s.headers))a=Ht(a,f,d);let c=n._removeEmptyFolders(e),u=n._getFinalPath(c),h=await(t=="PUT"?Rr:te)(n.fetch,`${n.url}/object/${u}`,i,k({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:c,id:h.Id,fullPath:h.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;let i=n._removeEmptyFolders(t),o=n._getFinalPath(i),a=new URL(n.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,c=k(k({},Cs),s),u=k(k({},n.headers),{"x-upsert":String(c.upsert)}),h=c.metadata;if(typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),h&&l.append("metadata",n.encodeMetadata(h)),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.has("cacheControl")||l.append("cacheControl",c.cacheControl),h&&!l.has("metadata")&&l.append("metadata",n.encodeMetadata(h))):(l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType,h&&(u["x-metadata"]=n.toBase64(n.encodeMetadata(h))),(typeof ReadableStream<"u"&&l instanceof ReadableStream||l&&typeof l=="object"&&"pipe"in l&&typeof l.pipe=="function")&&!c.duplex&&(c.duplex="half")),s?.headers)for(let[f,d]of Object.entries(s.headers))u=Ht(u,f,d);return{path:i,fullPath:(await Rr(n.fetch,a.toString(),l,k({headers:u},c?.duplex?{duplex:c.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t),n=k({},r.headers);e?.upsert&&(n["x-upsert"]="true");let i=await te(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new Kt("No token returned by API");return{signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await te(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await te(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t),i=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await te(s.fetch,`${s.url}/object/sign/${n}`,k({expiresIn:e},i?{transform:r.transform}:{}),{headers:s.headers}),a=new URLSearchParams;r?.download&&a.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&a.set("cacheNonce",String(r.cacheNonce));let l=a.toString();return{signedUrl:encodeURI(`${s.url}${o.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{let n=await te(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=new URLSearchParams;r?.download&&i.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&i.set("cacheNonce",String(r.cacheNonce));let o=i.toString();return n.map(a=>k(k({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${o?`&${o}`:""}`):null}))})}download(t,e,r){let s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",n=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));let i=n.toString(),o=this._getFinalPath(t),a=()=>pt(this.fetch,`${this.url}/${s}/${o}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new qi(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>Ar(await pt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await Di(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(Wt(n)){var s;let i=n instanceof Ft?n.status:n instanceof Ps?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),s=new URLSearchParams;e?.download&&s.set("download",e.download===!0?"":e.download),e?.transform&&this.applyTransformOptsToQuery(s,e.transform),e?.cacheNonce!=null&&s.set("cacheNonce",String(e.cacheNonce));let n=s.toString(),i=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}`)+(n?`?${n}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await gt(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async purgeCache(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t),i=new URLSearchParams;e?.transformations&&i.set("transformations","true");let o=i.toString();return await gt(s.fetch,`${s.url}/cdn/${n}${o?`?${o}`:""}`,{},{headers:s.headers},r)})}async list(t,e,r){var s=this;return s.handleOperation(async()=>{let n=e?.sortBy?k(k({},Tr.sortBy),e.sortBy):Tr.sortBy,i=k(k(k({},Tr),e),{},{sortBy:n,prefix:t||""});return await te(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let s=k({},t);return await te(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}},Fi="2.109.0",yt={"X-Client-Info":`storage-js/${Fi}`},Hi=class extends Ke{constructor(t,e={},r,s){let n=new URL(t);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(/\/$/,""),o=k(k({},yt),e);super(i,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await pt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await pt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await te(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await Rr(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await te(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await gt(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}async purgeBucketCache(t,e,r){var s=this;return s.handleOperation(async()=>{let n=new URLSearchParams;e?.transformations&&n.set("transformations","true");let i=n.toString();return await gt(s.fetch,`${s.url}/cdn/${t}${i?`?${i}`:""}`,{},{headers:s.headers},r)})}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Ki=class extends Ke{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=k(k({},yt),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await te(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await pt(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await gt(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Ni(t))throw new Kt("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new Rs({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){let o=n[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(n,a),error:null}}catch(l){if(s)throw l;return{data:null,error:l}}}}})}},Wi=class extends Ke{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=k(k({},yt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await J.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await J.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Vi=class extends Ke{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=k(k({},yt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},zi=class extends Ke{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=k(k({},yt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Ji=class extends zi{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Gi(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},Gi=class extends Wi{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,k(k({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,k(k({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Yi(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Yi=class extends Vi{constructor(t,e,r,s,n){super(t,e,n),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,k(k({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,k(k({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,k(k({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,k(k({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,k(k({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Us=class extends Hi{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new Mi(this.url,this.headers,t,this.fetch)}get vectors(){return new Ji(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Ki(this.url+"/iceberg",this.headers,this.fetch)}};var Vt="2.109.0";var ae=30*1e3,We=3,zt=We*ae,Ls=2*ae,$s="http://localhost:9999",Ds="supabase.auth.token";var Bs={"X-Client-Info":`gotrue-js/${Vt}`};var mt="X-Supabase-Api-Version",Or={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},qs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Ms=600*1e3;var ge=class extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}};function v(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Jt=class extends ge{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}};function Fs(t){return v(t)&&t.name==="AuthApiError"}var M=class extends ge{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},Z=class extends ge{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}},U=class extends Z{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function bt(t){return v(t)&&t.name==="AuthSessionMissingError"}var he=class extends Z{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Ee=class extends Z{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Te=class extends Z{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};function Hs(t){return v(t)&&t.name==="AuthImplicitGrantRedirectError"}var _t=class extends Z{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},Gt=class extends Z{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 Ve=class extends Z{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function xr(t){return v(t)&&t.name==="AuthRetryableFetchError"}var wt=class extends Z{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}};function Ks(t){return v(t)&&t.name==="AuthRefreshDiscardedError"}var vt=class extends Z{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}};var ye=class extends Z{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var Yt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ws=` \r=`.split(""),Xi=(()=>{let t=new Array(128);for(let e=0;e=6;){let s=e.queue>>e.queuedBits-6&63;r(Yt[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;r(Yt[s]),e.queuedBits-=6}}function zs(t,e,r){let s=Xi[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Cr(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=o=>{eo(o,s,r)};for(let o=0;o>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Zi(t,e){for(let r=0;r55295&&s<=56319){let n=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}Qi(s,e)}}function eo(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if((t>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function me(t){let e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;ne.push(r)),new Uint8Array(e)}function de(t){let e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>Vs(n,r,s)),Vs(null,r,s),e.join("")}function Gs(t){return Math.round(Date.now()/1e3)+t}function Ys(){return Symbol("auth-callback")}var D=()=>typeof window<"u"&&typeof document<"u",Ae={tested:!1,writable:!1},Xt=()=>{if(!D())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ae.tested)return Ae.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Ae.tested=!0,Ae.writable=!0}catch{Ae.tested=!0,Ae.writable=!1}return Ae.writable};function Xs(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return r.searchParams.forEach((s,n)=>{e[n]=s}),e}var Qt=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Qs=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Re=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},ee=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return null}},L=async(t,e)=>{await t.removeItem(e)},St=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};St.promiseConstructor=Promise;function kt(t){let e=t.split(".");if(e.length!==3)throw new ye("Invalid JWT structure");for(let s=0;s{setTimeout(()=>e(null),t)})}function en(t,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await t(i);if(!e(i,null,o)){s(o);return}}catch(o){if(!e(i,o)){n(o);return}}})()})}function to(t){return("0"+t.toString(16)).substr(-2)}function ro(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length,n="";for(let i=0;i<56;i++)n+=r.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,to).join("")}async function so(t){let r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function no(t){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."),t;let r=await so(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _e(t,e,r=!1){let s=ro(),n=s;r&&(n+="/recovery"),await Re(t,`${e}-code-verifier`,n);let i=await no(s);return[i,s===i?"plain":"s256"]}var io=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function tn(t){let e=t.headers.get(mt);if(!e||!e.match(io))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function rn(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function sn(t){switch(t){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 oo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function le(t){if(!oo.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function G(t){if(!t.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function Zt(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let s=r.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 "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function nn(t,e){return new Proxy(t,{get:(r,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;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(r,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=!0),Reflect.get(r,s,n)}})}function Pr(t){return JSON.parse(JSON.stringify(t))}var Oe=t=>{if(typeof t=="object"&&t!==null){let e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(t)},ao=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function on(t){var e;if(!Qs(t))throw new Ve(Oe(t),0);if(ao.includes(t.status))throw new Ve(Oe(t),t.status);let r;try{r=await t.json()}catch(i){throw new M(Oe(i),i)}let s,n=tn(t);if(n&&n.getTime()>=Or["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new vt(Oe(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new U}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new vt(Oe(r),t.status,r.weak_password.reasons);throw new Jt(Oe(r),t.status||500,s)}var lo=(t,e,r,s)=>{let n={method:t,headers:e?.headers||{}};return t==="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),r))};async function S(t,e,r,s){var n;let i=Object.assign({},s?.headers);i[mt]||(i[mt]=Or["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);let o=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await co(t,e,r+a,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function co(t,e,r,s,n,i){let o=lo(e,s,n,i),a;try{a=await t(r,Object.assign({},o))}catch(l){throw console.error(l),new Ve(Oe(l),0)}if(a.ok||await on(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await on(l)}}function Y(t){var e;let r=null;uo(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Gs(t.expires_in)));let s=(e=t.user)!==null&&e!==void 0?e:typeof t?.id=="string"?t:null;return{data:{session:r,user:s},error:null}}function Ir(t){let e=Y(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function ce(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function an(t){return{data:t,error:null}}function ln(t){let{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,o=Se(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function jr(t){return t}function uo(t){return!!t.access_token&&!!t.refresh_token&&!!t.expires_in}var er=["global","local","others"];var xe=class{constructor({url:e="",headers:r={},fetch:s,experimental:n}){this.url=e,this.headers=r,this.fetch=Qt(s),this.experimental=n??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,r=er[0]){if(er.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${er.join(", ")}`);try{return await S(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(v(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await S(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:ce})}catch(s){if(v(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:r}=e,s=Se(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await S(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:ln,redirectTo:r?.redirectTo})}catch(r){if(v(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await S(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ce})}catch(r){if(v(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await S(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.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:jr});if(u.error)throw u.error;let h=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,d=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return d.length>0&&(d.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(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(v(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){le(e);try{return await S(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ce})}catch(r){if(v(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){le(e);try{return await S(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:ce})}catch(s){if(v(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){le(e);try{return await S(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:ce})}catch(s){if(v(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){le(e.userId);try{let{data:r,error:s}=await S(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if(v(r))return{data:null,error:r};throw r}}async _deleteFactor(e){le(e.userId),le(e.id);try{return{data:await S(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(v(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await S(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.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:jr});if(u.error)throw u.error;let h=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,d=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return d.length>0&&(d.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(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(v(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await S(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await S(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await S(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(v(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await S(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await S(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await S(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(v(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await S(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await S(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await S(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(v(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await S(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return{data:null,error:r};throw r}}async _adminListPasskeys(e){G(this.experimental),le(e.userId);try{return await S(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(e){G(this.experimental),le(e.userId),le(e.passkeyId);try{return await S(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return{data:null,error:r};throw r}}};function Nr(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var ho={debug:!!(globalThis&&Xt()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},tr=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};function cn(){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 Ur(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function un(t){return parseInt(t,16)}function hn(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function dn(t){var e;let{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:h,version:f}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(` `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let d=Ur(t.address),p=u?`${u}://${s}`:s,g=t.statement?`${t.statement} `:"",_=`${p} wants you to sign in with your Ethereum account: ${d} ${g}`,w=`URI: ${h} Version: ${f} Chain ID: ${r}${o?` Nonce: ${o}`:""} Issued At: ${i.toISOString()}`;if(n&&(w+=` Expiration Time: ${n.toISOString()}`),a&&(w+=` Not Before: ${a.toISOString()}`),l&&(w+=` Request ID: ${l}`),c){let y=` Resources:`;for(let m of c){if(!m||typeof m!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${m}`);y+=` - ${m}`}w+=y}return`${_} ${w}`}var N=class extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}},Ce=class extends N{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function fn({error:t,options:e}){var r,s,n;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new N({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new N({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new N({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new N({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new N({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new N({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new N({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new N({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Lr(o)){if(i.rp.id!==o)return new N({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new N({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new N({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new N({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new N({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function pn({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new N({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new N({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let s=window.location.hostname;if(Lr(s)){if(r.rpId!==s)return new N({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new N({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new N({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new N({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var $r=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}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}}},nr=new $r;function Dr(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:s}=t,n=Se(t,["challenge","user","excludeCredentials"]),i=me(e).buffer,o=Object.assign(Object.assign({},r),{id:me(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:i,user:o});if(s&&s.length>0){a.excludeCredentials=new Array(s.length);for(let l=0;l0){i.allowCredentials=new Array(r.length);for(let o=0;on!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(let n of t)if(n)for(let i in n){let o=n[i];if(o!==void 0)if(Array.isArray(o))s[i]=o;else if(r(o))s[i]=o;else if(e(o)){let a=s[i];e(a)?s[i]=rr(a,o):s[i]=rr(o)}else s[i]=o}return s}function go(t,e){return rr(fo,t,e||{})}function yo(t,e){return rr(po,t,e||{})}var sr=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:r,friendlyName:s,signal:n},i){var o;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let c=n??nr.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let h=s;if(h)u.name=`${u.id}:${h}`;else{let d=(await this.client.getUser()).data.user,p=((o=d?.user_metadata)===null||o===void 0?void 0:o.name)||d?.email||d?.id||"User";u.name=`${u.id}:${p}`}}u.displayName||(u.displayName=u.name)}switch(a.webauthn.type){case"create":{let u=go(a.webauthn.credential_options.publicKey,i?.create),{data:h,error:f}=await Fr({publicKey:u,signal:c});return h?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:h}},error:null}:{data:null,error:f}}case"request":{let u=yo(a.webauthn.credential_options.publicKey,i?.request),{data:h,error:f}=await Hr(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:c}));return h?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:h}},error:null}:{data:null,error:f}}}}catch(a){return v(a)?{data:null,error:a}:{data:null,error:new M("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new ge("rpId is required for WebAuthn authentication")};try{if(!Et())return{data:null,error:new M("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!o)return{data:null,error:a};let{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:s,credential_response:l.credential_response}})}catch(o){return v(o)?{data:null,error:o}:{data:null,error:new M("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new ge("rpId is required for WebAuthn registration")};try{if(!Et())return{data:null,error:new M("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var h;return(h=u.data)===null||h===void 0?void 0:h.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};let{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return v(o)?{data:null,error:o}:{data:null,error:new M("Unexpected error in register",o)}}}};cn();var mo={url:$s,storageKey:Ds,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Bs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var ze={},ir=class t{get jwks(){var e,r;return(r=(e=ze[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){ze[this.storageKey]=Object.assign(Object.assign({},ze[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=ze[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ze[this.storageKey]=Object.assign(Object.assign({},ze[this.storageKey]),{cachedAt:e})}constructor(e){var r,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.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},mo),e);if(this.storageKey=i.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&D()){let o=`${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(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(s=i.experimental)!==null&&s!==void 0?s:{},this.admin=new xe({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Qt(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new sr(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:Xt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Nr(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Nr(this.memoryStorage)),D()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Vt}) ${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()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())(),await this.initializePromise)}async _initialize(){var e;try{let r={},s="none";if(D()&&(r=Xs(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),D()&&this.detectSessionInUrl&&s!=="none"){let{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Hs(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:o,redirectType:a}=n;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return v(r)?this._returnResult({error:r}):this._returnResult({error:new M("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{let i=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:Y}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(v(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;try{let i;if("email"in e){let{email:u,password:h,options:f}=e,d=null,p=null;this.flowType==="pkce"&&([d,p]=await _e(this.storage,this.storageKey)),i=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:u,password:h,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:d,code_challenge_method:p},xform:Y})}else if("phone"in e){let{phone:u,password:h,options:f}=e;i=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:Y})}else throw new Ee("You must provide either an email or phone number and a password");let{data:o,error:a}=i;if(a||!o)return await L(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(await L(this.storage,`${this.storageKey}-code-verifier`),v(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){let{email:i,password:o,options:a}=e;r=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ir})}else if("phone"in e){let{phone:i,password:o,options:a}=e;r=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ir})}else throw new Ee("You must provide either an email or phone number and a password");let{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){let i=new he;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(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.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.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e)):this._exchangeCodeForSession(e)}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,o,a,l,c,u,h,f;let d,p;if("message"in e)d=e.message,p=e.signature;else{let{chain:g,wallet:_,statement:w,options:y}=e,m;if(D())if(typeof _=="object")m=_;else{let K=window;if("ethereum"in K&&typeof K.ethereum=="object"&&"request"in K.ethereum&&typeof K.ethereum.request=="function")m=K.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"||!y?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");m=_}let E=new URL((r=y?.url)!==null&&r!==void 0?r:window.location.href),R=await m.request({method:"eth_requestAccounts"}).then(K=>K).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!R||R.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let b=Ur(R[0]),O=(s=y?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!O){let K=await m.request({method:"eth_chainId"});O=un(K)}let B={domain:E.host,address:b,statement:w,uri:E.href,version:"1",chainId:O,nonce:(n=y?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(o=(i=y?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=y?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=y?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=y?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=y?.signInWithEthereum)===null||u===void 0?void 0:u.resources};d=dn(B),p=await m.request({method:"personal_sign",params:[hn(d),b]})}try{let{data:g,error:_}=await S(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:p},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:Y});if(_)throw _;if(!g||!g.session||!g.user){let w=new he;return this._returnResult({data:{user:null,session:null},error:w})}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(v(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,s,n,i,o,a,l,c,u,h,f,d;let p,g;if("message"in e)p=e.message,g=e.signature;else{let{chain:_,wallet:w,statement:y,options:m}=e,E;if(D())if(typeof w=="object")E=w;else{let b=window;if("solana"in b&&typeof b.solana=="object"&&("signIn"in b.solana&&typeof b.solana.signIn=="function"||"signMessage"in b.solana&&typeof b.solana.signMessage=="function"))E=b.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 w!="object"||!m?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=w}let R=new URL((r=m?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in E&&E.signIn){let b=await E.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},m?.signInWithSolana),{version:"1",domain:R.host,uri:R.href}),y?{statement:y}:null)),O;if(Array.isArray(b)&&b[0]&&typeof b[0]=="object")O=b[0];else if(b&&typeof b=="object"&&"signedMessage"in b&&"signature"in b)O=b;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in O&&"signature"in O&&(typeof O.signedMessage=="string"||O.signedMessage instanceof Uint8Array)&&O.signature instanceof Uint8Array)p=typeof O.signedMessage=="string"?O.signedMessage:new TextDecoder().decode(O.signedMessage),g=O.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in E)||typeof E.signMessage!="function"||!("publicKey"in E)||typeof E!="object"||!E.publicKey||!("toBase58"in E.publicKey)||typeof E.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${R.host} wants you to sign in with your Solana account:`,E.publicKey.toBase58(),...y?["",y,""]:[""],"Version: 1",`URI: ${R.href}`,`Issued At: ${(n=(s=m?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=m?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${m.signInWithSolana.notBefore}`]:[],...!((o=m?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${m.signInWithSolana.expirationTime}`]:[],...!((a=m?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${m.signInWithSolana.chainId}`]:[],...!((l=m?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${m.signInWithSolana.nonce}`]:[],...!((c=m?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${m.signInWithSolana.requestId}`]:[],...!((h=(u=m?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",...m.signInWithSolana.resources.map(O=>`- ${O}`)]:[]].join(` `);let b=await E.signMessage(new TextEncoder().encode(p),"utf8");if(!b||!(b instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=b}}try{let{data:_,error:w}=await S(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:de(g)},!((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:Y});if(w)throw w;if(!_||!_.session||!_.user){let y=new he;return this._returnResult({data:{user:null,session:null},error:y})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:w})}catch(_){if(v(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){let r=await ee(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new Gt;let{data:i,error:o}=await S(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:Y});if(await L(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let a=new he;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers(n==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:o})}catch(i){if(await L(this.storage,`${this.storageKey}-code-verifier`),v(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:r,provider:s,token:n,access_token:i,nonce:o}=e,a=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:Y}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){let u=new he;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(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,o;try{if("email"in e){let{email:a,options:l}=e,c=null,u=null;this.flowType==="pkce"&&([c,u]=await _e(this.storage,this.storageKey));let{error:h}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},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:h})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:u}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,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:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:u})}throw new Ee("You must provide either an email or phone number.")}catch(a){if(await L(this.storage,`${this.storageKey}-code-verifier`),v(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:Y});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.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(v(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await _e(this.storage,this.storageKey));let c=await S(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=(r=e.options)===null||r===void 0?void 0:r.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:a,code_challenge_method:l}),headers:this.headers,xform:an});return!((i=c.data)===null||i===void 0)&&i.url&&D()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await L(this.storage,`${this.storageKey}-code-verifier`),v(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new U;let{error:n}=await S(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(v(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:n,options:i}=e,o=null,a=null;this.flowType==="pkce"&&([o,a]=await _e(this.storage,this.storageKey));let{error:l}=await S(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken},code_challenge:o,code_challenge_method:a},redirectTo:i?.emailRedirectTo});return l&&await L(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l})}else if("phone"in e){let{phone:s,type:n,options:i}=e,{data:o,error:a}=await S(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new Ee("You must provide either an email or phone number and a type")}catch(r){if(await L(this.storage,`${this.storageKey}-code-verifier`),v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,r){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 r()))();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=r();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 r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await ee(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(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()Date.now())){let a=await ee(this.storage,this.storageKey);if(a&&a.refresh_token===e.refresh_token)return this._returnResult({data:{session:e},error:null})}return this._returnResult({data:{session:null},error:i})}return 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 r;return this.lock!=null?r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):r=await this._getUser(),r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ce}):await this._useSession(async r=>{var s,n,i;let{data:o,error:a}=r;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new U}:await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:ce})})}catch(r){if(v(r))return bt(r)&&(await this._removeSession(),await L(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r)):await this._updateUser(e,r)}async _updateUser(e,r={}){try{return await this._useSession(async s=>{let{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new U;let o=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await _e(this.storage,this.storageKey));let{data:c,error:u}=await S(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:ce});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(s){if(await L(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new U;let r=Date.now()/1e3,s=r,n=!0,i=null,{payload:o}=kt(e.access_token);if(o.exp&&(s=o.exp,n=s<=r),n){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{let{data:a,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:a.user,token_type:"bearer",expires_in:s-r,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(r){if(v(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new U;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(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!D())throw new Te("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Te(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new _t("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Te("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new _t("No code detected.");let{data:m,error:E}=await this._exchangeCodeForSession(e.code);if(E)throw E;let R=new URL(window.location.href);return R.searchParams.delete("code"),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:m.session,redirectType:(s=m.redirectType)!==null&&s!==void 0?s:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:o,refresh_token:a,expires_in:l,expires_at:c,token_type:u}=e;if(!o||!l||!a||!u)throw new Te("No session defined in URL");let h=Math.round(Date.now()/1e3),f=parseInt(l),d=h+f;c&&(d=parseInt(c));let p=d-h;p*1e3<=ae&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${f}s`);let g=d-f;h-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,d,h):h-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,d,h);let{data:_,error:w}=await this._getUser(o);if(w)throw w;let y={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:f,expires_at:d,refresh_token:a,token_type:u,user:_.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(n){if(v(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){let r=await ee(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;let{data:n,error:i}=r;if(i&&!bt(i))return this._returnResult({error:i});let o=(s=n.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Fs(a)&&(a.status===404||a.status===401||a.status===403)||bt(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await L(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Ys(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)}):await this._emitInitialSession(r)))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{let{data:{session:i},error:o}=r;if(o)throw o;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),bt(i)?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await _e(this.storage,this.storageKey,!0));try{return await S(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await L(this.storage,`${this.storageKey}-code-verifier`),v(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:s,error:n}=await this._useSession(async i=>{var o,a,l,c,u;let{data:h,error:f}=i;if(f)throw f;let d=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await S(this.fetch,"GET",d,{headers:this.headers,jwt:(u=(c=h.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return D()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url},error:null})}catch(s){if(v(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{let{error:n,data:{session:i}}=r;if(n)throw n;let{options:o,provider:a,token:l,access_token:c,nonce:u}=e,h=await S(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:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:Y}),{data:f,error:d}=h;return d?this._returnResult({data:{user:null,session:null},error:d}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new he}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:d}))}catch(n){if(await L(this.storage,`${this.storageKey}-code-verifier`),v(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)throw o;return await S(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(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r="#_refreshAccessToken()";this._debug(r,"begin");try{let s=Date.now();return await en(async n=>(n>0&&await Zs(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await S(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Y})),(n,i)=>{let o=200*Math.pow(2,n);return i&&xr(i)&&Date.now()+o-sDate.now())?this._debug(n,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+Ls},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;athis._autoRefreshTokenTick(),ae);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/ae);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${ae}ms, refresh threshold is ${We} ticks`),n<=We&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof tr)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async r=>{let{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/ae);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${ae}ms, refresh threshold is ${We} ticks`),n<=We&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!D()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;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 r=`#_onVisibilityChanged(${e})`;if(this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(r,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){let n=[`provider=${encodeURIComponent(r)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[i,o]=await _e(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.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 r=>{var s;let{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await S(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(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=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 S(this.fetch,"POST",`${this.url}/factors`,{body:a,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(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?qr(e.webauthn.credential_response):Mr(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:c}))})}catch(s){if(v(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let a=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(a.error)return a;let{data:l}=a;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:Dr(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:Br(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(v(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){let{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};let n={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=r?.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 r,s,n,i;if(e)try{let{payload:d}=kt(e),p=null;d.aal&&(p=d.aal);let g=p,{data:{user:_},error:w}=await this.getUser(e);if(w)return this._returnResult({data:null,error:w});((s=(r=_?.factors)===null||r===void 0?void 0:r.filter(E=>E.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(g="aal2");let m=d.amr||[];return{data:{currentLevel:p,nextLevel:g,currentAuthenticationMethods:m},error:null}}catch(d){if(v(d))return this._returnResult({data:null,error:d});throw d}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=kt(o.access_token),c=null;l.aal&&(c=l.aal);let u=c;((i=(n=o.user.factors)===null||n===void 0?void 0:n.filter(d=>d.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");let f=l.amr||[];return{data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await S(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 U})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){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 U});let o=await S(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&D()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if(v(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){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 U});let o=await S(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&D()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if(v(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await S(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new U})})}catch(e){if(v(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await S(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 U})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(a=>a.kid===e);if(s)return s;let n=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+Ms>n)return s;let{data:i,error:o}=await S(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){let{data:d,error:p}=await this.getSession();if(p||!d.session)return this._returnResult({data:null,error:p});s=d.session.access_token}let{header:n,payload:i,signature:o,raw:{header:a,payload:l}}=kt(s);if(!r?.allowExpired)try{rn(i.exp)}catch(d){throw new ye(d instanceof Error?d.message:"JWT validation failed")}let c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:d}=await this.getUser(s);if(d)throw d;return{data:{claims:i,header:n,signature:o},error:null}}let u=sn(n.alg),h=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,o,Js(`${a}.${l}`)))throw new ye("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(s){if(v(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n;G(this.experimental);try{if(!Et())return this._returnResult({data:null,error:new M("Browser does not support WebAuthn",null)});let{data:i,error:o}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(o||!i)return this._returnResult({data:null,error:o});let a=Br(i.options),l=(n=(s=e?.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:nr.createNewAbortSignal(),{data:c,error:u}=await Hr({publicKey:a,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new M("WebAuthn ceremony failed",null)});let h=Mr(c);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:h})}catch(i){if(v(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var r,s;G(this.experimental);try{if(!Et())return this._returnResult({data:null,error:new M("Browser does not support WebAuthn",null)});let{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});let o=Dr(n.options),a=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:nr.createNewAbortSignal(),{data:l,error:c}=await Fr({publicKey:o,signal:a});if(c||!l)return this._returnResult({data:null,error:c??new M("WebAuthn ceremony failed",null)});let u=qr(l);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:u})}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){G(this.experimental);try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new U});let{data:n,error:i}=await S(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(v(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){G(this.experimental);try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new U});let{data:i,error:o}=await S(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;G(this.experimental);try{let{data:s,error:n}=await S(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(v(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){G(this.experimental);try{let{data:r,error:s}=await S(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Y});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){G(this.experimental);try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new U});let{data:n,error:i}=await S(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(v(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){G(this.experimental);try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new U});let{data:i,error:o}=await S(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){G(this.experimental);try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new U});let{error:i}=await S(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}};ir.nextInstanceID={};var Kr=ir;var _o=Kr,Wr=_o;var wo="2.109.0",Tt="",lr;typeof Deno<"u"?(Tt="deno",lr=(or=Deno.version)===null||or===void 0?void 0:or.deno):typeof document<"u"?Tt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Tt="react-native":(Tt="node",lr=typeof process<"u"?(ar=process.version)===null||ar===void 0?void 0:ar.replace(/^v/,""):void 0);var or,ar,mn=[`runtime=${Tt}`];lr&&mn.push(`runtime-version=${lr}`);var vo={"X-Client-Info":`supabase-js/${wo}; ${mn.join("; ")}`},bo={headers:vo},So={schema:"public"},ko={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Eo={},To={enabled:!1,respectSamplingDecision:!0};function Ao(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):n(u.value).then(a,l)}c((s=s.apply(t,e||[])).next())})}var Vr=null,Ro="@opentelemetry/api";function Oo(){return Vr===null&&(Vr=import(Ro).catch(()=>null)),Vr}function xo(){return Ao(this,void 0,void 0,function*(){try{let t=yield Oo();if(!t||!t.propagation||!t.context)return null;let e={};t.propagation.inject(t.context.active(),e);let r=e.traceparent;return r?{traceparent:r,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function Co(t){if(!t||typeof t!="string")return null;let e=t.split("-");if(e.length!==4)return null;let[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;let o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(s)||!o.test(n)||!o.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function Po(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(let s of e)try{if(typeof s=="string"){if(Io(r.hostname,s))return!0}else if(s instanceof RegExp){if(s.test(r.hostname))return!0}else if(typeof s=="function"&&s(r))return!0}catch{continue}return!1}function Io(t,e){if(e===t)return!0;if(e.startsWith("*.")){let r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function jo(t){let e=[];try{let r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function At(t){"@babel/helpers - typeof";return At=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},At(t)}function No(t,e){if(At(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(At(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Uo(t){var e=No(t,"string");return At(e)=="symbol"?e:e+""}function Lo(t,e,r){return(e=Uo(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function gn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function $(t){for(var e=1;et?(...e)=>t(...e):(...e)=>fetch(...e),Do=()=>Headers,Bo=(t,e,r,s,n)=>{let i=$o(s),o=Do(),a=n?.enabled===!0,l=n?.respectSamplingDecision!==!1,c=a?jo(e):null;return async(u,h)=>{var f;let d=(f=await r())!==null&&f!==void 0?f:t,p=new o(h?.headers);if(p.has("apikey")||p.set("apikey",t),p.has("Authorization")||p.set("Authorization",`Bearer ${d}`),c){let g=await qo(u,c,l);g&&(g.traceparent&&!p.has("traceparent")&&p.set("traceparent",g.traceparent),g.tracestate&&!p.has("tracestate")&&p.set("tracestate",g.tracestate),g.baggage&&!p.has("baggage")&&p.set("baggage",g.baggage))}return i(u,$($({},h),{},{headers:p}))}};async function qo(t,e,r){if(!Po(typeof t=="string"||t instanceof URL?t:t.url,e))return null;let s=await xo();if(!s||!s.traceparent)return null;if(r){let n=Co(s.traceparent);if(n&&!n.isSampled)return null}return s}function yn(t){return typeof t=="boolean"?{enabled:t}:t}function Mo(t){return t.endsWith("/")?t:t+"/"}function Fo(t,e){var r,s,n,i,o,a;let{db:l,auth:c,realtime:u,global:h}=t,{db:f,auth:d,realtime:p,global:g}=e,_=yn(t.tracePropagation),w=yn(e.tracePropagation),y={db:$($({},f),l),auth:$($({},d),c),realtime:$($({},p),u),storage:{},global:$($($({},g),h),{},{headers:$($({},(r=g?.headers)!==null&&r!==void 0?r:{}),(s=h?.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=_?.enabled)!==null&&i!==void 0?i:w?.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(o=(a=_?.respectSamplingDecision)!==null&&a!==void 0?a:w?.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?y.accessToken=t.accessToken:delete y.accessToken,y}function Ho(t){let e=t?.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(Mo(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Ko=class extends Wr{constructor(t){super(t)}},Wo=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;let i=Ho(t);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 o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:So,realtime:Eo,auth:$($({},ko),{},{storageKey:o}),global:bo,tracePropagation:To},l=Fo(r??{},a);if(this.settings=l,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,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} 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=Bo(e,t,this._getAccessToken.bind(this),l.global.fetch,l.tracePropagation),this.realtime=this._initRealtimeClient($({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},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 hs(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 Us(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new rt(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c,experimental:u,lockAcquireTimeout:h,skipAutoInitialize:f},d,p){let g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ko({url:this.authUrl.href,headers:$($({},g),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:l,throwOnError:c,experimental:u,fetch:p,lockAcquireTimeout:h,skipAutoInitialize:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(_=>_.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Fe(this.realtimeUrl.href,$($({},t),{},{params:$($({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},_n=(t,e,r)=>new Wo(t,e,r);function Vo(){if(typeof window<"u")return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Vo()&&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 wn=Object.freeze(["#shop","#shop/products","#shop/vendors","#community","#community/community-content","#encyclopedia","#encyclopedia/encyclopedia-content"]),vn=Object.freeze(["kakao","google","apple"]),zo=Object.freeze(["PC","MOBILE_WEB"]),Jo=new Set(["unauthorized","origin_not_allowed","integration_disabled","integration_not_configured","authentication_unavailable","shopby_unavailable","shopby_auth_failed","invalid_shopby_response"]);function Go(t,e){let r=new URL("./",e),s="#shop";if(wn.includes(t))s=t;else if(typeof t=="string"&&!t.startsWith("//"))try{let n=new URL(t);n.origin===r.origin&&n.pathname===r.pathname&&!n.username&&!n.password&&!n.search&&wn.includes(n.hash)&&(s=n.hash)}catch{}return r.hash=s,r.href}function Yo(t){return!!t&&t.tokenType==="Bearer"&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&Number.isFinite(t.expiresIn)&&t.expiresIn>0&&Number.isFinite(t.refreshTokenExpiresIn)&&t.refreshTokenExpiresIn>0}function zr(t){try{return JSON.stringify(JSON.parse(t),(e,r)=>e==="provider_token"||e==="provider_refresh_token"?void 0:r)}catch{return t}}function bn(t){return{oauth_denied:"\uB85C\uADF8\uC778\uC744 \uC644\uB8CC\uD558\uC9C0 \uC54A\uC558\uC5B4\uC694. \uC6D0\uD558\uB294 \uB85C\uADF8\uC778 \uBC29\uBC95\uC73C\uB85C \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",callback_expired:"\uB85C\uADF8\uC778 \uC5F0\uACB0\uC774 \uB9CC\uB8CC\uB410\uC5B4\uC694. \uB85C\uADF8\uC778 \uD654\uBA74\uC5D0\uC11C \uB2E4\uC2DC \uC2DC\uC791\uD574 \uC8FC\uC138\uC694.",browser_storage_unavailable:"\uBE0C\uB77C\uC6B0\uC800 \uC800\uC7A5 \uACF5\uAC04\uC744 \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC5B4\uC694. \uBE0C\uB77C\uC6B0\uC800 \uC124\uC815\uC744 \uD655\uC778\uD55C \uB4A4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",provider_unavailable:"\uC774 \uB85C\uADF8\uC778 \uBC29\uBC95\uC744 \uC2DC\uC791\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694. \uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",invalid_config:"\uB85C\uADF8\uC778 \uC124\uC815\uC744 \uD655\uC778\uD558\uACE0 \uC788\uC5B4\uC694. \uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",unauthorized:"\uB85C\uADF8\uC778 \uC778\uC99D\uC744 \uB2E4\uC2DC \uD655\uC778\uD574\uC57C \uD574\uC694. \uB2E4\uC2DC \uB85C\uADF8\uC778\uD574 \uC8FC\uC138\uC694.",session_changed:"\uB85C\uADF8\uC778 \uC0C1\uD0DC\uAC00 \uBCC0\uACBD\uB410\uC5B4\uC694. \uB2E4\uC2DC \uC5F0\uACB0\uD574 \uC8FC\uC138\uC694.",origin_not_allowed:"\uD604\uC7AC \uD398\uC774\uC9C0\uC758 \uC1FC\uD551 \uB85C\uADF8\uC778 \uC5F0\uACB0\uC774 \uC544\uC9C1 \uC900\uBE44\uB418\uC9C0 \uC54A\uC558\uC5B4\uC694.",bridge_unreachable:"\uC1FC\uD551 \uB85C\uADF8\uC778 \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694. \uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",integration_disabled:"\uC1FC\uD551 \uB85C\uADF8\uC778 \uC5F0\uACB0\uC744 \uC900\uBE44\uD558\uACE0 \uC788\uC5B4\uC694. \uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",integration_not_configured:"\uC1FC\uD551 \uB85C\uADF8\uC778 \uC5F0\uACB0\uC744 \uC900\uBE44\uD558\uACE0 \uC788\uC5B4\uC694. \uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",signout_failed:"\uB85C\uADF8\uC544\uC6C3\uC744 \uC644\uB8CC\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694. \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694."}[t]||pr(t)}function C(t){let e=new Error(bn(t));return e.code=t,e}function Sn({client:t,supabaseUrl:e,siteUrl:r,pendingStorage:s,fetcher:n=fetch,now:i=Date.now,navigate:o,replaceUrl:a,currentUrl:l,schedule:c=setTimeout,cancel:u=clearTimeout,resolveReturnTo:h=Go,callbackUrl:f=null,pendingKey:d="hellogreency-web-login-pending-v1",serializeReturnTo:p=m=>new URL(m).hash,applyVerifiedSession:g=()=>{},clearVerifiedSession:_=()=>{},platform:w="PC",signupGate:y=null}){if(!zo.includes(w))throw C("invalid_config");let m=new URL("./",r),E=new URL(f||"auth-callback.html",m);if(E.origin!==m.origin)throw C("invalid_config");let R=new Set,b={status:"loading",user:null,errorCode:null},O=0,B=0,K=null,xt=null,X=null,we=null,es=null,Je=!1,Ct=null,Ge=!1,Ye=null,cr=!1,Pt=null,It=null,Xe=!1;function Ie(A){try{return _(A),!0}catch{return!1}}function Q(A){b={...A},R.forEach(x=>x({...b}))}function ve(){return O+=1,K?.abort(),K=null,we=null,xt&&u(xt),xt=null,O}function ur(){X&&u(X),X=c(()=>{X=null,Qe()},0)}async function Qe({expectedAccessToken:A=null}={}){if(Ge)return b;let x=ve();Q({status:"loading",user:null,errorCode:null});let I=null;try{let F=await t.auth.getSession();if(x!==O)return b;if(F.error)throw C("unauthorized");let W=F.data?.session;if(!W){if(!Ie())throw C("browser_storage_unavailable");return Q({status:"signed_out",user:null,errorCode:null}),b}let j=W.access_token;if(typeof j!="string"||!j)throw C("unauthorized");if(A&&j!==A)throw C("session_changed");let H=await t.auth.getUser(j);if(x!==O)return b;let z=H.data?.user;if(H.error||!z?.id||z.id!==W.user?.id)throw C("unauthorized");K=new AbortController;let fe=K;I=c(()=>fe.abort(),2e4);let pe=null;if(y){if(pe=await y.inspect({token:j,user:z,signal:fe.signal}),x!==O)return b;if(pe.needs_consent){if(!Ie())throw C("browser_storage_unavailable");return Q({status:"consent_required",user:{id:z.id},consent:pe,errorCode:null}),b}}let Ze=await n(`${e}/functions/v1/shopby-external-auth/session`,{method:"POST",headers:{Authorization:`Bearer ${j}`,"Content-Type":"application/json"},body:JSON.stringify({platform:w}),signal:fe.signal}),re;try{re=await Ze.json()}catch{throw C("invalid_shopby_response")}if(x!==O)return b;if(!Ze.ok)throw C(Jo.has(re?.error)?re.error:"bridge_unreachable");if(!Yo(re))throw C("invalid_shopby_response");let hr=await t.auth.getSession();if(x!==O)return b;if(hr.error||hr.data?.session?.access_token!==j||hr.data?.session?.user?.id!==z.id)throw C("session_changed");we={accessToken:re.accessToken,expiresAt:i()+re.expiresIn*1e3,userId:z.id},g(re,{userId:z.id}),Q({status:"authenticated",user:{id:z.id,displayName:"\uB0B4 \uACC4\uC815"},signup:pe,errorCode:null}),xt=c(()=>{we=null,Qe()},Math.max(1e3,Math.min(2147483647,re.expiresIn*1e3-3e4)))}catch(F){if(x!==O)return b;we=null;let W=Ie();Q({status:"error",user:null,errorCode:W?F?.code||"bridge_unreachable":"browser_storage_unavailable"})}finally{I&&u(I)}return b}function ts(){try{let A=JSON.parse(s.getItem(d));return!A||!vn.includes(A.provider)||!Number.isFinite(A.startedAt)||i()-A.startedAt>900*1e3||i()0)throw C("callback_expired");if(A!==B)throw C("session_changed");let H=await Qe({expectedAccessToken:j});if(A!==B)throw C("session_changed");if(H.status==="consent_required")return H;if(H.status!=="authenticated")throw C(H.errorCode||"callback_expired");try{s.removeItem(d)}catch{}return o(W),{status:"authenticated"}}catch(j){let H=j?.code||"callback_expired";throw A===B&&Q({status:"error",user:null,errorCode:H}),C(H)}finally{Je=!1}}function Nn(){return Ct||(Ct=jn().finally(()=>{Ct=null})),Ct}async function Un(){y?.clear(),Ge=!0,B+=1,ve();let A=Ie();X&&u(X),X=null,Q({status:"loading",user:null,errorCode:null});try{let{error:x}=await t.auth.signOut({scope:"local"});if(x||!A)throw C("signout_failed");try{s.removeItem(d)}catch{}Q({status:"signed_out",user:null,errorCode:null})}catch{throw Q({status:"error",user:null,errorCode:"signout_failed"}),C("signout_failed")}finally{Ge=!1}}function Ln(A){if(Ye)return Ye;let x=b.user?.id,I=B;return!y||!x||b.status!=="consent_required"?Promise.reject(q("session_changed")):(cr=!0,Pt=x,Ye=(async()=>{let F=await t.auth.getSession(),W=F.data?.session;if(F.error||!W?.access_token||W.user?.id!==x)throw q("session_changed");let j=await t.auth.getUser(W.access_token);if(j.error||j.data?.user?.id!==x||I!==B)throw q("session_changed");let H=new AbortController,z=c(()=>H.abort(),2e4);It=H;let fe;try{fe=await y.complete({...A,token:W.access_token,user:j.data.user,signal:H.signal})}catch(re){throw I!==B?q("session_changed"):re}finally{u(z)}let pe=await t.auth.getSession();if(I!==B||pe.data?.session?.user?.id!==x)throw q("session_changed");let Ze=await Qe();if(I!==B)throw q("session_changed");if(Ze.status!=="authenticated")throw q(Ze.errorCode||"signup_unavailable");return fe})().finally(()=>{cr=!1,Pt=null,It=null,Ye=null,Xe&&!Ge&&!Je?(Xe=!1,ur()):Xe=!1}),Ye)}function $n({callbackPage:A=!1}={}){Je=A,es=t.auth.onAuthStateChange((x,I)=>{if(x==="SIGNED_OUT"){y?.clear(),B+=1,It?.abort(),Xe=!1,ve();let F=Ie();Q({status:F?"signed_out":"error",user:null,errorCode:F?null:"browser_storage_unavailable"});return}if(["INITIAL_SESSION","SIGNED_IN","USER_UPDATED"].includes(x)&&I?.user?.id&&!Ie({changedOnly:!0,nextUserId:I.user.id})){ve(),Q({status:"error",user:null,errorCode:"browser_storage_unavailable"});return}if(I?.user?.id&&y?.identityChanged(I.user.id),cr){Pt&&I?.user?.id&&I.user.id!==Pt&&(B+=1,It?.abort(),ve(),Xe=!0,Q({status:"loading",user:null,errorCode:null}));return}Ge||Je||["INITIAL_SESSION","SIGNED_IN","TOKEN_REFRESHED","USER_UPDATED"].includes(x)&&(ve(),ur())}).data.subscription,A||ur()}return Object.freeze({startLogin:In,completeLogin:Nn,signOut:Un,submitConsent:Ln,retrySession:Qe,initialize:$n,message:bn,getState:()=>({...b}),getReturnTo:ts,subscribe(A){return R.add(A),A({...b}),()=>R.delete(A)},getShopbyAccessToken(){return b.status!=="authenticated"||!we||we.expiresAt<=i()?null:we.accessToken},dispose(){B+=1,ve(),X&&u(X),es?.unsubscribe(),R.clear()}})}function kn(t){let e=document.querySelector("[data-hg-signup]");if(!e)return!1;let r=e.querySelector("form"),s=e.querySelector("[data-signup-status]"),n=e.querySelector("[data-signup-error]"),i=e.querySelector('[name="privacy"]'),o=e.querySelector('[name="service"]'),a=e.querySelector('[name="all"]'),l=e.querySelector('[name="invite"]'),c=e.querySelector("[data-signup-referral]"),u=e.querySelector('[type="submit"]'),h=e.querySelector("[data-signup-retry]"),f=e.querySelector("[data-signup-cancel]"),d=e.querySelector("[data-signup-success]"),p=e.querySelector("[data-signup-login]"),g=e.querySelector("h1"),_=e.querySelector("[data-signup-continue]"),w=null,y=!1,m=!1;e.querySelector("[data-privacy-link]").href=be.privacyUrl,e.querySelector("[data-service-link]").href=be.serviceUrl,_.href=t.getReturnTo();function E(){a.checked=i.checked&&o.checked,a.indeterminate=i.checked!==o.checked,u.disabled=y||!a.checked}function R(b){n.textContent=t.message(b?.code),n.hidden=!1,n.focus()}a.addEventListener("change",()=>{i.checked=o.checked=a.checked,E()});for(let b of[i,o])b.addEventListener("change",E);return l.addEventListener("input",()=>{m=!0,l.value=l.value.toUpperCase(),n.hidden=!0}),r.addEventListener("submit",async b=>{if(b.preventDefault(),!(y||!i.checked||!o.checked)){y=!0,n.hidden=!0,E(),f.disabled=!0,s.textContent="\uAC00\uC785 \uC815\uBCF4\uB97C \uC800\uC7A5\uD558\uACE0 \uC788\uC5B4\uC694.";try{await t.submitConsent({privacy:i.checked,service:o.checked,code:c.hidden?"":l.value})}catch(O){s.textContent="",R(O)}finally{y=!1,f.disabled=!1,E()}}}),h.addEventListener("click",async()=>{h.disabled=!0,await t.retrySession(),h.disabled=!1}),f.addEventListener("click",async()=>{if(!y){y=!0,f.disabled=!0,E();try{await t.signOut()}catch(b){R(b),y=!1,f.disabled=!1,E()}}}),t.subscribe(b=>{n.hidden=!0,p.hidden=!0,d.hidden=!0,h.hidden=!0,w&&b.user?.id&&w!==b.user.id&&(m=!1,l.value="",i.checked=o.checked=a.checked=!1),b.user?.id&&(w=b.user.id),b.status==="consent_required"?(r.hidden=!1,g.textContent=b.consent.can_set_referral?"\uCD08\uB85D \uC77C\uC0C1\uC744 \uC2DC\uC791\uD574\uC694.":"\uC57D\uAD00\uC744 \uD655\uC778\uD574 \uC8FC\uC138\uC694.",s.textContent=b.consent.referral_notice?`${t.message(b.consent.referral_notice)} \uACC4\uC18D \uC774\uC6A9\uD558\uB824\uBA74 \uD544\uC218 \uC57D\uAD00\uC5D0 \uB3D9\uC758\uD574 \uC8FC\uC138\uC694.`:"\uACC4\uC18D \uC774\uC6A9\uD558\uB824\uBA74 \uD544\uC218 \uC57D\uAD00\uC5D0 \uB3D9\uC758\uD574 \uC8FC\uC138\uC694.",c.hidden=!b.consent.can_set_referral,m||(l.value=b.consent.code||""),c.hidden&&(l.value=""),E()):b.status==="authenticated"?(r.hidden=!0,g.textContent="\uC900\uBE44\uAC00 \uC644\uB8CC\uB410\uC5B4\uC694.",s.textContent="",d.textContent=b.signup?.referral_notice?t.message(b.signup.referral_notice):b.signup?.referral_status==="accepted"?"\uCD08\uB300 \uCF54\uB4DC\uB85C \uAC00\uC785\uC774 \uC644\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uCD08\uB300 \uD61C\uD0DD\uC774 \uC5F0\uACB0\uB410\uC5B4\uC694.":"\uC57D\uAD00 \uD655\uC778\uC774 \uC644\uB8CC\uB410\uC5B4\uC694. \uD5EC\uB85C\uC6B0\uADF8\uB9B0\uC528\uC640 \uD568\uAED8\uD574\uC694.",d.hidden=!1,_.hidden=!1):(r.hidden=!0,_.hidden=!0,s.textContent=b.status==="loading"?"\uAC00\uC785 \uC815\uBCF4\uB97C \uD655\uC778\uD558\uACE0 \uC788\uC5B4\uC694.":"",b.status==="error"&&(R({code:b.errorCode}),h.hidden=!1),b.status==="signed_out"&&(w=null,m=!1,l.value="",i.checked=o.checked=a.checked=!1,p.hidden=!1,g.textContent="\uB85C\uADF8\uC778\uD558\uACE0 \uACC4\uC18D\uD574 \uC8FC\uC138\uC694."))}),!0}function En(t){function e(){if(kn(t))return;if(document.querySelector("[data-hg-auth-callback]")){let g=document.getElementById("hg-auth-error"),_=document.getElementById("hg-auth-status"),w=document.getElementById("hg-auth-retry"),y=!1;document.querySelectorAll("[data-hg-return]").forEach(E=>{E.href=t.getReturnTo()});async function m(){y=!1,g.hidden=!0,w.hidden=!0,_.textContent="\uB85C\uADF8\uC778\uACFC \uC1FC\uD551 \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uACE0 \uC788\uC5B4\uC694.";try{await t.completeLogin()}catch(E){y=E?.code==="oauth_denied"||E?.code==="callback_expired",w.textContent=y?"\uB85C\uADF8\uC778 \uB2E4\uC2DC \uC2DC\uB3C4":"\uC1FC\uD551 \uC5F0\uACB0 \uB2E4\uC2DC \uC2DC\uB3C4",_.textContent="",g.textContent=t.message(E?.code),g.hidden=!1,w.hidden=!1,g.focus()}}w.addEventListener("click",()=>{if(y){location.assign(`/pages/sign-in/sign-in.html?from=${encodeURIComponent(t.getReturnTo())}`);return}m()}),m();return}let s=document.getElementById("hg-native-login");if(!s)return;let i=new URLSearchParams(location.search).getAll("from"),o=t.safeReturnTo(i.length===1?i[0]:"/");s.querySelectorAll("[data-hg-return]").forEach(g=>{g.href=o});let a=s.querySelector("[data-hg-providers]"),l=[...a.querySelectorAll("button")],c=s.querySelector("[data-hg-status]"),u=s.querySelector("[data-hg-error]"),h=s.querySelector("[data-hg-connected]"),f=s.querySelector("[data-hg-retry]"),d=!1;function p(g){u.textContent=t.message(g?.code),u.hidden=!1,u.focus()}l.forEach(g=>g.addEventListener("click",async()=>{if(!d){d=!0,u.hidden=!0,a.setAttribute("aria-busy","true"),l.forEach(_=>{_.disabled=!0}),c.textContent="\uC120\uD0DD\uD55C \uB85C\uADF8\uC778 \uC11C\uBE44\uC2A4\uB85C \uC774\uB3D9\uD558\uACE0 \uC788\uC5B4\uC694.";try{await t.startLogin({provider:g.dataset.hgProvider,returnTo:o})}catch(_){d=!1,a.setAttribute("aria-busy","false"),l.forEach(w=>{w.disabled=!1}),c.textContent="",p(_)}}})),t.subscribe(g=>{if(d)return;let _=g.status==="authenticated";h.hidden=!_,a.hidden=_,f.hidden=g.status!=="error",c.textContent=_?g.signup?.referral_notice?t.message(g.signup.referral_notice):"\uD5EC\uB85C\uC6B0\uADF8\uB9B0\uC528 \uC1FC\uD551\uC5D0 \uC5F0\uACB0\uB410\uC5B4\uC694.":g.status==="loading"?"\uB85C\uADF8\uC778 \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uACE0 \uC788\uC5B4\uC694.":"",g.status==="error"?(u.textContent=t.message(g.errorCode),u.hidden=!1):u.hidden=!0}),f.addEventListener("click",async()=>{f.disabled=!0,await t.retrySession(),f.disabled=!1,f.hidden&&c.focus()}),window.addEventListener("pageshow",g=>{g.persisted&&(d=!1,a.setAttribute("aria-busy","false"),l.forEach(_=>{_.disabled=!1}),f.disabled=!1,u.hidden=!0,c.textContent="\uB85C\uADF8\uC778 \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uACE0 \uC788\uC5B4\uC694.",t.retrySession().catch(p))})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}var Yu=Object.freeze({community:"free",notice:"hgcnotice"}),Jr="/pages/board/post-list.html";var Tn={page:/^(?:[1-9]\d{0,2}|1000)$/,boardId:/^(free|hgcnotice)$/,tab:/^(all|notice|[1-9]\d{0,9})$/,view:/^(stories|photos)$/,postNo:/^[1-9]\d{0,14}$/,postBoard:/^(free|hgcnotice)$/,compose:/^1$/};function An(t){if(!Tn.boardId.test(t.get("boardId")||""))return!1;for(let[e,r]of t)if(!Tn[e]?.test(r)||t.getAll(e).length!==1)return!1;return!(t.has("postNo")!==t.has("postBoard")||t.has("compose")&&t.has("postNo")||t.has("page")&&(t.has("postNo")||t.has("compose")))}var Gr="/pages/sign-in/auth-callback.html",Rn=new Map([["/",new Set],[Jr,new Set(["boardId","tab","view","postNo","postBoard","compose","page"])],["/pages/my/my-page.html",new Set],["/pages/my/order-list.html",new Set],["/pages/my/like-product-list.html",new Set],["/pages/order/cart.html",new Set],["/pages/order/order-sheet-form.html",new Set(["ordersheetNo"])],["/pages/product/product-detail.html",new Set(["productNo"])],["/pages/product/product-list.html",new Set(["categoryNo","keyword"])]]);function Yr(t,e){let r=new URL("/",e),s=r.href;if(typeof t!="string"||!t||t.length>2e3||/[\\\s\u0000-\u001f]/.test(t)||t.startsWith("//"))return s;try{let n=new URL(t,r);if(n.origin!==r.origin||n.username||n.password||!Rn.has(n.pathname))return s;let i=t.replace(/^https?:\/\/[^/]+/i,"").split(/[?#]/)[0];if(/%|\.\./.test(i)||n.pathname===Jr&&!An(n.searchParams))return s;let o=Rn.get(n.pathname);for(let[a,l]of n.searchParams)if(!o.has(a)||n.searchParams.getAll(a).length!==1||(a==="keyword"?l.length>100||/[\u0000-\u001f]/.test(l):!/^[A-Za-z0-9_-]{1,100}$/.test(l)))return s;return n.hash&&!(n.pathname==="/"&&n.hash==="#hg-products")?s:n.href}catch{return s}}function On({utils:t,storage:e}){let r="hellogreency-native-auth-owner-v1";function s(){try{return e.getItem(r)}catch{return null}}function n({changedOnly:o=!1,nextUserId:a=null}={}){if(!(!s()||o&&s()===a)){t.removeAuthTokens();try{e.removeItem(r)}catch{}}}function i(o,{userId:a}){if(!t.memberAuth?.set||!t.refreshAuth?.set||!t.removeAuthTokens)throw new Error("native_auth_unavailable");s()&&s()!==a&&t.removeAuthTokens();try{if(e.setItem(r,a),t.refreshAuth.storeKeepLoginStatus(!1),t.memberAuth.set({value:o.accessToken,expires:o.expiresIn}),t.refreshAuth.set({value:o.refreshToken,expires:o.refreshTokenExpiresIn}),t.memberAuth.get()!==o.accessToken||t.refreshAuth.get()!==o.refreshToken)throw new Error("native_auth_unavailable")}catch{n();let c=new Error("Native login storage unavailable");throw c.code="browser_storage_unavailable",c}}return{apply:i,clear:n,owner:s}}var Ot=T,Pe=window.ShopbySkin?.utils;if(!Pe?.memberAuth?.set||!Pe?.refreshAuth?.set||!Pe?.removeAuthTokens)throw new Error("The Shopby 1.14.0 auth utilities are required.");var Xo={getItem(t){let e=localStorage.getItem(t);return e==null?null:zr(e)},setItem(t,e){localStorage.setItem(t,zr(e))},removeItem(t){localStorage.removeItem(t)}},Cn=_n(Ot.supabaseUrl,Ot.supabaseAnonKey,{auth:{flowType:"pkce",detectSessionInUrl:!1,persistSession:!0,autoRefreshToken:!0,storageKey:"hellogreency-native-web-auth-v1",storage:Xo}}),Pn=ss({supabaseUrl:Ot.supabaseUrl,anonKey:Ot.supabaseAnonKey,storage:sessionStorage});try{Pn.capture(location.href)}catch{}var xn=!!Pe.memberAuth.get(),Qr=On({utils:Pe,storage:localStorage}),Qo=Qr.owner(),Rt=Sn({signupGate:Pn,client:Cn,supabaseUrl:Ot.supabaseUrl,siteUrl:location.origin+"/",pendingStorage:sessionStorage,callbackUrl:Gr,pendingKey:"hellogreency-native-login-pending-v1",resolveReturnTo:Yr,serializeReturnTo:t=>t,applyVerifiedSession:Qr.apply,clearVerifiedSession:Qr.clear,navigate:t=>location.assign(t),replaceUrl:t=>history.replaceState(null,"",t),currentUrl:()=>{let t=window.__HG_AUTH_CALLBACK_URL||location.href;return delete window.__HG_AUTH_CALLBACK_URL,t}}),Zr=!1;window.HelloGreencyNativeAuth=Object.freeze({...Rt,getCommunityBlockedMembers:rs(Cn,Rt),safeReturnTo:t=>Yr(t,location.origin),async signOut(){Zr=!0;try{await Rt.signOut(),Pe.signOut({redirect:"/",replace:!0})}catch(t){throw Zr=!1,t}}});Rt.initialize({callbackPage:location.pathname===Gr});En(window.HelloGreencyNativeAuth);var Xr=!1;Rt.subscribe(t=>{if(Xr||Zr)return;if(t.status==="consent_required"&&location.pathname!==fr){Xr=!0,location.assign(fr);return}if(location.pathname.startsWith("/pages/sign-in/"))return;let e=t.status==="authenticated"&&(!xn||Qo!==t.user?.id),r=xn&&["signed_out","error"].includes(t.status)&&!Pe.memberAuth.get();(e||r)&&(Xr=!0,location.reload())});window.dispatchEvent(new Event("hellogreency-auth-ready"));})();