@mindexec/cli 0.2.370 → 0.2.372
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server.js +448 -5
- package/wwwroot/assets/{AdminDashboardPage-BwQDZQpO.js → AdminDashboardPage-Cz9oqmp1.js} +1 -1
- package/wwwroot/assets/{AppSidebar-CY0kMRhh.js → AppSidebar-CCyfl-_8.js} +2 -2
- package/wwwroot/assets/AuthPages-CkWEDGgC.js +1 -0
- package/wwwroot/assets/{CodePage-Do4K07Ge.js → CodePage-D0CxncU0.js} +1 -1
- package/wwwroot/assets/{CompanyCorePage-iD32axX4.js → CompanyCorePage-C8AAF9MJ.js} +1 -1
- package/wwwroot/assets/{ExecutionModePage-BHn-i9eu.js → ExecutionModePage-DM4G1xkT.js} +1 -1
- package/wwwroot/assets/{MindCanvas-0T8dFIuQ.css → MindCanvas-D7mLWp5-.css} +1 -1
- package/wwwroot/assets/MindCanvas-g37obZMq.js +48 -0
- package/wwwroot/assets/{PlanMasterPage-B9XXbERQ.js → PlanMasterPage-axrFePG0.js} +4 -4
- package/wwwroot/assets/{PricingPage-Ch9eWuME.js → PricingPage-BwayR6ga.js} +1 -1
- package/wwwroot/assets/{ToolPages-DLme_QLb.js → ToolPages-CTVDo24Z.js} +5 -5
- package/wwwroot/assets/{YouTubeSearchPage-BSQIhWnY.js → YouTubeSearchPage-BWA45eoM.js} +2 -2
- package/wwwroot/assets/canvas-runtime-CddXXjp9.js +44 -0
- package/wwwroot/assets/{index-BnDICYGs.js → index-Bc6exjGV.js} +2 -2
- package/wwwroot/assets/{storage-C8yTm9Oa.js → storage-BPqBi6qs.js} +1 -1
- package/wwwroot/assets/{supabaseAuthAdapter-Ct6_adpn.js → supabaseAuthAdapter-bSjZe3In.js} +2 -2
- package/wwwroot/index.html +2 -2
- package/wwwroot/assets/AuthPages-CI6GdrrU.js +0 -1
- package/wwwroot/assets/MindCanvas-Bt2vebbf.js +0 -48
- package/wwwroot/assets/canvas-runtime-CcSvL_l6.js +0 -44
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as z}from"./productionAdapterConfig-C5jfk6oG.js";import{
|
|
1
|
+
import{r as z}from"./productionAdapterConfig-C5jfk6oG.js";import{aP as _r,o as br,x as kr,aQ as Sr}from"./canvas-runtime-CddXXjp9.js";import{R as S}from"./app-runtime-xD2Z3NdN.js";import"./vendor-react-BXzpOyCS.js";import"./vendor-icons-678PAT8P.js";function Je(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);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function Er(t,e,r,s){function n(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):n(u.value).then(o,l)}c((s=s.apply(t,e||[])).next())})}const Tr=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class pt 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}}}class Ar extends pt{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class mt extends pt{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class yt extends pt{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var st;(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"})(st||(st={}));class Rr{constructor(e,{headers:r={},customFetch:s,region:n=st.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=Tr(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Er(this,arguments,void 0,function*(r,s={}){var n;let i,a;try{const{headers:o,method:l,body:c,signal:u,timeout:h}=s;let d={},{region:f}=s;f||(f=this.region);const p=new URL(`${this.url}/${r}`);f&&f!=="any"&&(d["x-region"]=f,p.searchParams.set("forceFunctionRegion",f));let g;c&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",g=c):typeof c=="string"?(d["Content-Type"]="text/plain",g=c):typeof FormData<"u"&&c instanceof FormData?g=c:(d["Content-Type"]="application/json",g=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?g=JSON.stringify(c):g=c;let _=u;h&&(a=new AbortController,i=setTimeout(()=>a.abort(),h),u?(_=a.signal,u.addEventListener("abort",()=>a.abort())):_=a.signal);const v=yield this.fetch(p.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),o),body:g,signal:_}).catch(x=>{throw new Ar(x)}),b=v.headers.get("x-relay-error");if(b&&b==="true")throw new mt(v);if(!v.ok)throw new yt(v);let y=((n=v.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),E;return y==="application/json"?E=yield v.json():y==="application/octet-stream"||y==="application/pdf"?E=yield v.blob():y==="text/event-stream"?E=v:y==="multipart/form-data"?E=yield v.formData():E=yield v.text(),{data:E,error:null,response:v}}catch(o){return{data:null,error:o,response:o instanceof yt||o instanceof mt?o.context:void 0}}finally{i&&clearTimeout(i)}})}}const zt=3,wt=t=>Math.min(1e3*2**t,3e4),Or=[520,503],Yt=["GET","HEAD","OPTIONS"];var vt=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 _t(t,e){return new Promise(r=>{if(e!=null&&e.aborted){r();return}const s=setTimeout(()=>{e==null||e.removeEventListener("abort",n),r()},t);function n(){clearTimeout(s),r()}e==null||e.addEventListener("abort",n)})}function Cr(t,e,r,s){return!(!s||r>=zt||!Yt.includes(t)||!Or.includes(e))}var Pr=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){const a=this.headers.get("Accept");a==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!a||a==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const s=this.fetch;let i=(async()=>{let a=0;for(;;){const c={};r.headers.forEach((h,d)=>{c[d]=h}),a>0&&(c["X-Retry-Count"]=String(a));let u;try{u=await s(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body,(h,d)=>typeof d=="bigint"?d.toString():d),signal:r.signal})}catch(h){if((h==null?void 0:h.name)==="AbortError"||(h==null?void 0:h.code)==="ABORT_ERR"||!Yt.includes(r.method))throw h;if(r.retryEnabled&&a<zt){const d=wt(a);a++,await _t(d,r.signal);continue}throw h}if(Cr(r.method,u.status,a,r.retryEnabled)){var o,l;const h=(o=(l=u.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&o!==void 0?o:null,d=h!==null?Math.max(0,parseInt(h,10)||0)*1e3:wt(a);await u.text(),a++,await _t(d,r.signal);continue}return await r.processResponse(u)}})();return this.shouldThrowOnError||(i=i.catch(a=>{var o;let l="",c="",u="";const h=a==null?void 0:a.cause;if(h){var d,f,p,g;const b=(d=h==null?void 0:h.message)!==null&&d!==void 0?d:"",y=(f=h==null?void 0:h.code)!==null&&f!==void 0?f:"";l=`${(p=a==null?void 0:a.name)!==null&&p!==void 0?p:"FetchError"}: ${a==null?void 0:a.message}`,l+=`
|
|
2
2
|
|
|
3
3
|
Caused by: ${(g=h==null?void 0:h.name)!==null&&g!==void 0?g:"Error"}: ${b}`,y&&(l+=` (${y})`),h!=null&&h.stack&&(l+=`
|
|
4
4
|
${h.stack}`)}else{var _;l=(_=a==null?void 0:a.stack)!==null&&_!==void 0?_:""}const v=this.url.toString().length;return(a==null?void 0:a.name)==="AbortError"||(a==null?void 0:a.code)==="ABORT_ERR"?(u="",c="Request was aborted (timeout or manual cancellation)",v>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${v} 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==null?void 0:h.name)==="HeadersOverflowError"||(h==null?void 0:h.code)==="UND_ERR_HEADERS_OVERFLOW")&&(u="",c="HTTP headers exceeded server limits (typically 16KB)",v>this.urlLengthLimit&&(c+=`. Your request URL is ${v} 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:`${(o=a==null?void 0:a.name)!==null&&o!==void 0?o:"FetchError"}: ${a==null?void 0:a.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,a=t.statusText;if(t.ok){var o,l;if(e.method!=="HEAD"){var c;const d=await t.text();if(d!=="")if(e.headers.get("Accept")==="text/csv")s=d;else if(e.headers.get("Accept")&&(!((c=e.headers.get("Accept"))===null||c===void 0)&&c.includes("application/vnd.pgrst.plan+text")))s=d;else try{s=JSON.parse(d)}catch{if(r={message:d},s=null,e.shouldThrowOnError)throw new vt({message:d,details:"",hint:"",code:""})}}const u=(o=e.headers.get("Prefer"))===null||o===void 0?void 0:o.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,a="Not Acceptable"):s.length===1?s=s[0]:s=null)}else{const u=await t.text();try{r=JSON.parse(u),Array.isArray(r)&&t.status===404&&(s=[],r=null,i=200,a="OK")}catch{t.status===404&&u===""?(i=204,a="No Content"):r={message:u}}if(r&&e.shouldThrowOnError)throw new vt(r)}return{success:r===null,error:r,data:s,count:n,status:i,statusText:a}}returns(){return this}overrideTypes(){return this}},jr=class extends Pr{throwOnError(){return super.throwOnError()}select(t){let e=!1;const 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}={}){const i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const 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 a;const o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const bt=new RegExp("[,()]");var le=class extends jr{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){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&bt.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&bt.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");const 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}={}){const 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}},Ir=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){const{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET";let i=!1;const a=(t??"*").split("").map(c=>/\s/.test(c)&&!i?"":(c==='"'&&(i=!i),c)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),s&&l.append("Prefer",`count=${s}`),new le({method:n,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const n="POST",{url:i,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),r||a.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(o.length>0){const l=[...new Set(o)].map(c=>`"${c}"`);i.searchParams.set("columns",l.join(","))}}return new le({method:n,url:i,headers:a,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;const a="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&l.append("Prefer",`count=${s}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){const c=t.reduce((u,h)=>u.concat(Object.keys(h)),[]);if(c.length>0){const u=[...new Set(c)].map(h=>`"${h}"`);o.searchParams.set("columns",u.join(","))}}return new le({method:a,url:o,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;const 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;const 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 be(t){"@babel/helpers - typeof";return be=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},be(t)}function $r(t,e){if(be(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(be(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function xr(t){var e=$r(t,"string");return be(e)=="symbol"?e:e+""}function Ur(t,e,r){return(e=xr(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function kt(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 Pe(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?kt(Object(r),!0).forEach(function(s){Ur(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):kt(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Nr=class Xt{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:a=8e3,retry:o}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=a;const l=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,u)=>{const h=new AbortController,d=setTimeout(()=>h.abort(),i),f=u==null?void 0:u.signal;if(f){if(f.aborted)return clearTimeout(d),l(c,u);const p=()=>{clearTimeout(d),h.abort()};return f.addEventListener("abort",p,{once:!0}),l(c,Pe(Pe({},u),{},{signal:h.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",p)})}return l(c,Pe(Pe({},u),{},{signal:h.signal})).finally(()=>clearTimeout(d))}:this.fetch=l,this.retry=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Ir(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 Xt(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 a;let o;const l=new URL(`${this.url}/rpc/${e}`);let c;const u=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(u)),h=s&&Object.values(r).some(u);h?(o="POST",c=r):s||n?(o=s?"HEAD":"GET",Object.entries(r).filter(([f,p])=>p!==void 0).map(([f,p])=>[f,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([f,p])=>{l.searchParams.append(f,p)})):(o="POST",c=r);const d=new Headers(this.headers);return h?d.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&d.set("Prefer",`count=${i}`),new le({method:o,url:l,headers:d,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class Lr{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};const 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."};const n=globalThis.process;if(n){const i=n.versions;if(i&&i.node){const a=i.node,o=parseInt(a.replace(/^v/,"").split(".")[0]);return o>=22?typeof globalThis.WebSocket<"u"?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${o} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${o} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
@@ -41,4 +41,4 @@ Request ID: ${l}`),c){let b=`
|
|
|
41
41
|
Resources:`;for(const y of c){if(!y||typeof y!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${y}`);b+=`
|
|
42
42
|
- ${y}`}v+=b}return`${_}
|
|
43
43
|
${v}`}class C 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}}}class Fe extends C{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function Hn({error:t,options:e}){var r,s,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new C({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 C({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 C({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 C({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 C({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new C({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new C({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new C({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const a=window.location.hostname;if(fr(a)){if(i.rp.id!==a)return new C({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new C({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 C({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 C({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 C({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Mn({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new C({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new C({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(fr(s)){if(r.rpId!==s)return new C({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new C({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new C({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 C({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class Fn{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const ft=new Fn;function Ft(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);const{challenge:e,user:r,excludeCredentials:s}=t,n=Je(t,["challenge","user","excludeCredentials"]),i=de(e).buffer,a=Object.assign(Object.assign({},r),{id:de(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){const c=s[l];o.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:de(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return o}function Kt(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,s=Je(t,["challenge","allowCredentials"]),n=de(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let a=0;a<r.length;a++){const o=r[a];i.allowCredentials[a]=Object.assign(Object.assign({},o),{id:de(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return i}function Wt(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:te(new Uint8Array(t.response.attestationObject)),clientDataJSON:te(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Vt(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:te(new Uint8Array(n.authenticatorData)),clientDataJSON:te(new Uint8Array(n.clientDataJSON)),signature:te(new Uint8Array(n.signature)),userHandle:n.userHandle?te(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function fr(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Ke(){var t,e;return!!(I()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function pr(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Fe("Browser returned unexpected credential type",e)}:{data:null,error:new Fe("Empty credential response",e)}}catch(e){return{data:null,error:Hn({error:e,options:t})}}}async function gr(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Fe("Browser returned unexpected credential type",e)}:{data:null,error:new Fe("Empty credential response",e)}}catch(e){return{data:null,error:Mn({error:e,options:t})}}}const Kn={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Wn={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function We(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const i in n){const a=n[i];if(a!==void 0)if(Array.isArray(a))s[i]=a;else if(r(a))s[i]=a;else if(e(a)){const o=s[i];e(o)?s[i]=We(o,a):s[i]=We(a)}else s[i]=a}return s}function Vn(t,e){return We(Kn,t,e||{})}function Jn(t,e){return We(Wn,t,e||{})}class Gn{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 a;try{const{data:o,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!o)return{data:null,error:l};const c=n??ft.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:u}=o.webauthn.credential_options.publicKey;if(!u.name){const h=s;if(h)u.name=`${u.id}:${h}`;else{const f=(await this.client.getUser()).data.user,p=((a=f==null?void 0:f.user_metadata)===null||a===void 0?void 0:a.name)||(f==null?void 0:f.email)||(f==null?void 0:f.id)||"User";u.name=`${u.id}:${p}`}}u.displayName||(u.displayName=u.name)}switch(o.webauthn.type){case"create":{const u=Vn(o.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:h,error:d}=await pr({publicKey:u,signal:c});return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:d}}case"request":{const u=Jn(o.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:h,error:d}=await gr(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:u,signal:c}));return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:d}}}}catch(o){return m(o)?{data:null,error:o}:{data:null,error:new q("Unexpected error in challenge",o)}}}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 Te("rpId is required for WebAuthn authentication")};try{if(!Ke())return{data:null,error:new q("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!a)return{data:null,error:o};const{webauthn:l}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:s,credential_response:l.credential_response}})}catch(a){return m(a)?{data:null,error:a}:{data:null,error:new q("Unexpected error in authenticate",a)}}}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 Te("rpId is required for WebAuthn registration")};try{if(!Ke())return{data:null,error:new q("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(u=>{var h;return(h=u.data)===null||h===void 0?void 0:h.all.find(d=>d.factor_type==="webauthn"&&d.friendly_name===e&&d.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u==null?void 0:u.id}):void 0),{data:null,error:o};const{data:l,error:c}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return l?this._verify({factorId:a.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(a){return m(a)?{data:null,error:a}:{data:null,error:new q("Unexpected error in register",a)}}}}Ln();const zn={url:Xs,storageKey:Qs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Zs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},ae={};class Ae{get jwks(){var e,r;return(r=(e=ae[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){ae[this.storageKey]=Object.assign(Object.assign({},ae[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=ae[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ae[this.storageKey]=Object.assign(Object.assign({},ae[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;const i=Object.assign(Object.assign({},zn),e);if(this.storageKey=i.storageKey,this.instanceID=(r=Ae.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,Ae.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&I()){const a=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(s=i.experimental)!==null&&s!==void 0?s:{},this.admin=new Un({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=hr(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 Gn(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:ur()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Mt(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Mt(this.memoryStorage)),I()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),(a.data.event==="TOKEN_REFRESHED"||a.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}i.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${or}) ${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(I()&&(r=gn(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),I()&&this.detectSessionInUrl&&s!=="none"){const{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),nn(i)){const 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}}const{session:a,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return m(r)?this._returnResult({error:r}):this._returnResult({error:new q("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}},xform:N}),{data:a,error:o}=i;if(o||!a)return this._returnResult({data:{user:null,session:null},error:o});const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(m(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){const{email:u,password:h,options:d}=e;let f=null,p=null;this.flowType==="pkce"&&([f,p]=await Z(this.storage,this.storageKey)),i=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d==null?void 0:d.emailRedirectTo,body:{email:u,password:h,data:(r=d==null?void 0:d.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:f,code_challenge_method:p},xform:N})}else if("phone"in e){const{phone:u,password:h,options:d}=e;i=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(s=d==null?void 0:d.data)!==null&&s!==void 0?s:{},channel:(n=d==null?void 0:d.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:N})}else throw new Ue("You must provide either an email or phone number and a password");const{data:a,error:o}=i;if(o||!a)return await O(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:a,options:o}=e;r=await w(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:qt})}else if("phone"in e){const{phone:i,password:a,options:o}=e;r=await w(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:qt})}else throw new Ue("You must provide either an email or phone number and a password");const{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const i=new ie;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(m(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){const{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,a,o,l,c,u,h,d;let f,p;if("message"in e)f=e.message,p=e.signature;else{const{chain:g,wallet:_,statement:v,options:b}=e;let y;if(I())if(typeof _=="object")y=_;else{const K=window;if("ethereum"in K&&typeof K.ethereum=="object"&&"request"in K.ethereum&&typeof K.ethereum.request=="function")y=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"||!(b!=null&&b.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=_}const E=new URL((r=b==null?void 0:b.url)!==null&&r!==void 0?r:window.location.href),x=await y.request({method:"eth_requestAccounts"}).then(K=>K).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!x||x.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const A=dr(x[0]);let j=(s=b==null?void 0:b.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!j){const K=await y.request({method:"eth_chainId"});j=Dn(K)}const vr={domain:E.host,address:A,statement:v,uri:E.href,version:"1",chainId:j,nonce:(n=b==null?void 0:b.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=b==null?void 0:b.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=b==null?void 0:b.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=b==null?void 0:b.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=b==null?void 0:b.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=b==null?void 0:b.signInWithEthereum)===null||u===void 0?void 0:u.resources};f=qn(vr),p=await y.request({method:"personal_sign",params:[Bn(f),A]})}try{const{data:g,error:_}=await w(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:p},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(d=e.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:N});if(_)throw _;if(!g||!g.session||!g.user){const v=new ie;return this._returnResult({data:{user:null,session:null},error:v})}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(m(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,s,n,i,a,o,l,c,u,h,d,f;let p,g;if("message"in e)p=e.message,g=e.signature;else{const{chain:_,wallet:v,statement:b,options:y}=e;let E;if(I())if(typeof v=="object")E=v;else{const A=window;if("solana"in A&&typeof A.solana=="object"&&("signIn"in A.solana&&typeof A.solana.signIn=="function"||"signMessage"in A.solana&&typeof A.solana.signMessage=="function"))E=A.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 v!="object"||!(y!=null&&y.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=v}const x=new URL((r=y==null?void 0:y.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in E&&E.signIn){const A=await E.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},y==null?void 0:y.signInWithSolana),{version:"1",domain:x.host,uri:x.href}),b?{statement:b}:null));let j;if(Array.isArray(A)&&A[0]&&typeof A[0]=="object")j=A[0];else if(A&&typeof A=="object"&&"signedMessage"in A&&"signature"in A)j=A;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in j&&"signature"in j&&(typeof j.signedMessage=="string"||j.signedMessage instanceof Uint8Array)&&j.signature instanceof Uint8Array)p=typeof j.signedMessage=="string"?j.signedMessage:new TextDecoder().decode(j.signedMessage),g=j.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=[`${x.host} wants you to sign in with your Solana account:`,E.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${x.href}`,`Issued At: ${(n=(s=y==null?void 0:y.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=y==null?void 0:y.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...!((a=y==null?void 0:y.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...!((o=y==null?void 0:y.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...!((l=y==null?void 0:y.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...!((c=y==null?void 0:y.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...!((h=(u=y==null?void 0:y.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",...y.signInWithSolana.resources.map(j=>`- ${j}`)]:[]].join(`
|
|
44
|
-
`);const A=await E.signMessage(new TextEncoder().encode(p),"utf8");if(!A||!(A instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=A}}try{const{data:_,error:v}=await w(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:te(g)},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:N});if(v)throw v;if(!_||!_.session||!_.user){const b=new ie;return this._returnResult({data:{user:null,session:null},error:b})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:v})}catch(_){if(m(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){const r=await L(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new an;const{data:i,error:a}=await w(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:N});if(await O(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const o=new ie;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}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:a})}catch(i){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,o=await w(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:N}),{data:l,error:c}=o;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){const u=new ie;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(m(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;try{if("email"in e){const{email:o,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await Z(this.storage,this.storageKey));const{error:h}=await w(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=l==null?void 0:l.data)!==null&&r!==void 0?r:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:o,options:l}=e,{data:c,error:u}=await w(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=l==null?void 0:l.data)!==null&&n!==void 0?n:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(a=l==null?void 0:l.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u})}throw new Ue("You must provide either an email or phone number.")}catch(o){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}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);const{data:a,error:o}=await w(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:N});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,c=a.user;return l!=null&&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(m(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,a;try{let o=null,l=null;this.flowType==="pkce"&&([o,l]=await Z(this.storage,this.storageKey));const c=await w(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==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:In});return!((i=c.data)===null||i===void 0)&&i.url&&I()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(o){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(o))return this._returnResult({data:null,error:o});throw o}}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=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new P;const{error:n}=await w(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(m(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:i}=e;let a=null,o=null;this.flowType==="pkce"&&([a,o]=await Z(this.storage,this.storageKey));const{error:l}=await w(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken},code_challenge:a,code_challenge_method:o},redirectTo:i==null?void 0:i.emailRedirectTo});return l&&await O(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:a,error:o}=await w(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o})}throw new Ue("You must provide either an email or phone number and a type")}catch(r){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(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){const 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;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const 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{const 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;const r=await L(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};const s=e.expires_at?e.expires_at*1e3-Date.now()<Xe:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await L(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=Qe()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=On(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i){if(!!(e.expires_at&&e.expires_at*1e3>Date.now())){const o=await L(this.storage,this.storageKey);if(o&&o.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 w(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:X}):await this._useSession(async r=>{var s,n,i;const{data:a,error:o}=r;if(o)throw o;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new P}:await w(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:X})})}catch(r){if(m(r))return xe(r)&&(await this._removeSession(),await O(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=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new P;const a=n.session;let o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await Z(this.storage,this.storageKey));const{data:c,error:u}=await w(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:l}),jwt:a.access_token,xform:X});if(u)throw u;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(s){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(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 P;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Le(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-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(m(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){const{data:a,error:o}=r;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new P;const{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(m(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!I())throw new Ne("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ne(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 jt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ne("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 jt("No code detected.");const{data:y,error:E}=await this._exchangeCodeForSession(e.code);if(E)throw E;const x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:y.session,redirectType:(s=y.redirectType)!==null&&s!==void 0?s:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:a,refresh_token:o,expires_in:l,expires_at:c,token_type:u}=e;if(!a||!l||!o||!u)throw new Ne("No session defined in URL");const h=Math.round(Date.now()/1e3),d=parseInt(l);let f=h+d;c&&(f=parseInt(c));const p=f-h;p*1e3<=G&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`);const g=f-d;h-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,f,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,f,h);const{data:_,error:v}=await this._getUser(a);if(v)throw v;const b={provider_token:n,provider_refresh_token:i,access_token:a,expires_in:d,expires_at:f,refresh_token:o,token_type:u,user:_.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(n){if(m(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){const r=await L(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;const{data:n,error:i}=r;if(i&&!xe(i))return this._returnResult({error:i});const a=(s=n.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);if(o&&!(sn(o)&&(o.status===404||o.status===401||o.status===403)||xe(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await O(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=pn(),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{const{data:{session:i},error:a}=r;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),xe(i)?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Z(this.storage,this.storageKey,!0));try{return await w(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 O(this.storage,`${this.storageKey}-code-verifier`),m(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{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(m(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{const{data:s,error:n}=await this._useSession(async i=>{var a,o,l,c,u;const{data:h,error:d}=i;if(d)throw d;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await w(this.fetch,"GET",f,{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 I()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(m(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{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:o,token:l,access_token:c,nonce:u}=e,h=await w(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i==null?void 0:i.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:N}),{data:d,error:f}=h;return f?this._returnResult({data:{user:null,session:null},error:f}):!d||!d.session||!d.user?this._returnResult({data:{user:null,session:null},error:new ie}):(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:f}))}catch(n){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(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;const{data:i,error:a}=r;if(a)throw a;return await w(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(m(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r="#_refreshAccessToken()";this._debug(r,"begin");try{const s=Date.now();return await wn(async n=>(n>0&&await yn(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await w(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:N})),(n,i)=>{const a=200*Math.pow(2,n);return i&&It(i)&&Date.now()+a-s<G})}catch(s){if(this._debug(r,"error",s),m(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),I()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await L(this.storage,this.storageKey);if(n&&this.userStorage){let a=await L(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await ue(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:Qe()}else if(n&&!n.user&&!n.user){const a=await L(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(n.user=a.user,await O(this.storage,this.storageKey+"-user"),await ue(this.storage,this.storageKey,n)):n.user=Qe()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Xe;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Xe}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(on(a)?this._debug(s,"refresh discarded by commit guard",a):this._debug(s,"refresh failed",a))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(n.access_token);!o&&(a!=null&&a.user)?(n.user=a.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new P;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;const n="#_callRefreshToken()";this._debug(n,"begin");try{this.refreshingDeferred=new Ye;const i=await L(this.storage,this.storageKey),{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new P;const l=await L(this.storage,this.storageKey);if(i!==null&&(l===null||l.refresh_token!==i.refresh_token)){this._debug(n,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:l?"replaced":"cleared"});const d={data:null,error:new $t};return this.refreshingDeferred.resolve(d),d}const u=this._sessionRemovalEpoch;if(await this._saveSession(a.session),this._sessionRemovalEpoch!==u){this._debug(n,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await O(this.storage,this.storageKey),this.userStorage&&await O(this.userStorage,this.storageKey+"-user");const d={data:null,error:new $t};return this.refreshingDeferred.resolve(d),d}await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const h={data:a.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(h),h}catch(i){if(this._debug(n,"error",i),m(i)){const a={data:null,error:i};if(!It(i)){const o=await L(this.storage,this.storageKey);!!(o!=null&&o.expires_at&&o.expires_at*1e3>Date.now())?this._debug(n,"proactive refresh failed, access token still valid — preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:a,expiresAt:Date.now()+Ys},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await O(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await ue(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=Dt(n);await ue(this.storage,this.storageKey,i)}else{const n=Dt(r);await ue(this.storage,this.storageKey,n)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await O(this.storage,this.storageKey),await O(this.storage,this.storageKey+"-code-verifier"),await O(this.storage,this.storageKey+"-user"),this.userStorage&&await O(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&I()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),G);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const 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()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const 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{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/G);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${G}ms, refresh threshold is ${me} ticks`),n<=me&&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 Nn)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{const e=Date.now();try{await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/G);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${G}ms, refresh threshold is ${me} ticks`),n<=me&&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()"),!I()||!(window!=null&&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==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const 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){const n=[`provider=${encodeURIComponent(r)}`];if(s!=null&&s.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,a]=await Z(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});n.push(o.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await w(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(m(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await w(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=i==null?void 0: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==null?void 0: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(m(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){const r=async()=>{try{return await this._useSession(async s=>{var n;const{data:i,error:a}=s;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Wt(e.webauthn.credential_response):Vt(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i==null?void 0: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(m(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){const r=async()=>{try{return await this._useSession(async s=>{var n;const{data:i,error:a}=s;if(a)return this._returnResult({data:null,error:a});const o=await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;const{data:l}=o;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:Ft(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:Kt(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(m(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){const{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;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r==null?void 0: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{const{payload:f}=Le(e);let p=null;f.aal&&(p=f.aal);let g=p;const{data:{user:_},error:v}=await this.getUser(e);if(v)return this._returnResult({data:null,error:v});((s=(r=_==null?void 0:_.factors)===null||r===void 0?void 0:r.filter(E=>E.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(g="aal2");const y=f.amr||[];return{data:{currentLevel:p,nextLevel:g,currentAuthenticationMethods:y},error:null}}catch(f){if(m(f))return this._returnResult({data:null,error:f});throw f}const{data:{session:a},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=Le(a.access_token);let c=null;l.aal&&(c=l.aal);let u=c;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");const d=l.amr||[];return{data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:d},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await w(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 P})})}catch(r){if(m(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new P});const a=await w(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&I()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(m(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new P});const a=await w(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&I()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(m(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await w(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 P})})}catch(e){if(m(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await w(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 P})})}catch(r){if(m(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(o=>o.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+tn>n)return s;const{data:i,error:a}=await w(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:f,error:p}=await this.getSession();if(p||!f.session)return this._returnResult({data:null,error:p});s=f.session.access_token}const{header:n,payload:i,signature:a,raw:{header:o,payload:l}}=Le(s);if(!(r!=null&&r.allowExpired))try{Tn(i.exp)}catch(f){throw new He(f instanceof Error?f.message:"JWT validation failed")}const c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!c){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:n,signature:a},error:null}}const u=An(n.alg),h=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,a,dn(`${o}.${l}`)))throw new He("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(m(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n;D(this.experimental);try{if(!Ke())return this._returnResult({data:null,error:new q("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}});if(a||!i)return this._returnResult({data:null,error:a});const o=Kt(i.options),l=(n=(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:ft.createNewAbortSignal(),{data:c,error:u}=await gr({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new q("WebAuthn ceremony failed",null)});const h=Vt(c);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:h})}catch(i){if(m(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var r,s;D(this.experimental);try{if(!Ke())return this._returnResult({data:null,error:new q("Browser does not support WebAuthn",null)});const{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});const a=Ft(n.options),o=(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:ft.createNewAbortSignal(),{data:l,error:c}=await pr({publicKey:a,signal:o});if(c||!l)return this._returnResult({data:null,error:c??new q("WebAuthn ceremony failed",null)});const u=Wt(l);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:u})}catch(n){if(m(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){D(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new P});const{data:n,error:i}=await w(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(m(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){D(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});const{data:i,error:a}=await w(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(m(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;D(this.experimental);try{const{data:s,error:n}=await w(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e==null?void 0: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(m(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){D(this.experimental);try{const{data:r,error:s}=await w(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:N});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(m(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){D(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new P});const{data:n,error:i}=await w(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:a=>({data:a,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(m(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){D(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});const{data:i,error:a}=await w(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(m(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){D(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});const{error:i}=await w(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(m(r))return this._returnResult({data:null,error:r});throw r}}}Ae.nextInstanceID={};const Yn=Ae,Xn="2.108.2";let ye="",Ve;if(typeof Deno<"u"){var et;ye="deno",Ve=(et=Deno.version)===null||et===void 0?void 0:et.deno}else if(typeof document<"u")ye="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")ye="react-native";else{var tt;ye="node",Ve=typeof process<"u"?(tt=process.version)===null||tt===void 0?void 0:tt.replace(/^v/,""):void 0}const mr=[`runtime=${ye}`];Ve&&mr.push(`runtime-version=${Ve}`);const Qn={"X-Client-Info":`supabase-js/${Xn}; ${mr.join("; ")}`},Zn={headers:Qn},ei={schema:"public"},ti={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ri={},si={enabled:!1,respectSamplingDecision:!0};function ni(t,e,r,s){function n(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):n(u.value).then(o,l)}c((s=s.apply(t,[])).next())})}let rt=null;const ii="@opentelemetry/api";function ai(){return rt===null&&(rt=import(ii).catch(()=>null)),rt}function oi(){return ni(this,void 0,void 0,function*(){try{const t=yield ai();if(!t||!t.propagation||!t.context)return null;const e={};t.propagation.inject(t.context.active(),e);const r=e.traceparent;return r?{traceparent:r,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function li(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;const a=/^[0-9a-f]+$/i;return!a.test(r)||!a.test(s)||!a.test(n)||!a.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function ci(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(const s of e)try{if(typeof s=="string"){if(ui(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 ui(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function hi(t){const e=[];try{const 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 Re(t){"@babel/helpers - typeof";return Re=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},Re(t)}function di(t,e){if(Re(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Re(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function fi(t){var e=di(t,"string");return Re(e)=="symbol"?e:e+""}function pi(t,e,r){return(e=fi(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Jt(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 R(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Jt(Object(r),!0).forEach(function(s){pi(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Jt(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const gi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),mi=()=>Headers,yi=(t,e,r,s,n)=>{const i=gi(s),a=mi(),o=(n==null?void 0:n.enabled)===!0,l=(n==null?void 0:n.respectSamplingDecision)!==!1,c=o?hi(e):null;return async(u,h)=>{var d;const f=(d=await r())!==null&&d!==void 0?d:t;let p=new a(h==null?void 0:h.headers);if(p.has("apikey")||p.set("apikey",t),p.has("Authorization")||p.set("Authorization",`Bearer ${f}`),c){const g=await wi(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,R(R({},h),{},{headers:p}))}};async function wi(t,e,r){if(!ci(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const s=await oi();if(!s||!s.traceparent)return null;if(r){const n=li(s.traceparent);if(n&&!n.isSampled)return null}return s}function Gt(t){return typeof t=="boolean"?{enabled:t}:t}function vi(t){return t.endsWith("/")?t:t+"/"}function _i(t,e){var r,s,n,i,a,o;const{db:l,auth:c,realtime:u,global:h}=t,{db:d,auth:f,realtime:p,global:g}=e,_=Gt(t.tracePropagation),v=Gt(e.tracePropagation),b={db:R(R({},d),l),auth:R(R({},f),c),realtime:R(R({},p),u),storage:{},global:R(R(R({},g),h),{},{headers:R(R({},(r=g==null?void 0:g.headers)!==null&&r!==void 0?r:{}),(s=h==null?void 0:h.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=_==null?void 0:_.enabled)!==null&&i!==void 0?i:v==null?void 0:v.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(a=(o=_==null?void 0:_.respectSamplingDecision)!==null&&o!==void 0?o:v==null?void 0:v.respectSamplingDecision)!==null&&a!==void 0?a:!0},accessToken:async()=>""};return t.accessToken?b.accessToken=t.accessToken:delete b.accessToken,b}function bi(t){const e=t==null?void 0: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(vi(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var ki=class extends Yn{constructor(t){super(t)}},Si=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=bi(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);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:ei,realtime:ri,auth:R(R({},ti),{},{storageKey:a}),global:Zn,tracePropagation:si},l=_i(r??{},o);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=yi(e,t,this._getAccessToken.bind(this),l.global.fetch,l.tracePropagation),this.realtime=this._initRealtimeClient(R({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 Nr(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 zs(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Rr(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();const{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:a,lock:o,debug:l,throwOnError:c,experimental:u,lockAcquireTimeout:h,skipAutoInitialize:d},f,p){const g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ki({url:this.authUrl.href,headers:R(R({},g),f),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:l,throwOnError:c,experimental:u,fetch:p,lockAcquireTimeout:h,skipAutoInitialize:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(_=>_.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new ws(this.realtimeUrl.href,R(R({},t),{},{params:R(R({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0: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)}};const Ei=(t,e,r)=>new Si(t,e,r);function Ti(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Ti()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Ai=["VITE_MINDEXEC_SUPABASE_PUBLISHABLE_KEY","VITE_SUPABASE_PUBLISHABLE_KEY","VITE_MINDEXEC_SUPABASE_ANON_KEY","VITE_SUPABASE_ANON_KEY"];let oe=null;function Ri(t,e){for(const r of e){const s=t[r],n=typeof s=="string"?s.trim():"";if(n)return{key:r,value:n}}return null}function Oi(t){const e=z(t),r=Ri(t,Ai);return!e.auth.canAttempt||!e.supabaseUrl.url||!r?null:{url:e.supabaseUrl.url,publicKey:r.value,keyEnvName:r.key,config:e}}function Oe(t){return{mode:t.auth.mode,canAttempt:t.auth.canAttempt,reason:t.auth.mode}}function Li(t){return Oe(z(t))}function re(t){const e=Oi(t);if(!e)return null;const r=`${e.url}|${e.keyEnvName}|${e.publicKey}`;return(oe==null?void 0:oe.cacheKey)===r||(oe={cacheKey:r,client:Ei(e.url,e.publicKey,{auth:{autoRefreshToken:!0,detectSessionInUrl:!0,flowType:"pkce",persistSession:!0}})}),oe.client}function Ci(t){try{const e=new URL(t),r=e.hostname.toLowerCase();return e.protocol==="http:"&&(r==="127.0.0.1"||r==="::1"||r==="[::1]"||r==="0.0.0.0")&&(e.hostname="localhost"),e.origin}catch{return t}}async function yr(t){if(typeof window>"u")return S.emit("auth.supabase.localBridgeSession.skipped",{source:t,reason:"non-browser"}),null;try{const e=await br(),r=kr(e.status);return e.state!=="connected"||!r?(S.emit("auth.supabase.localBridgeSession.skipped",{source:t,reason:e.state==="connected"?"bridge-auth-missing":"bridge-unavailable",baseUrl:e.baseUrl}),null):{auth:r,baseUrl:e.baseUrl}}catch(e){return S.emit("auth.supabase.localBridgeSession.failed",{source:t,phase:"bridge-status",message:e instanceof Error?e.message:String(e)}),null}}function Pi(t){return JSON.stringify({supabaseSession:t})}async function Di(t,e="supabase-session-sync"){var n;const r=z(t);if(!r.auth.canAttempt)return S.emit("auth.supabase.localBridgeSession.skipped",{source:e,reason:r.auth.mode}),!1;const s=re(t);if(!s)return S.emit("auth.supabase.localBridgeSession.skipped",{source:e,reason:"missing-client"}),!1;try{const{data:i,error:a}=await s.auth.getSession();if(a)return S.emit("auth.supabase.localBridgeSession.failed",{source:e,phase:"get-session",message:a.message}),!1;const o=i.session;if(!(o!=null&&o.access_token)||!((n=o.user)!=null&&n.id))return S.emit("auth.supabase.localBridgeSession.skipped",{source:e,reason:"session-missing"}),!1;const l=await yr(e);return l?(await _r(Pi(o),l.auth,l.baseUrl),S.emit("auth.supabase.localBridgeSession.synced",{source:e,baseUrl:l.baseUrl,hasRefreshToken:!!o.refresh_token,expiresAt:o.expires_at??null}),!0):!1}catch(i){return S.emit("auth.supabase.localBridgeSession.failed",{source:e,phase:"save-session",message:i instanceof Error?i.message:String(i)}),!1}}async function ji(t="supabase-session-clear"){try{const e=await yr(t);return e?(await Sr(e.auth,e.baseUrl),S.emit("auth.supabase.localBridgeSession.cleared",{source:t,baseUrl:e.baseUrl}),!0):!1}catch(e){return S.emit("auth.supabase.localBridgeSession.failed",{source:t,phase:"clear-session",message:e instanceof Error?e.message:String(e)}),!1}}function Bi(t,e,r=window.location.origin){const s=new URL(t,Ci(r));return e&&s.searchParams.set("next",e.startsWith("/")?e:`/${e}`),s.toString()}async function qi(t,e){const r=z(t);if(!r.auth.canAttempt)return S.emit("auth.supabase.oauth.skipped",{mode:r.auth.mode}),Oe(r);const s=re(t);if(!s)return S.emit("auth.supabase.oauth.skipped",{mode:"config-missing"}),{mode:"config-missing",canAttempt:!1,reason:"missing-client"};S.emit("auth.supabase.oauth.started",{provider:"google",redirectPath:new URL(e).pathname,redirectOrigin:new URL(e).origin});const{data:n,error:i}=await s.auth.signInWithOAuth({provider:"google",options:{redirectTo:e,skipBrowserRedirect:!0}});if(i)throw S.emit("auth.supabase.oauth.failed",{provider:"google",message:i.message}),i;if(!n.url){const o=new Error("Supabase OAuth did not return a redirect URL.");throw S.emit("auth.supabase.oauth.failed",{provider:"google",message:o.message}),o}const a=new URL(n.url);return S.emit("auth.supabase.oauth.redirecting",{provider:"google",oauthOrigin:a.origin,oauthPath:a.pathname}),window.location.assign(a.toString()),Oe(r)}async function Hi(t,e,r){const s=z(t);if(!s.passwordReset.canAttempt)return S.emit("auth.supabase.reset.skipped",{mode:s.passwordReset.mode}),{mode:s.passwordReset.mode,canAttempt:!1,reason:s.passwordReset.mode};const n=re(t);if(!n)return S.emit("auth.supabase.reset.skipped",{mode:"config-missing"}),{mode:"config-missing",canAttempt:!1,reason:"missing-client"};S.emit("auth.supabase.reset.requested",{emailDomain:e.split("@")[1]||"",redirectPath:new URL(r).pathname});const{error:i}=await n.auth.resetPasswordForEmail(e,{redirectTo:r});if(i)throw S.emit("auth.supabase.reset.failed",{emailDomain:e.split("@")[1]||"",message:i.message}),i;return{mode:s.passwordReset.mode,canAttempt:!0,reason:"reset-email-sent"}}async function Mi(t,e){const r=z(t);if(!r.passwordReset.canAttempt)return S.emit("auth.supabase.password.skipped",{mode:r.passwordReset.mode}),{mode:r.passwordReset.mode,canAttempt:!1,reason:r.passwordReset.mode};const s=re(t);if(!s)return S.emit("auth.supabase.password.skipped",{mode:"config-missing"}),{mode:"config-missing",canAttempt:!1,reason:"missing-client"};S.emit("auth.supabase.password.updateRequested",{hasPassword:!!e});const{error:n}=await s.auth.updateUser({password:e});if(n)throw S.emit("auth.supabase.password.failed",{message:n.message}),n;return S.emit("auth.supabase.password.updated"),{mode:r.passwordReset.mode,canAttempt:!0,reason:"password-updated"}}async function Fi(t,e="supabase-sign-out"){const r=z(t);let s=null,n=!1;if(r.auth.canAttempt){const a=re(t);if(a){n=!0;const{error:o}=await a.auth.signOut({scope:"local"});o&&(s=o,S.emit("auth.supabase.signOut.failed",{source:e,message:o.message}))}else S.emit("auth.supabase.signOut.skipped",{source:e,reason:"missing-client"})}else S.emit("auth.supabase.signOut.skipped",{source:e,reason:r.auth.mode});const i=await ji(e);if(S.emit("auth.supabase.signedOut",{source:e,providerAttempted:n,localBridgeCleared:i}),s)throw s;return{mode:r.auth.mode,canAttempt:r.auth.canAttempt,reason:n?"signed-out":r.auth.mode}}async function wr(t,e,r){var o;const s=e==null?void 0:e.user;if(!(e!=null&&e.access_token)||!(s!=null&&s.id))return null;let n=s;try{const{data:l,error:c}=await t.auth.getUser();c?S.emit("auth.supabase.user.failed",{source:r,message:c.message}):(n=l.user??s,S.emit("auth.supabase.user.loaded",{source:r,hasUser:!!l.user,hasEmail:!!((o=l.user)!=null&&o.email)}))}catch(l){S.emit("auth.supabase.user.failed",{source:r,message:l instanceof Error?l.message:String(l)})}const i=n.id||s.id,a=n.email||s.email;return!i||!a?null:{userId:`supabase-${i}`,email:a.toLowerCase(),provider:"Google",signedInAt:new Date().toISOString()}}async function Ki(t,e){const r=z(t),n=new URL(e,window.location.origin).searchParams.get("code");if(!r.auth.canAttempt)return S.emit("auth.supabase.callback.skipped",{mode:r.auth.mode,hasCode:!!n}),{...Oe(r),hasCode:!!n,hasSession:!1,session:null};const i=re(t);if(!i)return S.emit("auth.supabase.callback.skipped",{mode:"config-missing",hasCode:!!n}),{mode:"config-missing",canAttempt:!1,reason:"missing-client",hasCode:!!n,hasSession:!1,session:null};if(n){S.emit("auth.supabase.callback.exchangeStarted");const{error:c}=await i.auth.exchangeCodeForSession(n);if(c)throw S.emit("auth.supabase.callback.failed",{message:c.message}),c}const{data:a,error:o}=await i.auth.getSession();if(o)throw S.emit("auth.supabase.session.failed",{message:o.message}),o;const l=await wr(i,a.session,"auth-callback");return S.emit("auth.supabase.session.loaded",{hasCode:!!n,hasSession:!!l}),{mode:r.auth.mode,canAttempt:!0,reason:l?"session-loaded":"session-missing",hasCode:!!n,hasSession:!!l,session:l}}async function Wi(t){const e=z(t);if(!e.auth.canAttempt)return S.emit("auth.supabase.sessionRestore.skipped",{mode:e.auth.mode}),{...Oe(e),hasCode:!1,hasSession:!1,session:null};const r=re(t);if(!r)return S.emit("auth.supabase.sessionRestore.skipped",{mode:"config-missing"}),{mode:"config-missing",canAttempt:!1,reason:"missing-client",hasCode:!1,hasSession:!1,session:null};const{data:s,error:n}=await r.auth.getSession();if(n)throw S.emit("auth.supabase.sessionRestore.failed",{message:n.message}),n;const i=await wr(r,s.session,"session-restore");return S.emit("auth.supabase.sessionRestore.loaded",{hasSession:!!i}),{mode:e.auth.mode,canAttempt:!0,reason:i?"session-loaded":"session-missing",hasCode:!1,hasSession:!!i,session:i}}export{Bi as buildSupabaseAuthRedirectUrl,ji as clearSupabaseAuthSessionFromLocalBridge,Ki as completeSupabaseAuthCallback,re as getSupabaseBrowserClient,Wi as loadSupabaseAuthSession,Hi as requestSupabasePasswordReset,Li as resolveSupabaseAuthAdapterState,Fi as signOutSupabaseAuthSession,qi as startSupabaseGoogleOAuth,Di as syncSupabaseAuthSessionToLocalBridge,Mi as updateSupabasePassword};
|
|
44
|
+
`);const A=await E.signMessage(new TextEncoder().encode(p),"utf8");if(!A||!(A instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=A}}try{const{data:_,error:v}=await w(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:te(g)},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:N});if(v)throw v;if(!_||!_.session||!_.user){const b=new ie;return this._returnResult({data:{user:null,session:null},error:b})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:v})}catch(_){if(m(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){const r=await L(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new an;const{data:i,error:a}=await w(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:N});if(await O(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const o=new ie;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}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:a})}catch(i){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,o=await w(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:N}),{data:l,error:c}=o;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){const u=new ie;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(m(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;try{if("email"in e){const{email:o,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await Z(this.storage,this.storageKey));const{error:h}=await w(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=l==null?void 0:l.data)!==null&&r!==void 0?r:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:o,options:l}=e,{data:c,error:u}=await w(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=l==null?void 0:l.data)!==null&&n!==void 0?n:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(a=l==null?void 0:l.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u})}throw new Ue("You must provide either an email or phone number.")}catch(o){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}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);const{data:a,error:o}=await w(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:N});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,c=a.user;return l!=null&&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(m(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,a;try{let o=null,l=null;this.flowType==="pkce"&&([o,l]=await Z(this.storage,this.storageKey));const c=await w(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==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:In});return!((i=c.data)===null||i===void 0)&&i.url&&I()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(o){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(o))return this._returnResult({data:null,error:o});throw o}}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=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new P;const{error:n}=await w(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(m(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:i}=e;let a=null,o=null;this.flowType==="pkce"&&([a,o]=await Z(this.storage,this.storageKey));const{error:l}=await w(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken},code_challenge:a,code_challenge_method:o},redirectTo:i==null?void 0:i.emailRedirectTo});return l&&await O(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:a,error:o}=await w(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o})}throw new Ue("You must provide either an email or phone number and a type")}catch(r){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(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){const 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;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const 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{const 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;const r=await L(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};const s=e.expires_at?e.expires_at*1e3-Date.now()<Xe:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await L(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=Qe()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=On(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i){if(!!(e.expires_at&&e.expires_at*1e3>Date.now())){const o=await L(this.storage,this.storageKey);if(o&&o.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 w(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:X}):await this._useSession(async r=>{var s,n,i;const{data:a,error:o}=r;if(o)throw o;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new P}:await w(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:X})})}catch(r){if(m(r))return xe(r)&&(await this._removeSession(),await O(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=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new P;const a=n.session;let o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await Z(this.storage,this.storageKey));const{data:c,error:u}=await w(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:l}),jwt:a.access_token,xform:X});if(u)throw u;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(s){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(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 P;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Le(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-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(m(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){const{data:a,error:o}=r;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new P;const{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(m(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!I())throw new Ne("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ne(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 jt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ne("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 jt("No code detected.");const{data:y,error:E}=await this._exchangeCodeForSession(e.code);if(E)throw E;const x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:y.session,redirectType:(s=y.redirectType)!==null&&s!==void 0?s:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:a,refresh_token:o,expires_in:l,expires_at:c,token_type:u}=e;if(!a||!l||!o||!u)throw new Ne("No session defined in URL");const h=Math.round(Date.now()/1e3),d=parseInt(l);let f=h+d;c&&(f=parseInt(c));const p=f-h;p*1e3<=G&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`);const g=f-d;h-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,f,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,f,h);const{data:_,error:v}=await this._getUser(a);if(v)throw v;const b={provider_token:n,provider_refresh_token:i,access_token:a,expires_in:d,expires_at:f,refresh_token:o,token_type:u,user:_.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(n){if(m(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){const r=await L(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;const{data:n,error:i}=r;if(i&&!xe(i))return this._returnResult({error:i});const a=(s=n.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);if(o&&!(sn(o)&&(o.status===404||o.status===401||o.status===403)||xe(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await O(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=pn(),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{const{data:{session:i},error:a}=r;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),xe(i)?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Z(this.storage,this.storageKey,!0));try{return await w(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 O(this.storage,`${this.storageKey}-code-verifier`),m(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{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(m(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{const{data:s,error:n}=await this._useSession(async i=>{var a,o,l,c,u;const{data:h,error:d}=i;if(d)throw d;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await w(this.fetch,"GET",f,{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 I()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(m(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{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:o,token:l,access_token:c,nonce:u}=e,h=await w(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i==null?void 0:i.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:N}),{data:d,error:f}=h;return f?this._returnResult({data:{user:null,session:null},error:f}):!d||!d.session||!d.user?this._returnResult({data:{user:null,session:null},error:new ie}):(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:f}))}catch(n){if(await O(this.storage,`${this.storageKey}-code-verifier`),m(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;const{data:i,error:a}=r;if(a)throw a;return await w(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(m(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r="#_refreshAccessToken()";this._debug(r,"begin");try{const s=Date.now();return await wn(async n=>(n>0&&await yn(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await w(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:N})),(n,i)=>{const a=200*Math.pow(2,n);return i&&It(i)&&Date.now()+a-s<G})}catch(s){if(this._debug(r,"error",s),m(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),I()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await L(this.storage,this.storageKey);if(n&&this.userStorage){let a=await L(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await ue(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:Qe()}else if(n&&!n.user&&!n.user){const a=await L(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(n.user=a.user,await O(this.storage,this.storageKey+"-user"),await ue(this.storage,this.storageKey,n)):n.user=Qe()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Xe;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Xe}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(on(a)?this._debug(s,"refresh discarded by commit guard",a):this._debug(s,"refresh failed",a))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(n.access_token);!o&&(a!=null&&a.user)?(n.user=a.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new P;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;const n="#_callRefreshToken()";this._debug(n,"begin");try{this.refreshingDeferred=new Ye;const i=await L(this.storage,this.storageKey),{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new P;const l=await L(this.storage,this.storageKey);if(i!==null&&(l===null||l.refresh_token!==i.refresh_token)){this._debug(n,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:l?"replaced":"cleared"});const d={data:null,error:new $t};return this.refreshingDeferred.resolve(d),d}const u=this._sessionRemovalEpoch;if(await this._saveSession(a.session),this._sessionRemovalEpoch!==u){this._debug(n,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await O(this.storage,this.storageKey),this.userStorage&&await O(this.userStorage,this.storageKey+"-user");const d={data:null,error:new $t};return this.refreshingDeferred.resolve(d),d}await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const h={data:a.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(h),h}catch(i){if(this._debug(n,"error",i),m(i)){const a={data:null,error:i};if(!It(i)){const o=await L(this.storage,this.storageKey);!!(o!=null&&o.expires_at&&o.expires_at*1e3>Date.now())?this._debug(n,"proactive refresh failed, access token still valid — preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:a,expiresAt:Date.now()+Ys},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await O(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await ue(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=Dt(n);await ue(this.storage,this.storageKey,i)}else{const n=Dt(r);await ue(this.storage,this.storageKey,n)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await O(this.storage,this.storageKey),await O(this.storage,this.storageKey+"-code-verifier"),await O(this.storage,this.storageKey+"-user"),this.userStorage&&await O(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&I()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),G);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const 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()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const 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{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/G);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${G}ms, refresh threshold is ${me} ticks`),n<=me&&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 Nn)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{const e=Date.now();try{await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/G);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${G}ms, refresh threshold is ${me} ticks`),n<=me&&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()"),!I()||!(window!=null&&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==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const 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){const n=[`provider=${encodeURIComponent(r)}`];if(s!=null&&s.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,a]=await Z(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});n.push(o.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await w(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(m(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await w(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=i==null?void 0: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==null?void 0: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(m(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){const r=async()=>{try{return await this._useSession(async s=>{var n;const{data:i,error:a}=s;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Wt(e.webauthn.credential_response):Vt(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i==null?void 0: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(m(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){const r=async()=>{try{return await this._useSession(async s=>{var n;const{data:i,error:a}=s;if(a)return this._returnResult({data:null,error:a});const o=await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;const{data:l}=o;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:Ft(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:Kt(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(m(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){const{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;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r==null?void 0: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{const{payload:f}=Le(e);let p=null;f.aal&&(p=f.aal);let g=p;const{data:{user:_},error:v}=await this.getUser(e);if(v)return this._returnResult({data:null,error:v});((s=(r=_==null?void 0:_.factors)===null||r===void 0?void 0:r.filter(E=>E.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(g="aal2");const y=f.amr||[];return{data:{currentLevel:p,nextLevel:g,currentAuthenticationMethods:y},error:null}}catch(f){if(m(f))return this._returnResult({data:null,error:f});throw f}const{data:{session:a},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=Le(a.access_token);let c=null;l.aal&&(c=l.aal);let u=c;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");const d=l.amr||[];return{data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:d},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await w(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 P})})}catch(r){if(m(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new P});const a=await w(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&I()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(m(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new P});const a=await w(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&I()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(m(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await w(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 P})})}catch(e){if(m(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await w(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 P})})}catch(r){if(m(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(o=>o.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+tn>n)return s;const{data:i,error:a}=await w(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:f,error:p}=await this.getSession();if(p||!f.session)return this._returnResult({data:null,error:p});s=f.session.access_token}const{header:n,payload:i,signature:a,raw:{header:o,payload:l}}=Le(s);if(!(r!=null&&r.allowExpired))try{Tn(i.exp)}catch(f){throw new He(f instanceof Error?f.message:"JWT validation failed")}const c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!c){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:n,signature:a},error:null}}const u=An(n.alg),h=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,a,dn(`${o}.${l}`)))throw new He("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(m(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n;D(this.experimental);try{if(!Ke())return this._returnResult({data:null,error:new q("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}});if(a||!i)return this._returnResult({data:null,error:a});const o=Kt(i.options),l=(n=(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:ft.createNewAbortSignal(),{data:c,error:u}=await gr({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new q("WebAuthn ceremony failed",null)});const h=Vt(c);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:h})}catch(i){if(m(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var r,s;D(this.experimental);try{if(!Ke())return this._returnResult({data:null,error:new q("Browser does not support WebAuthn",null)});const{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});const a=Ft(n.options),o=(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:ft.createNewAbortSignal(),{data:l,error:c}=await pr({publicKey:a,signal:o});if(c||!l)return this._returnResult({data:null,error:c??new q("WebAuthn ceremony failed",null)});const u=Wt(l);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:u})}catch(n){if(m(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){D(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new P});const{data:n,error:i}=await w(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(m(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){D(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});const{data:i,error:a}=await w(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(m(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;D(this.experimental);try{const{data:s,error:n}=await w(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e==null?void 0: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(m(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){D(this.experimental);try{const{data:r,error:s}=await w(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:N});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(m(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){D(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new P});const{data:n,error:i}=await w(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:a=>({data:a,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(m(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){D(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});const{data:i,error:a}=await w(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(m(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){D(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});const{error:i}=await w(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(m(r))return this._returnResult({data:null,error:r});throw r}}}Ae.nextInstanceID={};const Yn=Ae,Xn="2.108.2";let ye="",Ve;if(typeof Deno<"u"){var et;ye="deno",Ve=(et=Deno.version)===null||et===void 0?void 0:et.deno}else if(typeof document<"u")ye="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")ye="react-native";else{var tt;ye="node",Ve=typeof process<"u"?(tt=process.version)===null||tt===void 0?void 0:tt.replace(/^v/,""):void 0}const mr=[`runtime=${ye}`];Ve&&mr.push(`runtime-version=${Ve}`);const Qn={"X-Client-Info":`supabase-js/${Xn}; ${mr.join("; ")}`},Zn={headers:Qn},ei={schema:"public"},ti={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ri={},si={enabled:!1,respectSamplingDecision:!0};function ni(t,e,r,s){function n(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):n(u.value).then(o,l)}c((s=s.apply(t,[])).next())})}let rt=null;const ii="@opentelemetry/api";function ai(){return rt===null&&(rt=import(ii).catch(()=>null)),rt}function oi(){return ni(this,void 0,void 0,function*(){try{const t=yield ai();if(!t||!t.propagation||!t.context)return null;const e={};t.propagation.inject(t.context.active(),e);const r=e.traceparent;return r?{traceparent:r,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function li(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;const a=/^[0-9a-f]+$/i;return!a.test(r)||!a.test(s)||!a.test(n)||!a.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function ci(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(const s of e)try{if(typeof s=="string"){if(ui(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 ui(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function hi(t){const e=[];try{const 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 Re(t){"@babel/helpers - typeof";return Re=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},Re(t)}function di(t,e){if(Re(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Re(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function fi(t){var e=di(t,"string");return Re(e)=="symbol"?e:e+""}function pi(t,e,r){return(e=fi(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Jt(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 R(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Jt(Object(r),!0).forEach(function(s){pi(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Jt(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const gi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),mi=()=>Headers,yi=(t,e,r,s,n)=>{const i=gi(s),a=mi(),o=(n==null?void 0:n.enabled)===!0,l=(n==null?void 0:n.respectSamplingDecision)!==!1,c=o?hi(e):null;return async(u,h)=>{var d;const f=(d=await r())!==null&&d!==void 0?d:t;let p=new a(h==null?void 0:h.headers);if(p.has("apikey")||p.set("apikey",t),p.has("Authorization")||p.set("Authorization",`Bearer ${f}`),c){const g=await wi(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,R(R({},h),{},{headers:p}))}};async function wi(t,e,r){if(!ci(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const s=await oi();if(!s||!s.traceparent)return null;if(r){const n=li(s.traceparent);if(n&&!n.isSampled)return null}return s}function Gt(t){return typeof t=="boolean"?{enabled:t}:t}function vi(t){return t.endsWith("/")?t:t+"/"}function _i(t,e){var r,s,n,i,a,o;const{db:l,auth:c,realtime:u,global:h}=t,{db:d,auth:f,realtime:p,global:g}=e,_=Gt(t.tracePropagation),v=Gt(e.tracePropagation),b={db:R(R({},d),l),auth:R(R({},f),c),realtime:R(R({},p),u),storage:{},global:R(R(R({},g),h),{},{headers:R(R({},(r=g==null?void 0:g.headers)!==null&&r!==void 0?r:{}),(s=h==null?void 0:h.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=_==null?void 0:_.enabled)!==null&&i!==void 0?i:v==null?void 0:v.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(a=(o=_==null?void 0:_.respectSamplingDecision)!==null&&o!==void 0?o:v==null?void 0:v.respectSamplingDecision)!==null&&a!==void 0?a:!0},accessToken:async()=>""};return t.accessToken?b.accessToken=t.accessToken:delete b.accessToken,b}function bi(t){const e=t==null?void 0: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(vi(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var ki=class extends Yn{constructor(t){super(t)}},Si=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=bi(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);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:ei,realtime:ri,auth:R(R({},ti),{},{storageKey:a}),global:Zn,tracePropagation:si},l=_i(r??{},o);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=yi(e,t,this._getAccessToken.bind(this),l.global.fetch,l.tracePropagation),this.realtime=this._initRealtimeClient(R({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 Nr(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 zs(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Rr(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();const{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:a,lock:o,debug:l,throwOnError:c,experimental:u,lockAcquireTimeout:h,skipAutoInitialize:d},f,p){const g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ki({url:this.authUrl.href,headers:R(R({},g),f),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:l,throwOnError:c,experimental:u,fetch:p,lockAcquireTimeout:h,skipAutoInitialize:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(_=>_.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new ws(this.realtimeUrl.href,R(R({},t),{},{params:R(R({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0: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)}};const Ei=(t,e,r)=>new Si(t,e,r);function Ti(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Ti()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Ai=["VITE_MINDEXEC_SUPABASE_PUBLISHABLE_KEY","VITE_SUPABASE_PUBLISHABLE_KEY","VITE_MINDEXEC_SUPABASE_ANON_KEY","VITE_SUPABASE_ANON_KEY"];let oe=null;function Ri(t,e){for(const r of e){const s=t[r],n=typeof s=="string"?s.trim():"";if(n)return{key:r,value:n}}return null}function Oi(t){const e=z(t),r=Ri(t,Ai);return!e.auth.canAttempt||!e.supabaseUrl.url||!r?null:{url:e.supabaseUrl.url,publicKey:r.value,keyEnvName:r.key,config:e}}function Oe(t){return{mode:t.auth.mode,canAttempt:t.auth.canAttempt,reason:t.auth.mode}}function Li(t){return Oe(z(t))}function re(t){const e=Oi(t);if(!e)return null;const r=`${e.url}|${e.keyEnvName}|${e.publicKey}`;return(oe==null?void 0:oe.cacheKey)===r||(oe={cacheKey:r,client:Ei(e.url,e.publicKey,{auth:{autoRefreshToken:!0,detectSessionInUrl:!0,flowType:"pkce",persistSession:!0}})}),oe.client}function Ci(t){try{const e=new URL(t),r=e.hostname.toLowerCase();return e.protocol==="http:"&&(r==="127.0.0.1"||r==="::1"||r==="[::1]"||r==="0.0.0.0")&&(e.hostname="localhost"),e.origin}catch{return t}}async function yr(t){if(typeof window>"u")return S.emit("auth.supabase.localBridgeSession.skipped",{source:t,reason:"non-browser"}),null;try{const e=await br(),r=kr(e.status);return e.state!=="connected"||!r?(S.emit("auth.supabase.localBridgeSession.skipped",{source:t,reason:e.state==="connected"?"bridge-auth-missing":"bridge-unavailable",baseUrl:e.baseUrl}),null):{auth:r,baseUrl:e.baseUrl}}catch(e){return S.emit("auth.supabase.localBridgeSession.failed",{source:t,phase:"bridge-status",message:e instanceof Error?e.message:String(e)}),null}}function Pi(t){return JSON.stringify({supabaseSession:t})}async function Di(t,e="supabase-session-sync"){var n;const r=z(t);if(!r.auth.canAttempt)return S.emit("auth.supabase.localBridgeSession.skipped",{source:e,reason:r.auth.mode}),!1;const s=re(t);if(!s)return S.emit("auth.supabase.localBridgeSession.skipped",{source:e,reason:"missing-client"}),!1;try{const{data:i,error:a}=await s.auth.getSession();if(a)return S.emit("auth.supabase.localBridgeSession.failed",{source:e,phase:"get-session",message:a.message}),!1;const o=i.session;if(!(o!=null&&o.access_token)||!((n=o.user)!=null&&n.id))return S.emit("auth.supabase.localBridgeSession.skipped",{source:e,reason:"session-missing"}),!1;const l=await yr(e);return l?(await _r(Pi(o),l.auth,l.baseUrl),S.emit("auth.supabase.localBridgeSession.synced",{source:e,baseUrl:l.baseUrl,hasRefreshToken:!!o.refresh_token,expiresAt:o.expires_at??null}),!0):!1}catch(i){return S.emit("auth.supabase.localBridgeSession.failed",{source:e,phase:"save-session",message:i instanceof Error?i.message:String(i)}),!1}}async function ji(t="supabase-session-clear"){try{const e=await yr(t);return e?(await Sr(e.auth,e.baseUrl),S.emit("auth.supabase.localBridgeSession.cleared",{source:t,baseUrl:e.baseUrl}),!0):!1}catch(e){return S.emit("auth.supabase.localBridgeSession.failed",{source:t,phase:"clear-session",message:e instanceof Error?e.message:String(e)}),!1}}function Bi(t,e,r=window.location.origin){const s=new URL(t,Ci(r));return e&&s.searchParams.set("next",e.startsWith("/")?e:`/${e}`),s.toString()}async function qi(t,e){const r=z(t);if(!r.auth.canAttempt)return S.emit("auth.supabase.oauth.skipped",{mode:r.auth.mode}),Oe(r);const s=re(t);if(!s)return S.emit("auth.supabase.oauth.skipped",{mode:"config-missing"}),{mode:"config-missing",canAttempt:!1,reason:"missing-client"};S.emit("auth.supabase.oauth.started",{provider:"google",redirectPath:new URL(e).pathname,redirectOrigin:new URL(e).origin});const{data:n,error:i}=await s.auth.signInWithOAuth({provider:"google",options:{redirectTo:e,queryParams:{prompt:"select_account"},skipBrowserRedirect:!0}});if(i)throw S.emit("auth.supabase.oauth.failed",{provider:"google",message:i.message}),i;if(!n.url){const o=new Error("Supabase OAuth did not return a redirect URL.");throw S.emit("auth.supabase.oauth.failed",{provider:"google",message:o.message}),o}const a=new URL(n.url);return S.emit("auth.supabase.oauth.redirecting",{provider:"google",oauthOrigin:a.origin,oauthPath:a.pathname}),window.location.assign(a.toString()),Oe(r)}async function Hi(t,e,r){const s=z(t);if(!s.passwordReset.canAttempt)return S.emit("auth.supabase.reset.skipped",{mode:s.passwordReset.mode}),{mode:s.passwordReset.mode,canAttempt:!1,reason:s.passwordReset.mode};const n=re(t);if(!n)return S.emit("auth.supabase.reset.skipped",{mode:"config-missing"}),{mode:"config-missing",canAttempt:!1,reason:"missing-client"};S.emit("auth.supabase.reset.requested",{emailDomain:e.split("@")[1]||"",redirectPath:new URL(r).pathname});const{error:i}=await n.auth.resetPasswordForEmail(e,{redirectTo:r});if(i)throw S.emit("auth.supabase.reset.failed",{emailDomain:e.split("@")[1]||"",message:i.message}),i;return{mode:s.passwordReset.mode,canAttempt:!0,reason:"reset-email-sent"}}async function Mi(t,e){const r=z(t);if(!r.passwordReset.canAttempt)return S.emit("auth.supabase.password.skipped",{mode:r.passwordReset.mode}),{mode:r.passwordReset.mode,canAttempt:!1,reason:r.passwordReset.mode};const s=re(t);if(!s)return S.emit("auth.supabase.password.skipped",{mode:"config-missing"}),{mode:"config-missing",canAttempt:!1,reason:"missing-client"};S.emit("auth.supabase.password.updateRequested",{hasPassword:!!e});const{error:n}=await s.auth.updateUser({password:e});if(n)throw S.emit("auth.supabase.password.failed",{message:n.message}),n;return S.emit("auth.supabase.password.updated"),{mode:r.passwordReset.mode,canAttempt:!0,reason:"password-updated"}}async function Fi(t,e="supabase-sign-out"){const r=z(t);let s=null,n=!1;if(r.auth.canAttempt){const a=re(t);if(a){n=!0;const{error:o}=await a.auth.signOut({scope:"local"});o&&(s=o,S.emit("auth.supabase.signOut.failed",{source:e,message:o.message}))}else S.emit("auth.supabase.signOut.skipped",{source:e,reason:"missing-client"})}else S.emit("auth.supabase.signOut.skipped",{source:e,reason:r.auth.mode});const i=await ji(e);if(S.emit("auth.supabase.signedOut",{source:e,providerAttempted:n,localBridgeCleared:i}),s)throw s;return{mode:r.auth.mode,canAttempt:r.auth.canAttempt,reason:n?"signed-out":r.auth.mode}}async function wr(t,e,r){var o;const s=e==null?void 0:e.user;if(!(e!=null&&e.access_token)||!(s!=null&&s.id))return null;let n=s;try{const{data:l,error:c}=await t.auth.getUser();c?S.emit("auth.supabase.user.failed",{source:r,message:c.message}):(n=l.user??s,S.emit("auth.supabase.user.loaded",{source:r,hasUser:!!l.user,hasEmail:!!((o=l.user)!=null&&o.email)}))}catch(l){S.emit("auth.supabase.user.failed",{source:r,message:l instanceof Error?l.message:String(l)})}const i=n.id||s.id,a=n.email||s.email;return!i||!a?null:{userId:`supabase-${i}`,email:a.toLowerCase(),provider:"Google",signedInAt:new Date().toISOString()}}async function Ki(t,e){const r=z(t),n=new URL(e,window.location.origin).searchParams.get("code");if(!r.auth.canAttempt)return S.emit("auth.supabase.callback.skipped",{mode:r.auth.mode,hasCode:!!n}),{...Oe(r),hasCode:!!n,hasSession:!1,session:null};const i=re(t);if(!i)return S.emit("auth.supabase.callback.skipped",{mode:"config-missing",hasCode:!!n}),{mode:"config-missing",canAttempt:!1,reason:"missing-client",hasCode:!!n,hasSession:!1,session:null};if(n){S.emit("auth.supabase.callback.exchangeStarted");const{error:c}=await i.auth.exchangeCodeForSession(n);if(c)throw S.emit("auth.supabase.callback.failed",{message:c.message}),c}const{data:a,error:o}=await i.auth.getSession();if(o)throw S.emit("auth.supabase.session.failed",{message:o.message}),o;const l=await wr(i,a.session,"auth-callback");return S.emit("auth.supabase.session.loaded",{hasCode:!!n,hasSession:!!l}),{mode:r.auth.mode,canAttempt:!0,reason:l?"session-loaded":"session-missing",hasCode:!!n,hasSession:!!l,session:l}}async function Wi(t){const e=z(t);if(!e.auth.canAttempt)return S.emit("auth.supabase.sessionRestore.skipped",{mode:e.auth.mode}),{...Oe(e),hasCode:!1,hasSession:!1,session:null};const r=re(t);if(!r)return S.emit("auth.supabase.sessionRestore.skipped",{mode:"config-missing"}),{mode:"config-missing",canAttempt:!1,reason:"missing-client",hasCode:!1,hasSession:!1,session:null};const{data:s,error:n}=await r.auth.getSession();if(n)throw S.emit("auth.supabase.sessionRestore.failed",{message:n.message}),n;const i=await wr(r,s.session,"session-restore");return S.emit("auth.supabase.sessionRestore.loaded",{hasSession:!!i}),{mode:e.auth.mode,canAttempt:!0,reason:i?"session-loaded":"session-missing",hasCode:!1,hasSession:!!i,session:i}}export{Bi as buildSupabaseAuthRedirectUrl,ji as clearSupabaseAuthSessionFromLocalBridge,Ki as completeSupabaseAuthCallback,re as getSupabaseBrowserClient,Wi as loadSupabaseAuthSession,Hi as requestSupabasePasswordReset,Li as resolveSupabaseAuthAdapterState,Fi as signOutSupabaseAuthSession,qi as startSupabaseGoogleOAuth,Di as syncSupabaseAuthSessionToLocalBridge,Mi as updateSupabasePassword};
|
package/wwwroot/index.html
CHANGED
|
@@ -7,11 +7,11 @@
|
|
|
7
7
|
name="description"
|
|
8
8
|
content="MindExec React is a fast AI execution canvas for solo builders, notes, assets, and task graphs."
|
|
9
9
|
/>
|
|
10
|
-
<meta name="build-version" content="
|
|
10
|
+
<meta name="build-version" content="ai-rich-model-catalog-2026-06-27" />
|
|
11
11
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
12
12
|
<link rel="manifest" href="/manifest.webmanifest" />
|
|
13
13
|
<title>MindExec React</title>
|
|
14
|
-
<script type="module" crossorigin src="/assets/index-
|
|
14
|
+
<script type="module" crossorigin src="/assets/index-Bc6exjGV.js"></script>
|
|
15
15
|
<link rel="modulepreload" crossorigin href="/assets/vendor-react-BXzpOyCS.js">
|
|
16
16
|
<link rel="modulepreload" crossorigin href="/assets/app-runtime-xD2Z3NdN.js">
|
|
17
17
|
<link rel="stylesheet" crossorigin href="/assets/index-yNpEK-gp.css">
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r,j as e}from"./vendor-react-BXzpOyCS.js";import{g as C,a as f,s as $,b as q,c as R,d as G}from"./index-BnDICYGs.js";import{p as L,P as K}from"./pricingCheckoutShell-O-DnwmbU.js";import{r as U}from"./productionAdapterConfig-C5jfk6oG.js";import{R as b}from"./app-runtime-xD2Z3NdN.js";import{syncSupabaseAuthSessionToLocalBridge as T,loadSupabaseAuthSession as F,buildSupabaseAuthRedirectUrl as O,startSupabaseGoogleOAuth as _,signOutSupabaseAuthSession as D,requestSupabasePasswordReset as H,updateSupabasePassword as Y}from"./supabaseAuthAdapter-Ct6_adpn.js";import{X as V,ao as W,ag as X,aT as z,N as I,f as J,aU as k,K as M,aV as Q,ac as Z}from"./vendor-icons-678PAT8P.js";import"./canvas-runtime-CcSvL_l6.js";function ee(o){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.trim())}function S(){return U(f())}function N(o,a,c=!1){return o.source==="supabase-provider-session"?a?`Google sign-in is active for ${o.email}. Return to pricing to continue checkout.`:`Google sign-in is active for ${o.email}.`:c?a?"A local auth shell exists, but secure Google sign-in is required before checkout can continue.":"A local auth shell exists, but secure Google sign-in is required before MindCanvas can sync remote services.":a?"A local Google auth shell is active. Return to pricing to continue checkout.":"A local Google auth shell is already active for this browser."}function B(o,a){return a?`Local Google auth shell ready for ${o}. Return to pricing to continue the gated checkout.`:`Local Google auth shell ready for ${o}. Secure Supabase OAuth can replace this adapter later.`}function ue({navigate:o}){const[a,c]=r.useState(!1),[s,d]=r.useState(()=>C()),[n]=r.useState(()=>L()),l=r.useMemo(()=>S(),[]),[x,u]=r.useState(()=>{const t=C(),i=L();return t?N(t,!!i,S().auth.canAttempt):i?"Sign in to continue MindCanvas Pro checkout. Payment remains gated until the secure adapter is connected.":"Use your Google account to sync cloud projects. No password to create or remember."});r.useEffect(()=>{if((s==null?void 0:s.source)==="supabase-provider-session"||!l.auth.canAttempt)return;let t=!1;return(async()=>{try{const w=await F(f());if(t||!w.session)return;const E=$({...w.session,source:"supabase-provider-session"});d(E),u(N(E,!!n,l.auth.canAttempt))}catch(w){b.emit("auth.supabase.sessionRestore.uiFailed",{message:w instanceof Error?w.message:String(w)})}})(),()=>{t=!0}},[n,l.auth.canAttempt,s==null?void 0:s.source]),r.useEffect(()=>{(s==null?void 0:s.source)!=="supabase-provider-session"||!l.auth.canAttempt||T(f(),"login-existing-session")},[l.auth.canAttempt,s==null?void 0:s.email,s==null?void 0:s.source]);const p=()=>{const t=C();if(t)return d(t),u(N(t,!!n,l.auth.canAttempt)),t;const i=G();return d(i),u(B(i.email,!!n)),i},m=async()=>{const t=p();t.source==="supabase-provider-session"&&await T(f(),"login-continue");const i={hasCheckoutIntent:!!n,signedIn:!!t,sessionSource:t.source};n?b.emit("auth.returnToPricing",i):b.emit("auth.continueMindCanvas",i),o(n?"/pricing":"/mindcanvas")},g=()=>{const t=G();d(t),u(B(t.email,!!n)),c(!1),window.setTimeout(()=>{m()},240)},h=async()=>{if(c(!0),l.auth.canAttempt)try{const t=O("/login",n?"/pricing":"/mindcanvas");u("Opening secure Google sign-in..."),(s==null?void 0:s.source)!=="supabase-provider-session"&&(R(),d(null)),await _(f(),t);return}catch(t){u(`Secure Google sign-in failed: ${t instanceof Error?t.message:String(t)}`),c(!1);return}window.setTimeout(()=>{g()},550)},j=!!(s&&(!l.auth.canAttempt||s.source==="supabase-provider-session")),v=j?n?"Continue checkout":"Continue to MindCanvas":a?"Opening Google...":"Continue with Google",y=j?m:h,A=async()=>{c(!0),u("Signing out...");let t="";try{await D(f(),"login-sign-out")}catch(i){t=i instanceof Error?i.message:String(i),b.emit("auth.signOut.uiFailed",{message:t})}R(),d(null),u(t?`Signed out locally. Provider sign-out warning: ${t}`:n?"Signed out. Choose another Google account to continue checkout.":"Signed out. Choose another Google account to continue."),c(!1)};return e.jsxs(P,{page:"login",children:[e.jsx("button",{className:"auth-close",type:"button",title:"Close",onClick:()=>o("/mindcanvas"),"data-testid":"auth-close",children:e.jsx(V,{size:16})}),e.jsxs("div",{className:"auth-logo",children:[e.jsx(W,{size:24}),e.jsx("strong",{children:"MindExec"})]}),e.jsx("h1",{children:"Sign in with Google"}),e.jsx("p",{"data-testid":"auth-message",children:x}),e.jsxs("button",{className:"google-button",type:"button",disabled:a,onClick:y,"data-testid":"auth-google-shell",children:[e.jsx("span",{className:"google-g",children:"G"}),v]}),e.jsxs("div",{className:"auth-action-strip",children:[s&&n&&e.jsx("button",{type:"button",onClick:()=>void m(),"data-testid":"auth-return-pricing",children:"Return to pricing"}),s&&e.jsx("button",{type:"button",disabled:a,onClick:()=>void A(),"data-testid":"auth-sign-out",children:"Sign out"}),e.jsx("button",{type:"button",onClick:()=>o("/forgot-password"),"data-testid":"auth-forgot-password",children:"Forgot password"}),e.jsx("button",{type:"button",onClick:()=>o("/pricing"),"data-testid":"auth-view-pricing",children:"View pricing"})]}),e.jsx("p",{className:"auth-note",children:l.auth.canAttempt?"Secure Supabase OAuth is connected for this browser build.":"The React port keeps this as a local auth shell until the secure Supabase OAuth adapter is connected."})]})}function le({navigate:o}){const[a,c]=r.useState(""),[s,d]=r.useState(!1),[n,l]=r.useState(""),[x,u]=r.useState(!1),p=r.useMemo(()=>S(),[]),m=async g=>{if(g.preventDefault(),!ee(a)){l("Enter a valid email address.");return}if(d(!0),l(""),p.passwordReset.canAttempt){try{const h=O("/reset-password","/login");await H(f(),a,h),u(!0),d(!1),b.emit("auth.reset.requested",{emailDomain:a.split("@")[1]||"",provider:"supabase"})}catch(h){l(h instanceof Error?h.message:String(h)),d(!1)}return}window.setTimeout(()=>{u(!0),d(!1),b.emit("auth.reset.requested",{emailDomain:a.split("@")[1]||""})},450)};return e.jsxs(P,{page:"forgot-password",children:[e.jsxs("button",{className:"auth-back",type:"button",onClick:()=>o("/login"),"data-testid":"forgot-back-login",children:[e.jsx(X,{size:16}),"Sign in"]}),e.jsx("div",{className:"auth-mark auth-mark--amber",children:e.jsx(z,{size:28})}),e.jsx("h1",{children:"Forgot password?"}),e.jsx("p",{children:"No worries. Enter your email and the React auth shell will walk through the reset flow."}),n&&e.jsx("div",{className:"auth-inline-error","data-testid":"forgot-error",children:n}),x?e.jsxs("div",{className:"auth-success-panel","data-testid":"forgot-success",children:[e.jsx(I,{size:32}),e.jsx("strong",{children:"Check your email"}),e.jsxs("span",{children:["Reset instructions were prepared for ",a,"."]}),e.jsx("button",{className:"btn btn-primary",type:"button",onClick:()=>o("/reset-password"),"data-testid":"forgot-continue-reset",children:"Continue to reset"})]}):e.jsxs("form",{className:"auth-form",onSubmit:m,"data-testid":"forgot-password-form",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Email Address"}),e.jsxs("div",{className:"auth-input-wrap",children:[e.jsx(z,{size:18}),e.jsx("input",{value:a,onChange:g=>c(g.target.value),type:"email",placeholder:"you@example.com","data-testid":"forgot-email"})]})]}),e.jsxs("button",{className:"btn btn-primary auth-submit",type:"submit",disabled:s,"data-testid":"forgot-submit",children:[e.jsx(J,{size:16}),s?"Sending...":"Send Reset Link"]})]})]})}function de({navigate:o}){const[a,c]=r.useState(""),[s,d]=r.useState(""),[n,l]=r.useState(!1),[x,u]=r.useState(!1),[p,m]=r.useState(!1),[g,h]=r.useState(""),j=r.useMemo(()=>S(),[]),v=r.useMemo(()=>a.length>=6&&a===s,[s,a]),y=s.length>0&&s!==a,A=async t=>{if(t.preventDefault(),a.length<6){h("Password must be at least 6 characters.");return}if(a!==s){h("Passwords do not match.");return}if(u(!0),h(""),j.passwordReset.canAttempt){try{await Y(f(),a),m(!0),u(!1),b.emit("auth.password.updated",{provider:"supabase"})}catch(i){h(i instanceof Error?i.message:String(i)),u(!1)}return}window.setTimeout(()=>{m(!0),u(!1),b.emit("auth.password.updated",{localShell:!0})},520)};return e.jsxs(P,{page:"reset-password",children:[e.jsx("div",{className:`auth-mark ${p?"auth-mark--success":""}`,children:p?e.jsx(I,{size:30}):e.jsx(k,{size:30})}),e.jsx("h1",{children:p?"Password reset!":"Reset password"}),e.jsx("p",{"data-testid":"reset-message",children:p?"Your local auth shell accepted the new password state.":"Enter a new password and confirm it below."}),g&&e.jsx("div",{className:"auth-inline-error","data-testid":"reset-error",children:g}),p?e.jsxs("button",{className:"btn btn-primary auth-submit",type:"button",onClick:()=>o("/login"),"data-testid":"reset-login",children:[e.jsx(M,{size:16}),"Sign In"]}):e.jsxs("form",{className:"auth-form",onSubmit:A,"data-testid":"reset-password-form",children:[e.jsxs("label",{children:[e.jsx("span",{children:"New Password"}),e.jsxs("div",{className:"auth-input-wrap",children:[e.jsx(k,{size:18}),e.jsx("input",{value:a,onChange:t=>c(t.target.value),type:n?"text":"password",placeholder:"Enter new password","data-testid":"reset-password-input"}),e.jsx("button",{type:"button",className:"auth-icon-button",title:"Toggle password visibility",onClick:()=>l(t=>!t),"data-testid":"reset-toggle-visibility",children:n?e.jsx(Q,{size:17}):e.jsx(Z,{size:17})})]}),e.jsx("span",{className:`auth-requirement ${a.length>=6?"is-met":""}`,children:"At least 6 characters"})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Confirm Password"}),e.jsxs("div",{className:"auth-input-wrap",children:[e.jsx(k,{size:18}),e.jsx("input",{value:s,onChange:t=>d(t.target.value),type:"password",placeholder:"Confirm new password","data-testid":"reset-confirm-input"})]}),s&&e.jsx("span",{className:`auth-requirement ${y?"is-error":"is-met"}`,children:y?"Passwords do not match":"Passwords match"})]}),e.jsxs("button",{className:"btn btn-primary auth-submit",type:"submit",disabled:!v||x,"data-testid":"reset-submit",children:[e.jsx(M,{size:16}),x?"Updating...":"Update Password"]})]})]})}function P({children:o,page:a}){const c=S();return e.jsxs("div",{className:"auth-page","data-testid":"auth-shell","data-auth-page":a,"data-auth-storage-key":q,"data-pricing-checkout-intent-key":K,"data-production-adapter-state":c.overallState,"data-auth-provider-mode":c.auth.mode,"data-auth-provider-ready":c.auth.canAttempt?"true":"false","data-client-secret-blocked":c.forbiddenClientSecretKeys.length>0?"true":"false",children:[e.jsx("div",{className:"auth-scrim"}),e.jsx("section",{className:"auth-card",children:o})]})}export{le as ForgotPasswordPage,ue as LoginPage,de as ResetPasswordPage};
|