From 5bbb0574fa064b7a61274035e3f8aa7e9e43387a Mon Sep 17 00:00:00 2001 From: Harsh Date: Thu, 12 Nov 2026 16:19:07 -0800 Subject: [PATCH 1/3] Workspace UI: paginate session directory and preserve composer drafts Fetch all session pages (bounded, stale-guarded) for the conversation recipient/filter dropdowns and channel author names, disambiguating duplicate display names while keeping offline labels. Stale directory pages arriving after a workspace switch are discarded. Keep unsent conversation and channel/thread drafts in memory, scoped to account, workspace and destination. Drafts survive tab navigation and refreshes, retain their idempotency key across failed sends, and clear only after a confirmed send. Sign-out forgets that account's drafts. Fixes #183, Fixes #185. --- bus/hostedweb/app.js | 38 ++++---- web/src/app.js | 80 +++++++++++++---- web/tests/workspace.spec.js | 168 ++++++++++++++++++++++++++++++++++++ 3 files changed, 255 insertions(+), 31 deletions(-) diff --git a/bus/hostedweb/app.js b/bus/hostedweb/app.js index ee96353..91ed840 100644 --- a/bus/hostedweb/app.js +++ b/bus/hostedweb/app.js @@ -1,22 +1,28 @@ -function ue(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s{let n=new Array(128);for(let e=0;e=6;){let r=e.queue>>e.queuedBits-6&63;t(Ke[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let r=e.queue>>e.queuedBits-6&63;t(Ke[r]),e.queuedBits-=6}}function Wt(n,e,t){let r=Er[n];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function at(n){let e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{Tr(o,r,t)};for(let o=0;o>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function Ir(n,e){for(let t=0;t55295&&r<=56319){let s=(r-55296)*1024&65535;r=(n.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}Ar(r,e)}}function Tr(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let r=1;r<6;r+=1)if((n>>7-r&1)===0){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function ae(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;se.push(t)),new Uint8Array(e)}function ne(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};return n.forEach(s=>Ft(s,t,r)),Ft(null,t,r),e.join("")}function Fe(n){return Math.round(Date.now()/1e3)+n}function Gt(){return Symbol("auth-callback")}var L=()=>typeof window<"u"&&typeof document<"u",pe={tested:!1,writable:!1},We=()=>{if(!L())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(pe.tested)return pe.writable;let n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),pe.tested=!0,pe.writable=!0}catch{pe.tested=!0,pe.writable=!1}return pe.writable};function lt(n){let e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}var Be=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),Vt=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",Q=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},M=async(n,e)=>{let t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}},W=async(n,e)=>{await n.removeItem(e)},Oe=class n{constructor(){this.promise=new n.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Oe.promiseConstructor=Promise;function Ue(n){let e=n.split(".");if(e.length!==3)throw new oe("Invalid JWT structure");for(let r=0;r{setTimeout(()=>e(null),n)})}function Jt(n,e){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await n(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function Ht(n){return("0"+n.toString(16)).substr(-2)}function xr(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,Ht).join("")}async function Cr(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function Or(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),n;let t=await Cr(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Pr=/^[a-zA-Z0-9_-]{8,64}$/;function je(n){return typeof n=="string"&&Pr.test(n)?n:null}function Ur(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,Ht).join("")}let n="";for(let e=0;e<32;e++)n+=Math.floor(Math.random()*16).toString(16);return n}var we=(n,e)=>`${n}-flow-${e}-code-verifier`,Pe=n=>`${n}-flows-code-verifier`;async function ct(n,e){let t=await M(n,Pe(e));return Array.isArray(t)?t.filter(r=>je(r)!==null):[]}async function jr(n,e,t,r,s){await Q(n,we(e,t),r);let i=(await ct(n,e)).filter(o=>o!==t);for(i.push(t);i.length>Lt;){let o=i.shift();await W(n,we(e,o)),s?.(o)}await Q(n,Pe(e),i),await Q(n,`${e}-code-verifier`,r)}async function Yt(n,e,t){if(t){let s=await M(n,we(e,t));return{verifier:typeof s=="string"?s:null,flowId:t}}let r=await M(n,`${e}-code-verifier`);return{verifier:typeof r=="string"?r:null,flowId:null}}async function J(n,e,t){let r=`${e}-code-verifier`;if(!t){await W(n,r);return}let s=we(e,t),i=await M(n,s);await W(n,s);let o=await ct(n,e),l=o.filter(c=>c!==t);l.length!==o.length&&(l.length>0?await Q(n,Pe(e),l):await W(n,Pe(e))),i!=null&&i===await M(n,r)&&await W(n,r)}async function Xt(n,e){let t=await ct(n,e);for(let r of t)await W(n,we(e,r));await W(n,Pe(e)),await W(n,`${e}-code-verifier`)}function Qt(n,e){let t=n.indexOf("#"),r=t===-1?n:n.slice(0,t),s=t===-1?"":n.slice(t),i=r.indexOf("?");if(i!==-1){let l=r.slice(0,i),c=r.slice(i+1).split("&").filter(u=>u!==""&&u!==re&&!u.startsWith(`${re}=`));r=c.length>0?`${l}?${c.join("&")}`:l}let o=r.includes("?")?"&":"?";return`${r}${o}${re}=${encodeURIComponent(e)}${s}`}async function Zt(n,e,t=!1,r){let s=xr(),i=s;t&&(i+="/recovery");let o=Ur();await jr(n,e,o,i,r);let l=await Or(s);return[l,s===l?"plain":"s256",o]}var $r=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function er(n){let e=n.headers.get(Ee);if(!e||!e.match($r))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function tr(n){if(!n)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function rr(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Dr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Z(n){if(!Dr.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ke(n){if(!n.recoveryCodes)throw new Error("@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).")}function Ge(){let n={};return new Proxy(n,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){let r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function sr(n,e){return new Proxy(n,{get:(t,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){let i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,s)}return!e.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(t,r,s)}})}function ut(n){return JSON.parse(JSON.stringify(n))}var ge=n=>{if(typeof n=="object"&&n!==null){let e=n;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(n)},nr=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function ir(n){var e;if(!Vt(n))throw new fe(ge(n),0);let t;try{t=await n.json()}catch(i){throw nr.includes(n.status)?new fe(n.statusText||`HTTP ${n.status}`,n.status):new K(ge(i),i)}if(nr.includes(n.status))throw new fe(ge(t),n.status);let r,s=er(n);if(s&&s.getTime()>=nt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Te(ge(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new j}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Te(ge(t),n.status,t.weak_password.reasons);throw new qe(ge(t),n.status||500,r)}var Nr=(n,e,t,r)=>{let s={method:n,headers:e?.headers||{}};return n==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function y(n,e,t,r){var s;let i=Object.assign({},r?.headers);i[Ee]||(i[Ee]=nt["2024-01-01"].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);let o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Lr(n,e,t+l,{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function Lr(n,e,t,r,s,i){let o=Nr(e,r,s,i),l;try{l=await n(t,Object.assign({},o))}catch(c){throw new fe(ge(c),0)}if(l.ok||await ir(l),r?.noResolveJson)return l;try{return await l.json()}catch(c){await ir(c)}}function V(n){var e;let t=null;qr(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=Fe(n.expires_in)));let r=(e=n.user)!==null&&e!==void 0?e:typeof n?.id=="string"?n:null;return{data:{session:t,user:r},error:null}}function dt(n){let e=V(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=n.weak_password),e}function ee(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function or(n){return{data:n,error:null}}function ar(n){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i}=n,o=ue(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i},c=Object.assign({},o);return{data:{properties:l,user:c},error:null}}function ht(n){return n}function qr(n){return!!n.access_token&&!!n.refresh_token&&!!n.expires_in}var Ve=["global","local","others"];var ye=class{constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=Be(r),this.experimental=s??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=Ve[0]){if(Ve.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ve.join(", ")}`);try{return await y(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(w(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await y(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ee})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=ue(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await y(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:ar,redirectTo:t?.redirectTo})}catch(t){if(w(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await y(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ee})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await y(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:ht});if(h.error)throw h.error;let f=await h.json(),g=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(k=>{let E=parseInt(k.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(k.split(";")[1].split("=")[1]);u[`${A}Page`]=E}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(w(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Z(e);try{return await y(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ee})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Z(e);try{return await y(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ee})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){Z(e);try{return await y(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ee})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){Z(e.userId);try{let{data:t,error:r}=await y(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Z(e.userId),Z(e.id);try{return{data:await y(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await y(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:ht});if(h.error)throw h.error;let f=await h.json(),g=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(k=>{let E=parseInt(k.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(k.split(";")[1].split("=")[1]);u[`${A}Page`]=E}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(w(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await y(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await y(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await y(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await y(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await y(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await y(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:r=>{var s;return{data:{providers:(s=r?.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(t){if(w(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await y(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await y(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await y(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await y(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminListPasskeys(e){Z(e.userId);try{return await y(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminDeletePasskey(e){Z(e.userId),Z(e.passkeyId);try{return await y(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}};function ft(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}var Mr={debug:!!(globalThis&&We()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ze=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};function lr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function pt(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))throw new Error(`@supabase/auth-js: Address "${n}" is invalid.`);return n.toLowerCase()}function cr(n){return parseInt(n,16)}function ur(n){let e=new TextEncoder().encode(n);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function dr(n){var e;let{chainId:t,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:l,requestId:c,resources:u,scheme:h,uri:f,version:g}=n;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(g!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${g}`);if(!((e=n.statement)===null||e===void 0)&&e.includes(` -`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${n.statement}`)}let p=pt(n.address),k=h?`${h}://${r}`:r,E=n.statement?`${n.statement} -`:"",A=`${k} wants you to sign in with your Ethereum account: +function he(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s{let n=new Array(128);for(let e=0;e=6;){let r=e.queue>>e.queuedBits-6&63;t(Ge[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let r=e.queue>>e.queuedBits-6&63;t(Ge[r]),e.queuedBits-=6}}function Ht(n,e,t){let r=Ur[n];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function ft(n){let e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{Dr(o,r,t)};for(let o=0;o>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function $r(n,e){for(let t=0;t55295&&r<=56319){let s=(r-55296)*1024&65535;r=(n.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}jr(r,e)}}function Dr(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let r=1;r<6;r+=1)if((n>>7-r&1)===0){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function ce(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;se.push(t)),new Uint8Array(e)}function oe(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};return n.forEach(s=>Jt(s,t,r)),Jt(null,t,r),e.join("")}function Ve(n){return Math.round(Date.now()/1e3)+n}function Xt(){return Symbol("auth-callback")}var q=()=>typeof window<"u"&&typeof document<"u",ge={tested:!1,writable:!1},ze=()=>{if(!q())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ge.tested)return ge.writable;let n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),ge.tested=!0,ge.writable=!0}catch{ge.tested=!0,ge.writable=!1}return ge.writable};function pt(n){let e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}var Je=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),Qt=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",ee=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},K=async(n,e)=>{let t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}},G=async(n,e)=>{await n.removeItem(e)},je=class n{constructor(){this.promise=new n.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};je.promiseConstructor=Promise;function De(n){let e=n.split(".");if(e.length!==3)throw new le("Invalid JWT structure");for(let r=0;r{setTimeout(()=>e(null),n)})}function er(n,e){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await n(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function tr(n){return("0"+n.toString(16)).substr(-2)}function Nr(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,tr).join("")}async function Lr(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function qr(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),n;let t=await Lr(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Mr=/^[a-zA-Z0-9_-]{8,64}$/;function Ne(n){return typeof n=="string"&&Mr.test(n)?n:null}function Kr(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,tr).join("")}let n="";for(let e=0;e<32;e++)n+=Math.floor(Math.random()*16).toString(16);return n}var ye=(n,e)=>`${n}-flow-${e}-code-verifier`,$e=n=>`${n}-flows-code-verifier`;async function wt(n,e){let t=await K(n,$e(e));return Array.isArray(t)?t.filter(r=>Ne(r)!==null):[]}async function Fr(n,e,t,r,s){await ee(n,ye(e,t),r);let i=(await wt(n,e)).filter(o=>o!==t);for(i.push(t);i.length>Bt;){let o=i.shift();await G(n,ye(e,o)),s?.(o)}await ee(n,$e(e),i),await ee(n,`${e}-code-verifier`,r)}async function rr(n,e,t){if(t){let s=await K(n,ye(e,t));return{verifier:typeof s=="string"?s:null,flowId:t}}let r=await K(n,`${e}-code-verifier`);return{verifier:typeof r=="string"?r:null,flowId:null}}async function H(n,e,t){let r=`${e}-code-verifier`;if(!t){await G(n,r);return}let s=ye(e,t),i=await K(n,s);await G(n,s);let o=await wt(n,e),l=o.filter(c=>c!==t);l.length!==o.length&&(l.length>0?await ee(n,$e(e),l):await G(n,$e(e))),i!=null&&i===await K(n,r)&&await G(n,r)}async function sr(n,e){let t=await wt(n,e);for(let r of t)await G(n,ye(e,r));await G(n,$e(e)),await G(n,`${e}-code-verifier`)}function nr(n,e){let t=n.indexOf("#"),r=t===-1?n:n.slice(0,t),s=t===-1?"":n.slice(t),i=r.indexOf("?");if(i!==-1){let l=r.slice(0,i),c=r.slice(i+1).split("&").filter(u=>u!==""&&u!==ne&&!u.startsWith(`${ne}=`));r=c.length>0?`${l}?${c.join("&")}`:l}let o=r.includes("?")?"&":"?";return`${r}${o}${ne}=${encodeURIComponent(e)}${s}`}async function ir(n,e,t=!1,r){let s=Nr(),i=s;t&&(i+="/recovery");let o=Kr();await Fr(n,e,o,i,r);let l=await qr(s);return[l,s===l?"plain":"s256",o]}var Wr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function or(n){let e=n.headers.get(Te);if(!e||!e.match(Wr))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function ar(n){if(!n)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function lr(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Br=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function te(n){if(!Br.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Re(n){if(!n.recoveryCodes)throw new Error("@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).")}function He(){let n={};return new Proxy(n,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){let r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function cr(n,e){return new Proxy(n,{get:(t,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){let i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,s)}return!e.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(t,r,s)}})}function gt(n){return JSON.parse(JSON.stringify(n))}var me=n=>{if(typeof n=="object"&&n!==null){let e=n;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(n)},ur=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function dr(n){var e;if(!Qt(n))throw new we(me(n),0);let t;try{t=await n.json()}catch(i){throw ur.includes(n.status)?new we(n.statusText||`HTTP ${n.status}`,n.status):new F(me(i),i)}if(ur.includes(n.status))throw new we(me(t),n.status);let r,s=or(n);if(s&&s.getTime()>=ut["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Oe(me(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new j}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Oe(me(t),n.status,t.weak_password.reasons);throw new We(me(t),n.status||500,r)}var Gr=(n,e,t,r)=>{let s={method:n,headers:e?.headers||{}};return n==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function g(n,e,t,r){var s;let i=Object.assign({},r?.headers);i[Te]||(i[Te]=ut["2024-01-01"].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);let o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Vr(n,e,t+l,{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function Vr(n,e,t,r,s,i){let o=Gr(e,r,s,i),l;try{l=await n(t,Object.assign({},o))}catch(c){throw new we(me(c),0)}if(l.ok||await dr(l),r?.noResolveJson)return l;try{return await l.json()}catch(c){await dr(c)}}function z(n){var e;let t=null;zr(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=Ve(n.expires_in)));let r=(e=n.user)!==null&&e!==void 0?e:typeof n?.id=="string"?n:null;return{data:{session:t,user:r},error:null}}function yt(n){let e=z(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=n.weak_password),e}function re(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function hr(n){return{data:n,error:null}}function fr(n){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i}=n,o=he(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i},c=Object.assign({},o);return{data:{properties:l,user:c},error:null}}function mt(n){return n}function zr(n){return!!n.access_token&&!!n.refresh_token&&!!n.expires_in}var Ye=["global","local","others"];var _e=class{constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=Je(r),this.experimental=s??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=Ye[0]){if(Ye.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ye.join(", ")}`);try{return await g(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(w(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await g(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:re})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=he(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await g(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:fr,redirectTo:t?.redirectTo})}catch(t){if(w(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await g(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:re})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await g(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:mt});if(h.error)throw h.error;let f=await h.json(),y=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(S=>{let E=parseInt(S.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(S.split(";")[1].split("=")[1]);u[`${A}Page`]=E}),u.total=parseInt(y)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(w(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){te(e);try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:re})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){te(e);try{return await g(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:re})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){te(e);try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:re})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){te(e.userId);try{let{data:t,error:r}=await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _deleteFactor(e){te(e.userId),te(e.id);try{return{data:await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await g(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:mt});if(h.error)throw h.error;let f=await h.json(),y=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(S=>{let E=parseInt(S.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(S.split(";")[1].split("=")[1]);u[`${A}Page`]=E}),u.total=parseInt(y)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(w(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await g(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await g(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await g(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await g(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await g(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:r=>{var s;return{data:{providers:(s=r?.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(t){if(w(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await g(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await g(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await g(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminListPasskeys(e){te(e.userId);try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminDeletePasskey(e){te(e.userId),te(e.passkeyId);try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}};function _t(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}var Jr={debug:!!(globalThis&&ze()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Xe=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};function pr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function vt(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))throw new Error(`@supabase/auth-js: Address "${n}" is invalid.`);return n.toLowerCase()}function wr(n){return parseInt(n,16)}function gr(n){let e=new TextEncoder().encode(n);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function yr(n){var e;let{chainId:t,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:l,requestId:c,resources:u,scheme:h,uri:f,version:y}=n;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(y!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${y}`);if(!((e=n.statement)===null||e===void 0)&&e.includes(` +`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${n.statement}`)}let p=vt(n.address),S=h?`${h}://${r}`:r,E=n.statement?`${n.statement} +`:"",A=`${S} wants you to sign in with your Ethereum account: ${p} -${E}`,O=`URI: ${f} -Version: ${g} +${E}`,x=`URI: ${f} +Version: ${y} Chain ID: ${t}${o?` Nonce: ${o}`:""} -Issued At: ${i.toISOString()}`;if(s&&(O+=` -Expiration Time: ${s.toISOString()}`),l&&(O+=` -Not Before: ${l.toISOString()}`),c&&(O+=` +Issued At: ${i.toISOString()}`;if(s&&(x+=` +Expiration Time: ${s.toISOString()}`),l&&(x+=` +Not Before: ${l.toISOString()}`),c&&(x+=` Request ID: ${c}`),u){let R=` -Resources:`;for(let v of u){if(!v||typeof v!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${v}`);R+=` -- ${v}`}O+=R}return`${A} -${O}`}var U=class extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},me=class extends U{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function hr({error:n,options:e}){var t,r,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new U({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new U({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new U({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new U({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new U({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new U({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){let o=window.location.hostname;if(wt(o)){if(i.rp.id!==o)return new U({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new U({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function fr({error:n,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){let r=window.location.hostname;if(wt(r)){if(t.rpId!==r)return new U({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}var gt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},Ye=new gt;function yt(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);let{challenge:e,user:t,excludeCredentials:r}=n,s=ue(n,["challenge","user","excludeCredentials"]),i=ae(e).buffer,o=Object.assign(Object.assign({},t),{id:ae(t.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c0){i.allowCredentials=new Array(t.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of n)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){let l=r[i];e(l)?r[i]=Je(l,o):r[i]=Je(o)}else r[i]=o}return r}function Wr(n,e){return Je(Kr,n,e||{})}function Br(n,e){return Je(Fr,n,e||{})}var He=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var o;try{let{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!l)return{data:null,error:c};let u=s??Ye.createNewAbortSignal();if(l.webauthn.type==="create"){let{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){let f=r;if(f)h.name=`${h.id}:${f}`;else{let p=(await this.client.getUser()).data.user,k=((o=p?.user_metadata)===null||o===void 0?void 0:o.name)||p?.email||p?.id||"User";h.name=`${h.id}:${k}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{let h=Wr(l.webauthn.credential_options.publicKey,i?.create),{data:f,error:g}=await bt({publicKey:h,signal:u});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}case"request":{let h=Br(l.webauthn.credential_options.publicKey,i?.request),{data:f,error:g}=await kt(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}}}catch(l){return w(l)?{data:null,error:l}:{data:null,error:new K("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ie("rpId is required for WebAuthn authentication")};try{if(!$e())return{data:null,error:new K("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:l};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new K("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ie("rpId is required for WebAuthn registration")};try{if(!$e())return{data:null,error:new K("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var f;return(f=h.data)===null||f===void 0?void 0:f.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status==="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:l};let{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new K("Unexpected error in register",o)}}}};lr();var Gr={url:jt,storageKey:$t,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Dt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Se={},pr=!1,Xe=class n{get jwks(){var e,t;return(t=(e=Se[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Se[this.storageKey]=Object.assign(Object.assign({},Se[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Se[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Se[this.storageKey]=Object.assign(Object.assign({},Se[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Gr),e);if(this.storageKey=i.storageKey,this.instanceID=(t=n.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,n.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&L()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new ye({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Be(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,pr||(pr=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),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 He(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(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:We()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=ft(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=ft(this.memoryStorage)),L()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ne}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(L()&&(t=lt(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),L()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Mt(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new K("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let i=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:V}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;let i=null;try{let o;if("email"in e){let{email:f,password:g,options:p}=e,k=null,E=null;this.flowType==="pkce"&&([k,E,i]=await this._getCodeChallengeAndMethod()),o=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(p?.emailRedirectTo,i),body:{email:f,password:g,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:k,code_challenge_method:E},xform:V})}else if("phone"in e){let{phone:f,password:g,options:p}=e;o=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:g,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(s=p?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:V})}else throw new de("You must provide either an email or phone number and a password");let{data:l,error:c}=o;if(c||!l)return await J(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let u=l.session,h=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:h,session:u},error:null})}catch(o){if(await J(this.storage,this.storageKey,i),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:l}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:dt})}else if("phone"in e){let{phone:i,password:o,options:l}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:dt})}else throw new de("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let i=new se;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,l,c,u,h,f,g;let p,k;if("message"in e)p=e.message,k=e.signature;else{let{chain:E,wallet:A,statement:O,options:R}=e,v;if(L())if(typeof A=="object")v=A;else{let x=window;if("ethereum"in x&&typeof x.ethereum=="object"&&"request"in x.ethereum&&typeof x.ethereum.request=="function")v=x.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 A!="object"||!R?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=A}let P=new URL((t=R?.url)!==null&&t!==void 0?t:window.location.href),S=await v.request({method:"eth_requestAccounts"}).then(x=>x).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!S||S.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let m=pt(S[0]),I=(r=R?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!I){let x=await v.request({method:"eth_chainId"});I=cr(x)}let T={domain:P.host,address:m,statement:O,uri:P.href,version:"1",chainId:I,nonce:(s=R?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=R?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=R?.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=R?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=R?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=R?.signInWithEthereum)===null||h===void 0?void 0:h.resources};p=dr(T),k=await v.request({method:"personal_sign",params:[ur(p),m]})}try{let{data:E,error:A}=await y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:k},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:V});if(A)throw A;if(!E||!E.session||!E.user){let O=new se;return this._returnResult({data:{user:null,session:null},error:O})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:A})}catch(E){if(w(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var t,r,s,i,o,l,c,u,h,f,g,p;let k,E;if("message"in e)k=e.message,E=e.signature;else{let{chain:A,wallet:O,statement:R,options:v}=e,P;if(L())if(typeof O=="object")P=O;else{let m=window;if("solana"in m&&typeof m.solana=="object"&&("signIn"in m.solana&&typeof m.solana.signIn=="function"||"signMessage"in m.solana&&typeof m.solana.signMessage=="function"))P=m.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 O!="object"||!v?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");P=O}let S=new URL((t=v?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in P&&P.signIn){let m=await P.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v?.signInWithSolana),{version:"1",domain:S.host,uri:S.href}),R?{statement:R}:null)),I;if(Array.isArray(m)&&m[0]&&typeof m[0]=="object")I=m[0];else if(m&&typeof m=="object"&&"signedMessage"in m&&"signature"in m)I=m;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in I&&"signature"in I&&(typeof I.signedMessage=="string"||I.signedMessage instanceof Uint8Array)&&I.signature instanceof Uint8Array)k=typeof I.signedMessage=="string"?I.signedMessage:new TextDecoder().decode(I.signedMessage),E=I.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in P)||typeof P.signMessage!="function"||!("publicKey"in P)||typeof P!="object"||!P.publicKey||!("toBase58"in P.publicKey)||typeof P.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");k=[`${S.host} wants you to sign in with your Solana account:`,P.publicKey.toBase58(),...R?["",R,""]:[""],"Version: 1",`URI: ${S.href}`,`Issued At: ${(s=(r=v?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=v?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${v.signInWithSolana.notBefore}`]:[],...!((o=v?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${v.signInWithSolana.expirationTime}`]:[],...!((l=v?.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${v.signInWithSolana.chainId}`]:[],...!((c=v?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((u=v?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((f=(h=v?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||f===void 0)&&f.length?["Resources",...v.signInWithSolana.resources.map(I=>`- ${I}`)]:[]].join(` -`);let m=await P.signMessage(new TextEncoder().encode(k),"utf8");if(!m||!(m instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=m}}try{let{data:A,error:O}=await y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:k,signature:ne(E)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:V});if(O)throw O;if(!A||!A.session||!A.user){let R=new se;return this._returnResult({data:{user:null,session:null},error:R})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:O})}catch(A){if(w(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e,t){let r=t?.flowId!=null,s=r?je(t?.flowId):L()?je(lt(window.location.href)[re]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",t?.flowId);let{verifier:i,flowId:o}=r&&!s?{verifier:null,flowId:null}:await Yt(this.storage,this.storageKey,s),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new Me;let{data:u,error:h}=await y(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:l},xform:V});if(await J(this.storage,this.storageKey,o),h)throw h;if(!u||!u.session||!u.user){let f=new se;return this._returnResult({data:{user:null,session:null,redirectType:null},error:f})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:h})}catch(u){if(await J(this.storage,this.storageKey,o),w(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:o}=e,l=await y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:V}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){let h=new se;return this._returnResult({data:{user:null,session:null},error:h})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;let l=null;try{if("email"in e){let{email:c,options:u}=e,h=null,f=null;this.flowType==="pkce"&&([h,f,l]=await this._getCodeChallengeAndMethod());let{error:g}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(t=u?.data)!==null&&t!==void 0?t:{},create_user:(r=u?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:g})}if("phone"in e){let{phone:c,options:u}=e,{data:h,error:f}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(s=u?.data)!==null&&s!==void 0?s:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(o=u?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:f})}throw new de("You must provide either an email or phone number.")}catch(c){if(await J(this.storage,this.storageKey,l),w(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:l}=await y(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:V});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(s){if(w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());let u=await y(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((t=e.options)===null||t===void 0?void 0:t.redirectTo,o)}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:or});return!((s=u.data)===null||s===void 0)&&s.url&&L()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await J(this.storage,this.storageKey,o),w(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new j;let{error:s}=await y(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(w(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:o}=e,l=null,c=null;this.flowType==="pkce"&&([l,c,t]=await this._getCodeChallengeAndMethod());let{error:u}=await y(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t)});return u&&await J(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){let{phone:s,type:i,options:o}=e,{data:l,error:c}=await y(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:c})}throw new de("You must provide either an email or phone number and a type")}catch(r){if(await J(this.storage,this.storageKey,t),w(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,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await M(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let t=await M(this.userStorage,this.storageKey+"-user");e.user=t?.user?t.user:Ge()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=sr(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return this.lock!=null?t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):t=await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ee}):await this._useSession(async t=>{var r,s,i;let{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new j}:await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:ee})})}catch(t){if(w(t))return xe(t)&&await this._removeSession(),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new j;let l=i.session,c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());let{data:h,error:f}=await y(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:ee});if(f)throw f;return l.user=h.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(s){if(await J(this.storage,this.storageKey,r),w(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 j;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:o}=Ue(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{let{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}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 t=>{var r;if(!e){let{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new j;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!L())throw new he("No browser detected.");if(e.error||e.error_description||e.error_code)throw new he(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new Ae("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new he("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ae("No code detected.");let{data:v,error:P}=await this._exchangeCodeForSession(e.code,{flowId:e[re]});if(P)throw P;let S=new URL(window.location.href);return S.searchParams.delete("code"),S.searchParams.delete(re),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:v.session,redirectType:(r=v.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:h}=e;if(!o||!c||!l||!h)throw new he("No session defined in URL");let f=Math.round(Date.now()/1e3),g=parseInt(c),p=f+g;u&&(p=parseInt(u));let k=p-f;k*1e3<=X&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${k}s, should have been closer to ${g}s`);let E=p-g;f-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,p,f):f-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,p,f);let{data:A,error:O}=await this._getUser(o);if(O)throw O;let R={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:g,expires_at:p,refresh_token:l,token_type:h,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:R,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=je(e[re]);return t&&await M(this.storage,we(this.storageKey,t))?!0:!!await M(this.storage,`${this.storageKey}-code-verifier`)}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 t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:o}=t;if(o&&!xe(o))return this._returnResult({error:o});let l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){let{error:c}=await this.admin.signOut(l,e);if(c&&!(it(c)&&(c.status===404||c.status===401||c.status===403)||xe(c)))return e!=="others"&&await s(),this._returnResult({error:c})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=Gt(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),ot(i))return;xe(i)||Ce(i)||it(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;this.flowType==="pkce"&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await y(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(o){if(await J(this.storage,this.storageKey,i),w(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async o=>{var l,c,u,h,f;let{data:g,error:p}=o;if(p)throw p;let{url:k,flowId:E}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(l=e.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=E,await y(this.fetch,"GET",k,{headers:this.headers,jwt:(f=(h=g.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(i)throw i;return L()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:r},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:l,token:c,access_token:u,nonce:h}=e,f=await y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:V}),{data:g,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new se}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:p}))}catch(s){if(await J(this.storage,this.storageKey,null),w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)throw o;return await y(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{let r=Date.now();return await Jt(async s=>(s>0&&await zt(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await y(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:V})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Ce(i)&&Date.now()+o-r{});let i=await M(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(e);if(l)throw l;if(!o.session)throw new j;let c=await M(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let g={data:null,error:new Ie};return this.refreshingDeferred.resolve(g),g}let h=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await W(this.storage,this.storageKey),this.userStorage&&await W(this.userStorage,this.storageKey+"-user");let g={data:null,error:new Ie};return this.refreshingDeferred.resolve(g),g}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let f={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(f),f}catch(i){if(this._debug(s,"error",i),w(i)){let o={data:null,error:i};if(!Ce(i)){let l=await M(this.storage,this.storageKey);!!(l?.expires_at&&l.expires_at*1e3>Date.now())?this._debug(s,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+Ut},(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:e,session:t,broadcast:r});return}let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;lthis._autoRefreshTokenTick(),X);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/X);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${X}ms, refresh threshold is ${be} ticks`),s<=be&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof ze)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/X);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${X}ms, refresh threshold is ${be} ticks`),s<=be&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!L()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"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(t,"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(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=r?.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,l));let c=[`provider=${encodeURIComponent(t)}`];if(s&&c.push(`redirect_to=${encodeURIComponent(s)}`),r?.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){let u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r?.queryParams){let u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r?.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:Qt(e,t)}async _getCodeChallengeAndMethod(e=!1){return Zt(this.storage,this.storageKey,e,t=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",t))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await y(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await y(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?_t(e.webauthn.credential_response):vt(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;let{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:yt(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:mt(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&i.factor_type in s&&Array.isArray(s[i.factor_type])&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:p}=Ue(e),k=null;p.aal&&(k=p.aal);let E=k,{data:{user:A},error:O}=await this.getUser(e);if(O)return this._returnResult({data:null,error:O});((r=(t=A?.factors)===null||t===void 0?void 0:t.filter(P=>P.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(E="aal2");let v=p.amr||[];return{data:{currentLevel:k,nextLevel:E,currentAuthenticationMethods:v},error:null}}catch(p){if(w(p))return this._returnResult({data:null,error:p});throw p}let{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ue(o.access_token),u=null;c.aal&&(u=c.aal);let h=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let g=c.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:g},error:null}}async _getRecoveryCodesStatus(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){ke(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:o,error:l}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):this._returnResult({data:o,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verifyRecoveryCode(e){ke(this.experimental);let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let{data:l,error:c}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(c)return this._returnResult({data:null,error:c});let u=Object.assign({expires_at:Fe(l.expires_in)},l);return await this._saveSession(u),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:l,error:null})})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await y(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await y(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&L()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await y(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&L()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await y(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new j})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await y(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+qt>s)return r;let{data:i,error:o}=await y(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:p,error:k}=await this.getSession();if(k||!p.session)return this._returnResult({data:null,error:k});r=p.session.access_token}let{header:s,payload:i,signature:o,raw:{header:l,payload:c}}=Ue(r);if(!t?.allowExpired)try{tr(i.exp)}catch(p){throw new oe(p instanceof Error?p.message:"JWT validation failed")}let u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){let{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:s,signature:o},error:null}}let h=rr(s.alg),f=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,f,o,Bt(`${l}.${c}`)))throw new oe("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var t,r,s,i;try{if(!$e())return this._returnResult({data:null,error:new K("Browser does not support WebAuthn",null)});let{data:o,error:l}=await this._startPasskeyAuthentication({options:{captchaToken:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}});if(l||!o)return this._returnResult({data:null,error:l});let c=mt(o.options),u=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:Ye.createNewAbortSignal(),{data:h,error:f}=await kt({publicKey:c,signal:u,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(f||!h)return this._returnResult({data:null,error:f??new K("WebAuthn ceremony failed",null)});let g=vt(h);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:g})}catch(o){if(w(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var t,r;try{if(!$e())return this._returnResult({data:null,error:new K("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let o=yt(s.options),l=(r=(t=e?.options)===null||t===void 0?void 0:t.signal)!==null&&r!==void 0?r:Ye.createNewAbortSignal(),{data:c,error:u}=await bt({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new K("WebAuthn ceremony failed",null)});let h=_t(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await y(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await y(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;try{let{data:r,error:s}=await y(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:r}=await y(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:V});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await y(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await y(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{error:i}=await y(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}};Xe.nextInstanceID={};var St=Xe;var Vr=St,Rt=Vr;var le=document.querySelector("#app"),De=document.querySelector("#notice"),d={auth:null,config:null,user:null,workspaces:[],workspace:null,tab:"sessions",generation:0,conversationAgent:"",search:"",channelId:"",threadId:"",channelSearch:""},wr,Ze=[];function mr(){for(let n of Ze.splice(0))n()}var _e=new URLSearchParams(location.search);_e.has("billing")&&(d.tab="billing");var xt="agentintercom-pending",$={};try{let n=JSON.parse(sessionStorage.getItem(xt)||"{}");n.until>Date.now()&&($=n)}catch{}_e.get("authorization_id")&&($.authorization=_e.get("authorization_id"));var _r=new URLSearchParams(location.hash.slice(1)),gr=_r.get("invite"),yr=_r.get("device")||_e.get("device_code");yr&&($.device=yr,history.replaceState(null,"",location.pathname+location.search));gr&&($.invite=gr,history.replaceState(null,"",location.pathname+location.search));($.authorization||$.invite||$.device)&&sessionStorage.setItem(xt,JSON.stringify({...$,until:Date.now()+1200*1e3}));function a(n,e={},...t){let r=document.createElement(n);for(let[s,i]of Object.entries(e))i==null||i===!1||(s.startsWith("on")?r.addEventListener(s.slice(2),i):s==="class"?r.className=i:s==="text"?r.textContent=i:r.setAttribute(s,i===!0?"":String(i)));for(let s of t.flat(1/0))s!=null&&r.append(s instanceof Node?s:document.createTextNode(String(s)));return r}function H(n,e=!1){clearTimeout(wr),De.textContent=n,De.hidden=!1,De.className=e?"error":"",De.setAttribute("role",e?"alert":"status"),wr=setTimeout(()=>{De.hidden=!0},e?15e3:6e3)}async function Re(n,e){if(!n?.disabled){n&&(n.disabled=!0);try{return await e()}catch(t){H(t.message||"Something went wrong. Please try again.",!0)}finally{n&&(n.disabled=!1)}}}function _(n,e,t=""){return a("button",{type:"button",class:t,onclick:r=>Re(r.currentTarget,e)},n)}function N(n,e={}){let t=a(e.multiline?"textarea":"input",{...e,multiline:null});return{input:t,node:a("label",{},n,t)}}function F(n,e,t){let r=a("button",{type:"submit",class:"primary"},e);return a("form",{onsubmit:s=>{s.preventDefault(),Re(r,()=>t(new FormData(s.currentTarget)))}},n,r)}var ce=()=>a("div",{class:"brand"},a("span",{class:"mark","aria-hidden":!0},"o"),"agent intercom"),B=n=>n?new Date(n).toLocaleString():"\u2014",D=n=>`/api/workspaces/${encodeURIComponent(d.workspace.id)}${n}`;async function b(n,e={}){let t={"Content-Type":"application/json"};if(d.auth&&n!=="/api/config"){let{data:i,error:o}=await d.auth.getSession();if(o)throw o;i.session&&(t.Authorization=`Bearer ${i.session.access_token}`)}let r=await fetch(n,{method:e.method||"GET",credentials:"omit",headers:t,body:e.body==null?void 0:JSON.stringify(e.body),signal:AbortSignal.timeout(e.timeout||15e3)}),s=await r.json();if(!r.ok||s.ok===!1||s.error)throw new Error(s.error?.message||"The request could not be completed. Please try again.");return s.result}async function rt(n){await navigator.clipboard.writeText(n),H("Copied to clipboard.")}var Et=new WeakMap;async function Ct(n,e={}){let{data:t,error:r}=await d.auth.getSession();if(r)throw r;if(!t.session)throw new Error("Sign in again to access workspace files.");let s=await fetch(n,{...e,credentials:"omit",redirect:"error",headers:{Authorization:`Bearer ${t.session.access_token}`,"Content-Type":"application/octet-stream"},signal:AbortSignal.timeout(3e4)});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(i.error?.message||"File transfer failed. Please try again.")}return s}async function vr(n,e){if(e.size>16*1024*1024)throw new Error("Files can be up to 16 MiB.");Et.has(e)||Et.set(e,crypto.randomUUID());let t=new URLSearchParams({name:e.name,mediaType:e.type.split(";")[0]||"application/octet-stream",idempotencyKey:Et.get(e)}),s=await(await Ct(n+"/attachments?"+t,{method:"POST",body:e})).json();if(!s.ok)throw new Error(s.error?.message||"Upload failed.");return s.result}async function br(n,e,t){let r=await Ct(n+"/attachments/"+encodeURIComponent(e)+"/content"),s=await r.arrayBuffer();if([...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(u=>u.toString(16).padStart(2,"0")).join("")!==r.headers.get("X-Content-SHA256"))throw new Error("File checksum did not match. The download was stopped.");let o=r.headers.get("Content-Disposition")||"";if(!t)try{t=decodeURIComponent(o.match(/filename\*=utf-8''([^;]+)/i)?.[1]||"")||o.match(/filename="([^"]+)"/)?.[1]||o.match(/filename=([^;]+)/)?.[1]}catch{}let l=URL.createObjectURL(new Blob([s],{type:"application/octet-stream"})),c=a("a",{href:l,download:(t||e).replace(/[\\/\x00-\x1f]/g,"_")});document.body.append(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}function kr(n,e){let t=N("Attach a file",{type:"file"}),r=_("Upload and attach",async()=>{let s=t.input.files[0];if(!s)throw new Error("Choose a file first.");let i=t.input.closest("form")?.querySelector('[type="submit"]');i&&(i.disabled=!0);try{let o=await vr(n,s);e.value+=`${e.value?` +Resources:`;for(let m of u){if(!m||typeof m!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${m}`);R+=` +- ${m}`}x+=R}return`${A} +${x}`}var U=class extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},ve=class extends U{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function mr({error:n,options:e}){var t,r,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new U({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new U({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new U({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new U({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new U({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new U({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){let o=window.location.hostname;if(bt(o)){if(i.rp.id!==o)return new U({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new U({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function _r({error:n,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){let r=window.location.hostname;if(bt(r)){if(t.rpId!==r)return new U({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}var kt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},et=new kt;function St(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);let{challenge:e,user:t,excludeCredentials:r}=n,s=he(n,["challenge","user","excludeCredentials"]),i=ce(e).buffer,o=Object.assign(Object.assign({},t),{id:ce(t.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c0){i.allowCredentials=new Array(t.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of n)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){let l=r[i];e(l)?r[i]=Qe(l,o):r[i]=Qe(o)}else r[i]=o}return r}function Xr(n,e){return Qe(Hr,n,e||{})}function Qr(n,e){return Qe(Yr,n,e||{})}var Ze=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var o;try{let{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!l)return{data:null,error:c};let u=s??et.createNewAbortSignal();if(l.webauthn.type==="create"){let{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){let f=r;if(f)h.name=`${h.id}:${f}`;else{let p=(await this.client.getUser()).data.user,S=((o=p?.user_metadata)===null||o===void 0?void 0:o.name)||p?.email||p?.id||"User";h.name=`${h.id}:${S}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{let h=Xr(l.webauthn.credential_options.publicKey,i?.create),{data:f,error:y}=await It({publicKey:h,signal:u});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:y}}case"request":{let h=Qr(l.webauthn.credential_options.publicKey,i?.request),{data:f,error:y}=await Tt(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:y}}}}catch(l){return w(l)?{data:null,error:l}:{data:null,error:new F("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ae("rpId is required for WebAuthn authentication")};try{if(!Le())return{data:null,error:new F("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:l};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new F("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ae("rpId is required for WebAuthn registration")};try{if(!Le())return{data:null,error:new F("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var f;return(f=h.data)===null||f===void 0?void 0:f.all.find(y=>y.factor_type==="webauthn"&&y.friendly_name===e&&y.status==="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:l};let{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new F("Unexpected error in register",o)}}}};pr();var Zr={url:Mt,storageKey:Kt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ft,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Ee={},vr=!1,tt=class n{get jwks(){var e,t;return(t=(e=Ee[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Ee[this.storageKey]=Object.assign(Object.assign({},Ee[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Ee[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ee[this.storageKey]=Object.assign(Object.assign({},Ee[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Zr),e);if(this.storageKey=i.storageKey,this.instanceID=(t=n.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,n.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&q()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new _e({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Je(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,vr||(vr=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),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 Ze(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(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:ze()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=_t(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=_t(this.memoryStorage)),q()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ke}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(q()&&(t=pt(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),q()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Vt(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new F("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let i=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:z}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;let i=null;try{let o;if("email"in e){let{email:f,password:y,options:p}=e,S=null,E=null;this.flowType==="pkce"&&([S,E,i]=await this._getCodeChallengeAndMethod()),o=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(p?.emailRedirectTo,i),body:{email:f,password:y,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:S,code_challenge_method:E},xform:z})}else if("phone"in e){let{phone:f,password:y,options:p}=e;o=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:y,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(s=p?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:z})}else throw new fe("You must provide either an email or phone number and a password");let{data:l,error:c}=o;if(c||!l)return await H(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let u=l.session,h=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:h,session:u},error:null})}catch(o){if(await H(this.storage,this.storageKey,i),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:l}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:yt})}else if("phone"in e){let{phone:i,password:o,options:l}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:yt})}else throw new fe("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let i=new ie;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,l,c,u,h,f,y;let p,S;if("message"in e)p=e.message,S=e.signature;else{let{chain:E,wallet:A,statement:x,options:R}=e,m;if(q())if(typeof A=="object")m=A;else{let b=window;if("ethereum"in b&&typeof b.ethereum=="object"&&"request"in b.ethereum&&typeof b.ethereum.request=="function")m=b.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 A!="object"||!R?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");m=A}let P=new URL((t=R?.url)!==null&&t!==void 0?t:window.location.href),M=await m.request({method:"eth_requestAccounts"}).then(b=>b).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!M||M.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let C=vt(M[0]),_=(r=R?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!_){let b=await m.request({method:"eth_chainId"});_=wr(b)}let N={domain:P.host,address:C,statement:x,uri:P.href,version:"1",chainId:_,nonce:(s=R?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=R?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=R?.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=R?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=R?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=R?.signInWithEthereum)===null||h===void 0?void 0:h.resources};p=yr(N),S=await m.request({method:"personal_sign",params:[gr(p),C]})}try{let{data:E,error:A}=await g(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:S},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(y=e.options)===null||y===void 0?void 0:y.captchaToken}}:null),xform:z});if(A)throw A;if(!E||!E.session||!E.user){let x=new ie;return this._returnResult({data:{user:null,session:null},error:x})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:A})}catch(E){if(w(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var t,r,s,i,o,l,c,u,h,f,y,p;let S,E;if("message"in e)S=e.message,E=e.signature;else{let{chain:A,wallet:x,statement:R,options:m}=e,P;if(q())if(typeof x=="object")P=x;else{let C=window;if("solana"in C&&typeof C.solana=="object"&&("signIn"in C.solana&&typeof C.solana.signIn=="function"||"signMessage"in C.solana&&typeof C.solana.signMessage=="function"))P=C.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 x!="object"||!m?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");P=x}let M=new URL((t=m?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in P&&P.signIn){let C=await P.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},m?.signInWithSolana),{version:"1",domain:M.host,uri:M.href}),R?{statement:R}:null)),_;if(Array.isArray(C)&&C[0]&&typeof C[0]=="object")_=C[0];else if(C&&typeof C=="object"&&"signedMessage"in C&&"signature"in C)_=C;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in _&&"signature"in _&&(typeof _.signedMessage=="string"||_.signedMessage instanceof Uint8Array)&&_.signature instanceof Uint8Array)S=typeof _.signedMessage=="string"?_.signedMessage:new TextDecoder().decode(_.signedMessage),E=_.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in P)||typeof P.signMessage!="function"||!("publicKey"in P)||typeof P!="object"||!P.publicKey||!("toBase58"in P.publicKey)||typeof P.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");S=[`${M.host} wants you to sign in with your Solana account:`,P.publicKey.toBase58(),...R?["",R,""]:[""],"Version: 1",`URI: ${M.href}`,`Issued At: ${(s=(r=m?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=m?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${m.signInWithSolana.notBefore}`]:[],...!((o=m?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${m.signInWithSolana.expirationTime}`]:[],...!((l=m?.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${m.signInWithSolana.chainId}`]:[],...!((c=m?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${m.signInWithSolana.nonce}`]:[],...!((u=m?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${m.signInWithSolana.requestId}`]:[],...!((f=(h=m?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||f===void 0)&&f.length?["Resources",...m.signInWithSolana.resources.map(_=>`- ${_}`)]:[]].join(` +`);let C=await P.signMessage(new TextEncoder().encode(S),"utf8");if(!C||!(C instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=C}}try{let{data:A,error:x}=await g(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:S,signature:oe(E)},!((y=e.options)===null||y===void 0)&&y.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:z});if(x)throw x;if(!A||!A.session||!A.user){let R=new ie;return this._returnResult({data:{user:null,session:null},error:R})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:x})}catch(A){if(w(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e,t){let r=t?.flowId!=null,s=r?Ne(t?.flowId):q()?Ne(pt(window.location.href)[ne]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",t?.flowId);let{verifier:i,flowId:o}=r&&!s?{verifier:null,flowId:null}:await rr(this.storage,this.storageKey,s),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new Be;let{data:u,error:h}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:l},xform:z});if(await H(this.storage,this.storageKey,o),h)throw h;if(!u||!u.session||!u.user){let f=new ie;return this._returnResult({data:{user:null,session:null,redirectType:null},error:f})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:h})}catch(u){if(await H(this.storage,this.storageKey,o),w(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:o}=e,l=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:z}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){let h=new ie;return this._returnResult({data:{user:null,session:null},error:h})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;let l=null;try{if("email"in e){let{email:c,options:u}=e,h=null,f=null;this.flowType==="pkce"&&([h,f,l]=await this._getCodeChallengeAndMethod());let{error:y}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(t=u?.data)!==null&&t!==void 0?t:{},create_user:(r=u?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:y})}if("phone"in e){let{phone:c,options:u}=e,{data:h,error:f}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(s=u?.data)!==null&&s!==void 0?s:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(o=u?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:f})}throw new fe("You must provide either an email or phone number.")}catch(c){if(await H(this.storage,this.storageKey,l),w(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:l}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:z});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(s){if(w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());let u=await g(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:this._maybeAppendFlowIdToRedirect((t=e.options)===null||t===void 0?void 0:t.redirectTo,o)}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:hr});return!((s=u.data)===null||s===void 0)&&s.url&&q()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await H(this.storage,this.storageKey,o),w(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new j;let{error:s}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(w(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:o}=e,l=null,c=null;this.flowType==="pkce"&&([l,c,t]=await this._getCodeChallengeAndMethod());let{error:u}=await g(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t)});return u&&await H(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){let{phone:s,type:i,options:o}=e,{data:l,error:c}=await g(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:c})}throw new fe("You must provide either an email or phone number and a type")}catch(r){if(await H(this.storage,this.storageKey,t),w(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,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await K(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let t=await K(this.userStorage,this.storageKey+"-user");e.user=t?.user?t.user:He()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=cr(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return this.lock!=null?t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):t=await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:re}):await this._useSession(async t=>{var r,s,i;let{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new j}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:re})})}catch(t){if(w(t))return Pe(t)&&await this._removeSession(),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new j;let l=i.session,c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());let{data:h,error:f}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:re});if(f)throw f;return l.user=h.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(s){if(await H(this.storage,this.storageKey,r),w(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 j;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:o}=De(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{let{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}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 t=>{var r;if(!e){let{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new j;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!q())throw new pe("No browser detected.");if(e.error||e.error_description||e.error_code)throw new pe(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new xe("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new pe("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new xe("No code detected.");let{data:m,error:P}=await this._exchangeCodeForSession(e.code,{flowId:e[ne]});if(P)throw P;let M=new URL(window.location.href);return M.searchParams.delete("code"),M.searchParams.delete(ne),window.history.replaceState(window.history.state,"",M.toString()),{data:{session:m.session,redirectType:(r=m.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:h}=e;if(!o||!c||!l||!h)throw new pe("No session defined in URL");let f=Math.round(Date.now()/1e3),y=parseInt(c),p=f+y;u&&(p=parseInt(u));let S=p-f;S*1e3<=Z&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${S}s, should have been closer to ${y}s`);let E=p-y;f-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,p,f):f-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,p,f);let{data:A,error:x}=await this._getUser(o);if(x)throw x;let R={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:y,expires_at:p,refresh_token:l,token_type:h,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:R,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=Ne(e[ne]);return t&&await K(this.storage,ye(this.storageKey,t))?!0:!!await K(this.storage,`${this.storageKey}-code-verifier`)}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 t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:o}=t;if(o&&!Pe(o))return this._returnResult({error:o});let l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){let{error:c}=await this.admin.signOut(l,e);if(c&&!(dt(c)&&(c.status===404||c.status===401||c.status===403)||Pe(c)))return e!=="others"&&await s(),this._returnResult({error:c})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=Xt(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),ht(i))return;Pe(i)||Ue(i)||dt(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;this.flowType==="pkce"&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(o){if(await H(this.storage,this.storageKey,i),w(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async o=>{var l,c,u,h,f;let{data:y,error:p}=o;if(p)throw p;let{url:S,flowId:E}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(l=e.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=E,await g(this.fetch,"GET",S,{headers:this.headers,jwt:(f=(h=y.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(i)throw i;return q()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:r},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:l,token:c,access_token:u,nonce:h}=e,f=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:z}),{data:y,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!y||!y.session||!y.user?this._returnResult({data:{user:null,session:null},error:new ie}):(y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("USER_UPDATED",y.session)),this._returnResult({data:y,error:p}))}catch(s){if(await H(this.storage,this.storageKey,null),w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)throw o;return await g(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{let r=Date.now();return await er(async s=>(s>0&&await Zt(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:z})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Ue(i)&&Date.now()+o-r{});let i=await K(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(e);if(l)throw l;if(!o.session)throw new j;let c=await K(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let y={data:null,error:new Ce};return this.refreshingDeferred.resolve(y),y}let h=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await G(this.storage,this.storageKey),this.userStorage&&await G(this.userStorage,this.storageKey+"-user");let y={data:null,error:new Ce};return this.refreshingDeferred.resolve(y),y}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let f={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(f),f}catch(i){if(this._debug(s,"error",i),w(i)){let o={data:null,error:i};if(!Ue(i)){let l=await K(this.storage,this.storageKey);!!(l?.expires_at&&l.expires_at*1e3>Date.now())?this._debug(s,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+qt},(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:e,session:t,broadcast:r});return}let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;lthis._autoRefreshTokenTick(),Z);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/Z);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Z}ms, refresh threshold is ${Se} ticks`),s<=Se&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof Xe)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/Z);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Z}ms, refresh threshold is ${Se} ticks`),s<=Se&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!q()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"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(t,"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(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=r?.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,l));let c=[`provider=${encodeURIComponent(t)}`];if(s&&c.push(`redirect_to=${encodeURIComponent(s)}`),r?.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){let u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r?.queryParams){let u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r?.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:nr(e,t)}async _getCodeChallengeAndMethod(e=!1){return ir(this.storage,this.storageKey,e,t=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",t))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await g(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Et(e.webauthn.credential_response):At(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;let{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:St(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:Rt(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&i.factor_type in s&&Array.isArray(s[i.factor_type])&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:p}=De(e),S=null;p.aal&&(S=p.aal);let E=S,{data:{user:A},error:x}=await this.getUser(e);if(x)return this._returnResult({data:null,error:x});((r=(t=A?.factors)===null||t===void 0?void 0:t.filter(P=>P.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(E="aal2");let m=p.amr||[];return{data:{currentLevel:S,nextLevel:E,currentAuthenticationMethods:m},error:null}}catch(p){if(w(p))return this._returnResult({data:null,error:p});throw p}let{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=De(o.access_token),u=null;c.aal&&(u=c.aal);let h=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let y=c.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:y},error:null}}async _getRecoveryCodesStatus(){Re(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){Re(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:o,error:l}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):this._returnResult({data:o,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verifyRecoveryCode(e){Re(this.experimental);let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let{data:l,error:c}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(c)return this._returnResult({data:null,error:c});let u=Object.assign({expires_at:Ve(l.expires_in)},l);return await this._saveSession(u),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:l,error:null})})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){Re(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){Re(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await g(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await g(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&q()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await g(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&q()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await g(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new j})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await g(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+Gt>s)return r;let{data:i,error:o}=await g(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:p,error:S}=await this.getSession();if(S||!p.session)return this._returnResult({data:null,error:S});r=p.session.access_token}let{header:s,payload:i,signature:o,raw:{header:l,payload:c}}=De(r);if(!t?.allowExpired)try{ar(i.exp)}catch(p){throw new le(p instanceof Error?p.message:"JWT validation failed")}let u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){let{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:s,signature:o},error:null}}let h=lr(s.alg),f=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,f,o,Yt(`${l}.${c}`)))throw new le("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var t,r,s,i;try{if(!Le())return this._returnResult({data:null,error:new F("Browser does not support WebAuthn",null)});let{data:o,error:l}=await this._startPasskeyAuthentication({options:{captchaToken:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}});if(l||!o)return this._returnResult({data:null,error:l});let c=Rt(o.options),u=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:et.createNewAbortSignal(),{data:h,error:f}=await Tt({publicKey:c,signal:u,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(f||!h)return this._returnResult({data:null,error:f??new F("WebAuthn ceremony failed",null)});let y=At(h);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:y})}catch(o){if(w(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var t,r;try{if(!Le())return this._returnResult({data:null,error:new F("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let o=St(s.options),l=(r=(t=e?.options)===null||t===void 0?void 0:t.signal)!==null&&r!==void 0?r:et.createNewAbortSignal(),{data:c,error:u}=await It({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new F("WebAuthn ceremony failed",null)});let h=Et(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await g(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await g(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;try{let{data:r,error:s}=await g(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:r}=await g(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:z});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await g(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await g(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{error:i}=await g(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}};tt.nextInstanceID={};var xt=tt;var es=xt,Ct=es;var ue=document.querySelector("#app"),qe=document.querySelector("#notice"),d={auth:null,config:null,user:null,workspaces:[],workspace:null,tab:"sessions",generation:0,conversationAgent:"",search:"",channelId:"",threadId:"",channelSearch:""},br,st=[];function Rr(){for(let n of st.splice(0))n()}var be=new URLSearchParams(location.search);be.has("billing")&&(d.tab="billing");var $t="agentintercom-pending",$={};try{let n=JSON.parse(sessionStorage.getItem($t)||"{}");n.until>Date.now()&&($=n)}catch{}be.get("authorization_id")&&($.authorization=be.get("authorization_id"));var Er=new URLSearchParams(location.hash.slice(1)),kr=Er.get("invite"),Sr=Er.get("device")||be.get("device_code");Sr&&($.device=Sr,history.replaceState(null,"",location.pathname+location.search));kr&&($.invite=kr,history.replaceState(null,"",location.pathname+location.search));($.authorization||$.invite||$.device)&&sessionStorage.setItem($t,JSON.stringify({...$,until:Date.now()+1200*1e3}));function a(n,e={},...t){let r=document.createElement(n);for(let[s,i]of Object.entries(e))i==null||i===!1||(s.startsWith("on")?r.addEventListener(s.slice(2),i):s==="class"?r.className=i:s==="text"?r.textContent=i:r.setAttribute(s,i===!0?"":String(i)));for(let s of t.flat(1/0))s!=null&&r.append(s instanceof Node?s:document.createTextNode(String(s)));return r}function Y(n,e=!1){clearTimeout(br),qe.textContent=n,qe.hidden=!1,qe.className=e?"error":"",qe.setAttribute("role",e?"alert":"status"),br=setTimeout(()=>{qe.hidden=!0},e?15e3:6e3)}async function Ie(n,e){if(!n?.disabled){n&&(n.disabled=!0);try{return await e()}catch(t){Y(t.message||"Something went wrong. Please try again.",!0)}finally{n&&(n.disabled=!1)}}}function v(n,e,t=""){return a("button",{type:"button",class:t,onclick:r=>Ie(r.currentTarget,e)},n)}function L(n,e={}){let t=a(e.multiline?"textarea":"input",{...e,multiline:null});return{input:t,node:a("label",{},n,t)}}function W(n,e,t){let r=a("button",{type:"submit",class:"primary"},e);return a("form",{onsubmit:s=>{s.preventDefault(),Ie(r,()=>t(new FormData(s.currentTarget)))}},n,r)}var de=()=>a("div",{class:"brand"},a("span",{class:"mark","aria-hidden":!0},"o"),"agent intercom"),V=n=>n?new Date(n).toLocaleString():"\u2014",D=n=>`/api/workspaces/${encodeURIComponent(d.workspace.id)}${n}`;async function k(n,e={}){let t={"Content-Type":"application/json"};if(d.auth&&n!=="/api/config"){let{data:i,error:o}=await d.auth.getSession();if(o)throw o;i.session&&(t.Authorization=`Bearer ${i.session.access_token}`)}let r=await fetch(n,{method:e.method||"GET",credentials:"omit",headers:t,body:e.body==null?void 0:JSON.stringify(e.body),signal:AbortSignal.timeout(e.timeout||15e3)}),s=await r.json();if(!r.ok||s.ok===!1||s.error)throw new Error(s.error?.message||"The request could not be completed. Please try again.");return s.result}async function at(n){await navigator.clipboard.writeText(n),Y("Copied to clipboard.")}var Me=new Map,Ar=()=>`${d.user?.id||""} +${d.workspace?.id||""}`,Ae=n=>Me.get(Ar()+` +`+n),nt=(n,e)=>{let t=Ar()+` +`+n;e==null?Me.delete(t):Me.set(t,e)};function ts(n){if(n)for(let e of[...Me.keys()])e.startsWith(n+` +`)&&Me.delete(e)}async function Ir(n,e){let t=[],r=new Set,s="";for(let i=0;;i++){let o=await k(n+"/sessions"+(s?"?after="+encodeURIComponent(s):""));if(e.stale())break;for(let l of o.sessions)r.has(l.id)||(r.add(l.id),t.push(l));if(s=o.nextCursor,!s||i+1>=50)break}return t}function rs(n){let e=new Map;for(let t of n){let r=t.displayName||t.agentId||t.id;e.set(r,(e.get(r)||0)+1)}return new Map(n.map(t=>{let r=t.displayName||t.agentId||t.id;return[t.id,e.get(r)>1?`${r} \xB7 ${t.deviceName||t.id}`:r]}))}var Ot=new WeakMap;async function Dt(n,e={}){let{data:t,error:r}=await d.auth.getSession();if(r)throw r;if(!t.session)throw new Error("Sign in again to access workspace files.");let s=await fetch(n,{...e,credentials:"omit",redirect:"error",headers:{Authorization:`Bearer ${t.session.access_token}`,"Content-Type":"application/octet-stream"},signal:AbortSignal.timeout(3e4)});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(i.error?.message||"File transfer failed. Please try again.")}return s}async function Tr(n,e){if(e.size>16*1024*1024)throw new Error("Files can be up to 16 MiB.");Ot.has(e)||Ot.set(e,crypto.randomUUID());let t=new URLSearchParams({name:e.name,mediaType:e.type.split(";")[0]||"application/octet-stream",idempotencyKey:Ot.get(e)}),s=await(await Dt(n+"/attachments?"+t,{method:"POST",body:e})).json();if(!s.ok)throw new Error(s.error?.message||"Upload failed.");return s.result}async function xr(n,e,t){let r=await Dt(n+"/attachments/"+encodeURIComponent(e)+"/content"),s=await r.arrayBuffer();if([...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(u=>u.toString(16).padStart(2,"0")).join("")!==r.headers.get("X-Content-SHA256"))throw new Error("File checksum did not match. The download was stopped.");let o=r.headers.get("Content-Disposition")||"";if(!t)try{t=decodeURIComponent(o.match(/filename\*=utf-8''([^;]+)/i)?.[1]||"")||o.match(/filename="([^"]+)"/)?.[1]||o.match(/filename=([^;]+)/)?.[1]}catch{}let l=URL.createObjectURL(new Blob([s],{type:"application/octet-stream"})),c=a("a",{href:l,download:(t||e).replace(/[\\/\x00-\x1f]/g,"_")});document.body.append(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}function Cr(n,e){let t=L("Attach a file",{type:"file"}),r=v("Upload and attach",async()=>{let s=t.input.files[0];if(!s)throw new Error("Choose a file first.");let i=t.input.closest("form")?.querySelector('[type="submit"]');i&&(i.disabled=!0);try{let o=await Tr(n,s);e.value+=`${e.value?` -`:""}${o.name}: ${o.uri}`,t.input.value="",H("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Sr(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>_(i?`Download ${i}`:"Download shared file",()=>br(n,s,i))))}async function zr(){let n=D(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?_("Delete file",()=>te("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),_("Delete permanently",async()=>{await b(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await C()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${B(l.createdAt)}`),a("div",{class:"actions"},_("Download",()=>br(n,l.id,l.name)),_("Copy reference",()=>rt(l.uri)),u)))}},s=await b(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=N("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},F([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await vr(n,o),await C()})),t),s.nextCursor){let o=s.nextCursor,l=_("More files",async()=>{let c=await b(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function et(n){delete $[n],sessionStorage.setItem(xt,JSON.stringify({...$,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}function te(n,e){let t=a("dialog",{},a("h2",{},n)),r=()=>{t.close(),t.remove()};return t.append(e(r),a("div",{class:"actions end"},_("Close",r))),t.addEventListener("close",()=>t.remove()),document.body.append(t),t.showModal(),t}function tt(n,e,t){te(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),_("Copy",()=>rt(e))))}function At(){mr(),d.user=null;let n=N("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),e=F([n.node],"Continue with email",async i=>{let{error:o}=await d.auth.signInWithOtp({email:i.get("email"),options:{emailRedirectTo:location.origin+"/app"+($.authorization?"?authorization_id="+encodeURIComponent($.authorization):$.device?"?device_code="+encodeURIComponent($.device):""),shouldCreateUser:!0}});if(o)throw o;H("Check your email for an October sign-in link. Open it in this browser."),e.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),t=N("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),r=N("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),s=F([t.node,r.node],"Sign in",async i=>{let{error:o}=await d.auth.signInWithPassword({email:i.get("email"),password:i.get("password")});if(o)throw o;await Y()});le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. -A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),e,a("details",{},a("summary",{},"Use an existing password"),s),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function Y(){d.user=await b("/api/me"),d.workspaces=await b("/api/workspaces");let n=_e.has("billing")&&_e.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,$.invite)return Jr();if($.authorization)return It();if($.device)return Tt();if(!d.workspace)return Rr();await C()}function st(n){let e=N("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return F([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await b("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Rr(){le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),st(C),_("Sign out",Ot))))}async function Ot(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,At()}function Pt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Re(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function It(){let n=await b(`/api/oauth/requests/${encodeURIComponent($.authorization)}`),e=d.workspace?.id,r=(e?await b(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await b(`/api/oauth/requests/${encodeURIComponent($.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});et("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Pt(It)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},_("Allow connection",()=>o(!0),"primary"),_("Cancel",()=>o(!1)))):st(It);le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function Tt(){let n=await b(`/api/device/authorizations/${encodeURIComponent($.device)}`),e=d.workspace?.id,r=(e?await b(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await b(`/api/device/authorizations/${encodeURIComponent($.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),et("device"),le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),_("Open workspace",Y,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Pt(Tt)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},_("Connect this device",()=>o(!0),"primary"),_("Decline",()=>o(!1)))):st(Tt);le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function Jr(){le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},_("Accept invitation",async()=>{let n=await b("/api/invites/accept",{method:"POST",body:{token:$.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),et("invite"),await Y()},"primary"),_("Use another account",Ot),_("Cancel",async()=>{et("invite"),await Y()})))))}var Qe={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function C(){if(mr(),!d.workspace)return Rr();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(Qe).map(([s,[i]])=>_(i,async()=>{d.tab=s,await C()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(Qe)[i]===d.tab&&s.setAttribute("aria-current","page")}),le.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},ce(),a("div",{class:"workspace-switch"},Pt(C),_("+ New workspace",()=>te("New workspace",s=>st(async()=>{s(),await C()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),_("Sign out",Ot,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},Qe[d.tab][0]),a("p",{class:"muted"},Qe[d.tab][1])),d.tab==="sessions"?_("Connect an app",async()=>{d.tab="connect",await C()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:ns,billing:ss,files:zr,channels:rs,messages:Zr,tasks:es,questions:ts,sessions:Hr,connect:Yr,members:Xr}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),_("Try again",C)))}}async function Hr(){let n=a("div"),e=a("div",{class:"grid"}),t=await b(D("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${B(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},_("Open conversation",async()=>{d.conversationAgent=i.id,d.tab="messages",await C()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),_("Copy session ID",()=>rt(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),_("Connect an app",async()=>{d.tab="connect",await C()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=_("Show more sessions",async()=>{let o=await b(D("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),_("Refresh sessions",C)),n}function Yr(){let n=d.config.mcpUrl,e=D("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),_("Copy connector URL",()=>rt(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),F([N("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await b(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});tt("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${B(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default -agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),F([N("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await b(D("/devices"),{method:"POST",body:{name:t.get("name")}});tt("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function Xr(){let n=D(""),[e,t]=await Promise.all([b(D("/members")),b(D("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await b(D(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await Y()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>te("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await b(D(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await Y()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${B(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>te("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let f=await b(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),tt("Replacement MCP key",f.token,`Update your app\u2019s secret/API key field. Shown once; expires ${B(f.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>te("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await b(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await C()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${B(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=N("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=F([l.node],"Create invitation",async f=>{let g=await b(D("/invites"),{method:"POST",body:{email:f.get("email"),role:"member"}});tt("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(g.token)}`,`Share this link with ${g.email}. It expires ${B(g.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await b(D("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let f of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},f.email),a("p",{class:"help"},`Expires ${B(f.expiresAt)}`)),_("Revoke invitation",async()=>{await b(D(`/invites/${encodeURIComponent(f.id)}`),{method:"DELETE"}),await C()},"danger")));o.append(h)}return o}async function Qr(){if(d.config=await b("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new Rt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await Y():At(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,At()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Re(null,Y),0)})}Qr().catch(n=>{le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});async function Zr(){let n=d.generation,e=D(""),[t,r]=await Promise.all([b(e+"/sessions"),b(e+"/members")]),s=t.sessions,i=new Map(s.map(S=>["agent:"+S.id,S.displayName]));for(let S of r)i.set("human:"+S.userId,S.email);let o=(S,m)=>i.get(S+":"+m)||m,l=new URLSearchParams;d.conversationAgent&&l.set("agentId",d.conversationAgent),d.search&&l.set("query",d.search);let c=a("select",{"aria-label":"Filter by session",onchange:S=>{d.conversationAgent=S.target.value,Re(null,C)}},a("option",{value:""},"All sessions"),s.map(S=>a("option",{value:S.id,selected:S.id===d.conversationAgent},S.displayName))),u=N("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),h=F([u.node],"Search",async S=>{d.search=S.get("query").trim(),await C()}),f=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",c),h)),g=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),p=new Map,k=!0,E=!1;Ze.push(()=>{k=!1});let A=S=>S.responseMessageId?"Replied":S.state==="acknowledged"?S.toKind==="human"?"Read":"Acknowledged":S.state==="delivered"?"Delivered to app":S.state==="expired"?"Expired":"Waiting for delivery",O=(S,m=!1)=>{let I=m?[...S.messages].reverse():S.messages;for(let T of I){let x=JSON.stringify(T),q=p.get(T.id);if(q?.fingerprint===x)continue;let G=a("article",{class:"card",id:T.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},o(T.fromKind,T.from))," \u2192 ",o(T.toKind,T.to),a("p",{class:"help"},B(T.createdAt))),a("span",{class:"badge"},A(T))),a("p",{class:"message"},T.body));G.append(Sr(e,T.body,T.context)),T.responseTo&&G.append(a("p",{class:"help"},"Reply to ",a("code",{},T.responseTo))),T.toKind==="human"&&T.to===d.user.id&&T.state!=="acknowledged"&&T.state!=="expired"&&G.append(_("Mark read",async()=>{await b(e+"/messages/read",{method:"POST",body:{messageIds:[T.id]}}),await C()},"subtle-button")),q?q.node.replaceWith(G):m?g.prepend(G):g.append(G),p.set(T.id,{fingerprint:x,node:G})}},R=await b(e+"/messages?"+l);O(R);let v=l.toString(),P=setInterval(async()=>{if(d.generation!==n){clearInterval(P);return}if(!(!k||E||document.hidden)){E=!0;try{let S=await b(e+"/messages?"+v);k&&(S.messages.length&&g.querySelector(".empty")?.remove(),O(S,!0))}catch(S){k&&H("Conversation refresh failed. "+S.message,!0)}finally{E=!1}}},5e3);if(Ze.push(()=>clearInterval(P)),R.messages.length||g.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),f.append(g),R.nextCursor){let S=R.nextCursor,m=_("Earlier messages",async()=>{l.set("before",S);let I=await b(e+"/messages?"+l);O(I),S=I.nextCursor,S||m.remove()});f.append(m)}if(s.length){let S=a("select",{name:"to",required:!0},s.map(q=>a("option",{value:q.id,selected:q.id===d.conversationAgent},q.displayName+(q.reachable?"":" \xB7 offline")))),m=N("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),I=crypto.randomUUID(),T="",x=F([a("label",{},"Send to",S),m.node,kr(e,m.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async q=>{let G=JSON.stringify([q.get("to"),q.get("body")]);T&&T!==G&&(I=crypto.randomUUID()),T=G,await b(e+"/messages",{method:"POST",body:{to:q.get("to"),body:q.get("body"),mode:"request",idempotencyKey:I}}),d.conversationAgent=q.get("to"),d.search="",H("Request saved. Delivery status will update when the app checks its inbox."),await C()});f.append(a("section",{class:"card"},a("h2",{},"Send a message"),x))}else f.append(_("Connect an app",async()=>{d.tab="connect",await C()},"primary"));return f.append(_("Refresh conversation",C)),f}async function es(){let n=D(""),e=await b(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},B(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await b(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=N("Task title",{name:"title",maxlength:256,required:!0}),o=N("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),F([i.node,o.node],"Create task",async l=>{await b(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),H("Task created. An agent can now claim it."),await C()}))),t}async function ts(){let n=D(""),e=await b(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=N("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",B(i.createdAt)),a("div",{class:"actions"},l),F([o.node],"Send answer",async c=>{await b(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),H("Answer saved for the requesting session."),await C()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await b(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",C)),t}async function rs(){let n=d.generation,e=D(""),t=await b(e+"/channels"),r=t.find(m=>m.id===d.channelId)||t[0];r?.id!==d.channelId&&(d.threadId=""),d.channelId=r?.id||"";let s=()=>te("Create a channel",m=>F([N("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,N("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async I=>{let T=await b(e+"/channels",{method:"POST",body:{name:I.get("name"),description:I.get("description")}});d.channelId=T.id,d.threadId="",d.channelSearch="",m(),await C()}));if(!r)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",s,"primary"));let i=a("select",{"aria-label":"Channel",onchange:m=>{d.channelId=m.target.value,d.threadId="",d.channelSearch="",Re(null,C)}},t.map(m=>a("option",{value:m.id,selected:m.id===r.id},"#"+m.name))),o=F([N("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async m=>{d.channelSearch=m.get("query").trim(),d.threadId="",await C()}),l=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",i),_("New channel",s)),a("p",{},r.description),a("p",{class:"help"},`${r.subscribers} subscribed sessions. Ask a connected session to join #${r.name} using subscribe_channel to receive future notifications.`),o));d.threadId&&l.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await C()})));let c=new URLSearchParams({channelId:r.id});d.threadId&&c.set("threadId",d.threadId),d.channelSearch&&c.set("query",d.channelSearch);let[u,h,f]=await Promise.all([b(e+"/channel-posts?"+c),b(e+"/members"),b(e+"/sessions")]),g=new Map(h.map(m=>["human:"+m.userId,m.email]));for(let m of f.sessions)g.set("agent:"+m.id,m.displayName);let p=a("div",{class:"conversation-list","aria-label":"Channel posts"}),k=new Map,E=(m,I=!1)=>{let T=I?[...m.posts].reverse():m.posts;for(let x of T){let q=JSON.stringify(x),G=k.get(x.id);if(G?.fingerprint===q)continue;let ve=a("article",{class:"card"},a("div",{class:"row"},a("strong",{},g.get(x.authorKind+":"+x.authorId)||x.authorId),a("small",{},B(x.createdAt))),a("p",{class:"message"},x.body));ve.append(Sr(e,x.body)),(!d.threadId||d.channelSearch)&&ve.append(_(x.replies?`${x.replies} ${x.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=x.threadId||x.id,d.channelSearch="",await C()})),G?G.node.replaceWith(ve):I?p.prepend(ve):p.append(ve),k.set(x.id,{fingerprint:q,node:ve})}};if(E(u),u.posts.length||p.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),l.append(p),u.nextCursor){let m=u.nextCursor,I=_("Earlier posts",async()=>{let T=new URLSearchParams(c);T.set("before",m);let x=await b(e+"/channel-posts?"+T);E(x),m=x.nextCursor,m||I.remove()});l.append(I)}let A=N(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),O=crypto.randomUUID(),R="";l.append(a("section",{class:"card"},F([A.node,kr(e,A.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async m=>{let I=m.get("body");R&&R!==I&&(O=crypto.randomUUID()),R=I,await b(e+"/channel-posts",{method:"POST",body:{channelId:r.id,body:I,threadId:d.threadId||void 0,idempotencyKey:O}}),d.channelSearch="",await C()})));let v=!0,P=!1,S=setInterval(async()=>{if(d.generation!==n){clearInterval(S);return}if(!(!v||P||document.hidden)){P=!0;try{let m=await b(e+"/channel-posts?"+c);v&&(m.posts.length&&p.querySelector(".empty")?.remove(),E(m,!0))}catch(m){v&&H("Channel refresh failed. "+m.message,!0)}finally{P=!1}}},5e3);return Ze.push(()=>{v=!1,clearInterval(S)}),l}async function ss(){let n=D("/billing"),e=await b(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=f=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(f/100),i=f=>f>=1024**3?`${(f/1024**3).toFixed(1)} GiB`:`${(f/1024**2).toFixed(1)} MiB`,o=f=>Number(f).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),_e.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${B(e.paidUntil)}.`:r?`Trial ends ${B(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${B(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(f,g){let p=await b(n+"/"+f,{method:"POST",body:g,timeout:3e4}),k=new URL(p.url);if(k.protocol!=="https:"||k.username||k.password||!["checkout.stripe.com","billing.stripe.com"].includes(k.host))throw new Error("Payment destination could not be verified.");location.assign(k.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await b(n+"/refresh",{method:"POST",timeout:3e4}),await C(),H("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await b(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await C()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[f,g,p,k]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},f),a("span",{},`${k(g)} / ${k(p)}`)),a("progress",{max:p,value:Math.min(g,p),"aria-label":f})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ns(){let n=D(""),e=d.workspace,t=await b(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>te(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await b(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await Y()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Ct(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=N("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),F([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await b(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});te("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await b(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await C(),H("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>te("Permanently delete this workspace?",o=>{let l=N("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),F([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await b(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await Y(),u}o(),await Y(),H("Workspace deleted.")}))}),"danger"))),s} +`:""}${o.name}: ${o.uri}`,e.dispatchEvent(new Event("input",{bubbles:!0})),t.input.value="",Y("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Or(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>v(i?`Download ${i}`:"Download shared file",()=>xr(n,s,i))))}async function ss(){let n=D(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?v("Delete file",()=>se("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),v("Delete permanently",async()=>{await k(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await O()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${V(l.createdAt)}`),a("div",{class:"actions"},v("Download",()=>xr(n,l.id,l.name)),v("Copy reference",()=>at(l.uri)),u)))}},s=await k(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=L("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},W([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await Tr(n,o),await O()})),t),s.nextCursor){let o=s.nextCursor,l=v("More files",async()=>{let c=await k(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function it(n){delete $[n],sessionStorage.setItem($t,JSON.stringify({...$,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}function se(n,e){let t=a("dialog",{},a("h2",{},n)),r=()=>{t.close(),t.remove()};return t.append(e(r),a("div",{class:"actions end"},v("Close",r))),t.addEventListener("close",()=>t.remove()),document.body.append(t),t.showModal(),t}function ot(n,e,t){se(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),v("Copy",()=>at(e))))}function Pt(){Rr();let n=d.user?.id;d.user=null,ts(n);let e=L("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),t=W([e.node],"Continue with email",async o=>{let{error:l}=await d.auth.signInWithOtp({email:o.get("email"),options:{emailRedirectTo:location.origin+"/app"+($.authorization?"?authorization_id="+encodeURIComponent($.authorization):$.device?"?device_code="+encodeURIComponent($.device):""),shouldCreateUser:!0}});if(l)throw l;Y("Check your email for an October sign-in link. Open it in this browser."),t.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),r=L("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),s=L("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),i=W([r.node,s.node],"Sign in",async o=>{let{error:l}=await d.auth.signInWithPassword({email:o.get("email"),password:o.get("password")});if(l)throw l;await Q()});ue.replaceChildren(a("main",{id:"main",class:"auth-wrap"},de(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. +A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),t,a("details",{},a("summary",{},"Use an existing password"),i),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function Q(){d.user=await k("/api/me"),d.workspaces=await k("/api/workspaces");let n=be.has("billing")&&be.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,$.invite)return ns();if($.authorization)return Ut();if($.device)return jt();if(!d.workspace)return Pr();await O()}function lt(n){let e=L("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return W([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await k("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Pr(){ue.replaceChildren(a("main",{id:"main",class:"auth-wrap"},de(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),lt(O),v("Sign out",Nt))))}async function Nt(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,Pt()}function Lt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Ie(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function Ut(){let n=await k(`/api/oauth/requests/${encodeURIComponent($.authorization)}`),e=d.workspace?.id,r=(e?await k(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await k(`/api/oauth/requests/${encodeURIComponent($.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});it("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Lt(Ut)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},v("Allow connection",()=>o(!0),"primary"),v("Cancel",()=>o(!1)))):lt(Ut);ue.replaceChildren(a("main",{id:"main",class:"consent"},de(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function jt(){let n=await k(`/api/device/authorizations/${encodeURIComponent($.device)}`),e=d.workspace?.id,r=(e?await k(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await k(`/api/device/authorizations/${encodeURIComponent($.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),it("device"),ue.replaceChildren(a("main",{id:"main",class:"consent"},de(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),v("Open workspace",Q,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Lt(jt)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},v("Connect this device",()=>o(!0),"primary"),v("Decline",()=>o(!1)))):lt(jt);ue.replaceChildren(a("main",{id:"main",class:"consent"},de(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function ns(){ue.replaceChildren(a("main",{id:"main",class:"consent"},de(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},v("Accept invitation",async()=>{let n=await k("/api/invites/accept",{method:"POST",body:{token:$.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),it("invite"),await Q()},"primary"),v("Use another account",Nt),v("Cancel",async()=>{it("invite"),await Q()})))))}var rt={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function O(){if(Rr(),!d.workspace)return Pr();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(rt).map(([s,[i]])=>v(i,async()=>{d.tab=s,await O()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(rt)[i]===d.tab&&s.setAttribute("aria-current","page")}),ue.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},de(),a("div",{class:"workspace-switch"},Lt(O),v("+ New workspace",()=>se("New workspace",s=>lt(async()=>{s(),await O()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),v("Sign out",Nt,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},rt[d.tab][0]),a("p",{class:"muted"},rt[d.tab][1])),d.tab==="sessions"?v("Connect an app",async()=>{d.tab="connect",await O()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:ps,billing:fs,files:ss,channels:hs,messages:cs,tasks:us,questions:ds,sessions:is,connect:os,members:as}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),v("Try again",O)))}}async function is(){let n=a("div"),e=a("div",{class:"grid"}),t=await k(D("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${V(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},v("Open conversation",async()=>{d.conversationAgent=i.id,d.tab="messages",await O()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),v("Copy session ID",()=>at(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),v("Connect an app",async()=>{d.tab="connect",await O()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=v("Show more sessions",async()=>{let o=await k(D("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),v("Refresh sessions",O)),n}function os(){let n=d.config.mcpUrl,e=D("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),v("Copy connector URL",()=>at(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),W([L("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await k(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});ot("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${V(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default +agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),W([L("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await k(D("/devices"),{method:"POST",body:{name:t.get("name")}});ot("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function as(){let n=D(""),[e,t]=await Promise.all([k(D("/members")),k(D("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,v("Save role",async()=>{await k(D(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await Q()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(v(l.userId===d.user.id?"Leave":"Remove",()=>se("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),v("Remove access",async()=>{await k(D(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await Q()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${V(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(v("Replace key",()=>se("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),v("Create replacement key",async()=>{let f=await k(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),ot("Replacement MCP key",f.token,`Update your app\u2019s secret/API key field. Shown once; expires ${V(f.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(v("Revoke",()=>se("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),v("Revoke connection",async()=>{await k(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await O()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${V(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=L("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=W([l.node],"Create invitation",async f=>{let y=await k(D("/invites"),{method:"POST",body:{email:f.get("email"),role:"member"}});ot("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(y.token)}`,`Share this link with ${y.email}. It expires ${V(y.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await k(D("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let f of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},f.email),a("p",{class:"help"},`Expires ${V(f.expiresAt)}`)),v("Revoke invitation",async()=>{await k(D(`/invites/${encodeURIComponent(f.id)}`),{method:"DELETE"}),await O()},"danger")));o.append(h)}return o}async function ls(){if(d.config=await k("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new Ct({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await Q():Pt(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,Pt()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Ie(null,Q),0)})}ls().catch(n=>{ue.replaceChildren(a("main",{id:"main",class:"auth-wrap"},de(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),v("Try again",()=>location.reload()))))});async function cs(){let n=d.generation,e=D(""),t=d.workspace.id,r={stale:()=>n!==d.generation||d.workspace?.id!==t},[s,i]=await Promise.all([Ir(e,r),k(e+"/members")]),o=rs(s),l=new Map(s.map(_=>["agent:"+_.id,_.displayName]));for(let _ of i)l.set("human:"+_.userId,_.email);let c=(_,N)=>l.get(_+":"+N)||N,u=new URLSearchParams;d.conversationAgent&&u.set("agentId",d.conversationAgent),d.search&&u.set("query",d.search);let h=a("select",{"aria-label":"Filter by session",onchange:_=>{d.conversationAgent=_.target.value,Ie(null,O)}},a("option",{value:""},"All sessions"),s.map(_=>a("option",{value:_.id,selected:_.id===d.conversationAgent},o.get(_.id)))),f=L("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),y=W([f.node],"Search",async _=>{d.search=_.get("query").trim(),await O()}),p=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",h),y)),S=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),E=new Map,A=!0,x=!1;st.push(()=>{A=!1});let R=_=>_.responseMessageId?"Replied":_.state==="acknowledged"?_.toKind==="human"?"Read":"Acknowledged":_.state==="delivered"?"Delivered to app":_.state==="expired"?"Expired":"Waiting for delivery",m=(_,N=!1)=>{let b=N?[..._.messages].reverse():_.messages;for(let I of b){let X=JSON.stringify(I),T=E.get(I.id);if(T?.fingerprint===X)continue;let B=a("article",{class:"card",id:I.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},c(I.fromKind,I.from))," \u2192 ",c(I.toKind,I.to),a("p",{class:"help"},V(I.createdAt))),a("span",{class:"badge"},R(I))),a("p",{class:"message"},I.body));B.append(Or(e,I.body,I.context)),I.responseTo&&B.append(a("p",{class:"help"},"Reply to ",a("code",{},I.responseTo))),I.toKind==="human"&&I.to===d.user.id&&I.state!=="acknowledged"&&I.state!=="expired"&&B.append(v("Mark read",async()=>{await k(e+"/messages/read",{method:"POST",body:{messageIds:[I.id]}}),await O()},"subtle-button")),T?T.node.replaceWith(B):N?S.prepend(B):S.append(B),E.set(I.id,{fingerprint:X,node:B})}},P=await k(e+"/messages?"+u);m(P);let M=u.toString(),C=setInterval(async()=>{if(d.generation!==n){clearInterval(C);return}if(!(!A||x||document.hidden)){x=!0;try{let _=await k(e+"/messages?"+M);A&&(_.messages.length&&S.querySelector(".empty")?.remove(),m(_,!0))}catch(_){A&&Y("Conversation refresh failed. "+_.message,!0)}finally{x=!1}}},5e3);if(st.push(()=>clearInterval(C)),P.messages.length||S.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),p.append(S),P.nextCursor){let _=P.nextCursor,N=v("Earlier messages",async()=>{u.set("before",_);let b=await k(e+"/messages?"+u);m(b),_=b.nextCursor,_||N.remove()});p.append(N)}if(s.length){let _=a("select",{name:"to",required:!0},s.map(T=>a("option",{value:T.id,selected:T.id===d.conversationAgent},o.get(T.id)+(T.reachable?"":" \xB7 offline")))),N=L("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),b=Ae("message");b?.body&&(N.input.value=b.body),b?.to&&s.some(T=>T.id===b.to)&&(_.value=b.to);let I=()=>{let T=JSON.stringify([_.value,N.input.value]),B=Ae("message");nt("message",{to:_.value,body:N.input.value,fingerprint:T,key:B?.fingerprint===T?B.key:crypto.randomUUID()})};_.addEventListener("change",I),N.input.addEventListener("input",I);let X=W([a("label",{},"Send to",_),N.node,Cr(e,N.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async T=>{I();let B=Ae("message");await k(e+"/messages",{method:"POST",body:{to:T.get("to"),body:T.get("body"),mode:"request",idempotencyKey:B.key}}),nt("message",null),d.conversationAgent=T.get("to"),d.search="",Y("Request saved. Delivery status will update when the app checks its inbox."),await O()});p.append(a("section",{class:"card"},a("h2",{},"Send a message"),X))}else p.append(v("Connect an app",async()=>{d.tab="connect",await O()},"primary"));return p.append(v("Refresh conversation",O)),p}async function us(){let n=D(""),e=await k(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},V(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=v("More tasks",async()=>{let u=await k(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=L("Task title",{name:"title",maxlength:256,required:!0}),o=L("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),W([i.node,o.node],"Create task",async l=>{await k(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),Y("Task created. An agent can now claim it."),await O()}))),t}async function ds(){let n=D(""),e=await k(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=L("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>v(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",V(i.createdAt)),a("div",{class:"actions"},l),W([o.node],"Send answer",async c=>{await k(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),Y("Answer saved for the requesting session."),await O()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=v("More questions",async()=>{let o=await k(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(v("Refresh questions",O)),t}async function hs(){let n=d.generation,e=D(""),t=await k(e+"/channels"),r=t.find(b=>b.id===d.channelId)||t[0];r?.id!==d.channelId&&(d.threadId=""),d.channelId=r?.id||"";let s=()=>se("Create a channel",b=>W([L("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,L("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async I=>{let X=await k(e+"/channels",{method:"POST",body:{name:I.get("name"),description:I.get("description")}});d.channelId=X.id,d.threadId="",d.channelSearch="",b(),await O()}));if(!r)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),v("Create a channel",s,"primary"));let i=a("select",{"aria-label":"Channel",onchange:b=>{d.channelId=b.target.value,d.threadId="",d.channelSearch="",Ie(null,O)}},t.map(b=>a("option",{value:b.id,selected:b.id===r.id},"#"+b.name))),o=W([L("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async b=>{d.channelSearch=b.get("query").trim(),d.threadId="",await O()}),l=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",i),v("New channel",s)),a("p",{},r.description),a("p",{class:"help"},`${r.subscribers} subscribed sessions. Ask a connected session to join #${r.name} using subscribe_channel to receive future notifications.`),o));d.threadId&&l.append(a("div",{class:"actions"},a("h2",{},"Thread"),v("Back to channel",async()=>{d.threadId="",await O()})));let c=new URLSearchParams({channelId:r.id});d.threadId&&c.set("threadId",d.threadId),d.channelSearch&&c.set("query",d.channelSearch);let u=d.workspace.id,h={stale:()=>n!==d.generation||d.workspace?.id!==u},[f,y,p]=await Promise.all([k(e+"/channel-posts?"+c),k(e+"/members"),Ir(e,h)]),S=new Map(y.map(b=>["human:"+b.userId,b.email]));for(let b of p)S.set("agent:"+b.id,b.displayName);let E=a("div",{class:"conversation-list","aria-label":"Channel posts"}),A=new Map,x=(b,I=!1)=>{let X=I?[...b.posts].reverse():b.posts;for(let T of X){let B=JSON.stringify(T),ct=A.get(T.id);if(ct?.fingerprint===B)continue;let ke=a("article",{class:"card"},a("div",{class:"row"},a("strong",{},S.get(T.authorKind+":"+T.authorId)||T.authorId),a("small",{},V(T.createdAt))),a("p",{class:"message"},T.body));ke.append(Or(e,T.body)),(!d.threadId||d.channelSearch)&&ke.append(v(T.replies?`${T.replies} ${T.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=T.threadId||T.id,d.channelSearch="",await O()})),ct?ct.node.replaceWith(ke):I?E.prepend(ke):E.append(ke),A.set(T.id,{fingerprint:B,node:ke})}};if(x(f),f.posts.length||E.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),l.append(E),f.nextCursor){let b=f.nextCursor,I=v("Earlier posts",async()=>{let X=new URLSearchParams(c);X.set("before",b);let T=await k(e+"/channel-posts?"+X);x(T),b=T.nextCursor,b||I.remove()});l.append(I)}let R=L(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),m=`channel +${r.id} +${d.threadId||""}`,P=Ae(m);P?.body&&(R.input.value=P.body);let M=()=>{let b=Ae(m);nt(m,{body:R.input.value,key:b?.body===R.input.value&&b.key?b.key:crypto.randomUUID()})};R.input.addEventListener("input",M),l.append(a("section",{class:"card"},W([R.node,Cr(e,R.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async b=>{M();let I=Ae(m);await k(e+"/channel-posts",{method:"POST",body:{channelId:r.id,body:b.get("body"),threadId:d.threadId||void 0,idempotencyKey:I.key}}),nt(m,null),d.channelSearch="",await O()})));let C=!0,_=!1,N=setInterval(async()=>{if(d.generation!==n){clearInterval(N);return}if(!(!C||_||document.hidden)){_=!0;try{let b=await k(e+"/channel-posts?"+c);C&&(b.posts.length&&E.querySelector(".empty")?.remove(),x(b,!0))}catch(b){C&&Y("Channel refresh failed. "+b.message,!0)}finally{_=!1}}},5e3);return st.push(()=>{C=!1,clearInterval(N)}),l}async function fs(){let n=D("/billing"),e=await k(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=f=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(f/100),i=f=>f>=1024**3?`${(f/1024**3).toFixed(1)} GiB`:`${(f/1024**2).toFixed(1)} MiB`,o=f=>Number(f).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),be.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${V(e.paidUntil)}.`:r?`Trial ends ${V(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${V(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(f,y){let p=await k(n+"/"+f,{method:"POST",body:y,timeout:3e4}),S=new URL(p.url);if(S.protocol!=="https:"||S.username||S.password||!["checkout.stripe.com","billing.stripe.com"].includes(S.host))throw new Error("Payment destination could not be verified.");location.assign(S.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(v(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),v(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(v("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(v("Check payment status",async()=>{await k(n+"/refresh",{method:"POST",timeout:3e4}),await O(),Y("Payment status checked.")})),e.pendingCheckout&&c.append(v("Close unfinished checkout",async()=>{await k(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await O()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[f,y,p,S]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},f),a("span",{},`${S(y)} / ${S(p)}`)),a("progress",{max:p,value:Math.min(y,p),"aria-label":f})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ps(){let n=D(""),e=d.workspace,t=await k(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),v(d.workspace.paused?"Resume sessions":"Pause sessions",()=>se(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),v("Confirm",async()=>{await k(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await Q()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),v("Download workspace archive",async()=>{let l=await(await Dt(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=L("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),W([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await k(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});se("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),v("Delete eligible history",async()=>{await k(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await O(),Y("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),v(e.deleting?"Retry workspace deletion":"Delete workspace",()=>se("Permanently delete this workspace?",o=>{let l=L("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),W([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await k(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await Q(),u}o(),await Q(),Y("Workspace deleted.")}))}),"danger"))),s} diff --git a/web/src/app.js b/web/src/app.js index bba9d0f..109c0b5 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -65,6 +65,32 @@ async function api(url, options = {}) { } async function copy(value) { await navigator.clipboard.writeText(value); inform('Copied to clipboard.'); } +const drafts = new Map(); +const draftScope = () => `${state.user?.id || ''}\n${state.workspace?.id || ''}`; +const getDraft = key => drafts.get(draftScope() + '\n' + key); +const setDraft = (key, value) => { const mapKey = draftScope() + '\n' + key; if (value == null) drafts.delete(mapKey); else drafts.set(mapKey, value); }; +function forgetDraftsFor(userId) { if (!userId) return; for (const key of [...drafts.keys()]) if (key.startsWith(userId + '\n')) drafts.delete(key); } +async function fetchSessions(scopePath, token) { + const sessions = [], seen = new Set(); + let cursor = ''; + for (let pages = 0; ; pages++) { + const page = await api(scopePath + '/sessions' + (cursor ? '?after=' + encodeURIComponent(cursor) : '')); + if (token.stale()) break; + for (const session of page.sessions) if (!seen.has(session.id)) { seen.add(session.id); sessions.push(session); } + cursor = page.nextCursor; + if (!cursor || pages + 1 >= 50) break; + } + return sessions; +} +function sessionLabels(sessions) { + const counts = new Map(); + for (const session of sessions) { const name = session.displayName || session.agentId || session.id; counts.set(name, (counts.get(name) || 0) + 1); } + return new Map(sessions.map(session => { + const name = session.displayName || session.agentId || session.id; + return [session.id, counts.get(name) > 1 ? `${name} · ${session.deviceName || session.id}` : name]; + })); +} + const uploadKeys = new WeakMap(); async function fileRequest(url, options = {}) { const { data, error } = await state.auth.getSession(); @@ -96,7 +122,7 @@ function attachmentPicker(scopePath, textInput) { const attach = button('Upload and attach', async () => { const selected = file.input.files[0]; if (!selected) throw new Error('Choose a file first.'); const submit = file.input.closest('form')?.querySelector('[type="submit"]'); if (submit) submit.disabled = true; - try { const uploaded = await uploadFile(scopePath, selected); textInput.value += `${textInput.value ? '\n\n' : ''}${uploaded.name}: ${uploaded.uri}`; file.input.value = ''; inform('File attached. Send your message to share the reference.'); } + try { const uploaded = await uploadFile(scopePath, selected); textInput.value += `${textInput.value ? '\n\n' : ''}${uploaded.name}: ${uploaded.uri}`; textInput.dispatchEvent(new Event('input', { bubbles: true })); file.input.value = ''; inform('File attached. Send your message to share the reference.'); } finally { if (submit) submit.disabled = false; } }); return el('details', {}, el('summary', {}, 'Attach a file'), file.node, attach, el('p', { class: 'help' }, 'Up to 16 MiB. Uploaded files are visible to everyone in this workspace.')); @@ -135,7 +161,9 @@ function secretDialog(title, value, description) { function signIn() { clearView(); + const previousUser = state.user?.id; state.user = null; + forgetDraftsFor(previousUser); const email = field('Email address', { type: 'email', name: 'email', autocomplete: 'email', required: true }); const emailForm = form([email.node], 'Continue with email', async data => { const { error } = await state.auth.signInWithOtp({ email: data.get('email'), options: { emailRedirectTo: location.origin + '/app' + (pending.authorization ? '?authorization_id=' + encodeURIComponent(pending.authorization) : pending.device ? '?device_code=' + encodeURIComponent(pending.device) : ''), shouldCreateUser: true } }); @@ -326,15 +354,17 @@ start().catch(error => { root.replaceChildren(el('main', { id: 'main', class: 'a async function messagesView() { const generation = state.generation; const scopePath = path(''); - const [sessionsPage, members] = await Promise.all([api(scopePath + '/sessions'), api(scopePath + '/members')]); - const sessions = sessionsPage.sessions; + const workspaceId = state.workspace.id; + const token = { stale: () => generation !== state.generation || state.workspace?.id !== workspaceId }; + const [sessions, members] = await Promise.all([fetchSessions(scopePath, token), api(scopePath + '/members')]); + const labels = sessionLabels(sessions); const names = new Map(sessions.map(s => ['agent:' + s.id, s.displayName])); for (const member of members) names.set('human:' + member.userId, member.email); const name = (kind, id) => names.get(kind + ':' + id) || id; const query = new URLSearchParams(); if (state.conversationAgent) query.set('agentId', state.conversationAgent); if (state.search) query.set('query', state.search); - const filter = el('select', { 'aria-label': 'Filter by session', onchange: e => { state.conversationAgent = e.target.value; action(null, render); } }, el('option', { value: '' }, 'All sessions'), sessions.map(s => el('option', { value: s.id, selected: s.id === state.conversationAgent }, s.displayName))); + const filter = el('select', { 'aria-label': 'Filter by session', onchange: e => { state.conversationAgent = e.target.value; action(null, render); } }, el('option', { value: '' }, 'All sessions'), sessions.map(s => el('option', { value: s.id, selected: s.id === state.conversationAgent }, labels.get(s.id)))); const search = field('Search messages', { name: 'query', value: state.search, type: 'search', maxlength: 256 }); const searchForm = form([search.node], 'Search', async data => { state.search = data.get('query').trim(); await render(); }); const container = el('div', {}, el('div', { class: 'card grid' }, el('label', {}, 'Conversation', filter), searchForm)); @@ -379,14 +409,23 @@ async function messagesView() { container.append(more); } if (sessions.length) { - const target = el('select', { name: 'to', required: true }, sessions.map(s => el('option', { value: s.id, selected: s.id === state.conversationAgent }, s.displayName + (s.reachable ? '' : ' · offline')))); + const target = el('select', { name: 'to', required: true }, sessions.map(s => el('option', { value: s.id, selected: s.id === state.conversationAgent }, labels.get(s.id) + (s.reachable ? '' : ' · offline')))); const body = field('Your message', { name: 'body', multiline: true, required: true, maxlength: 65536, placeholder: 'What would you like this session to help with?' }); - let idempotencyKey = crypto.randomUUID(), draft = ''; + const restored = getDraft('message'); + if (restored?.body) body.input.value = restored.body; + if (restored?.to && sessions.some(s => s.id === restored.to)) target.value = restored.to; + const saveDraft = () => { + const fingerprint = JSON.stringify([target.value, body.input.value]); + const previous = getDraft('message'); + setDraft('message', { to: target.value, body: body.input.value, fingerprint, key: previous?.fingerprint === fingerprint ? previous.key : crypto.randomUUID() }); + }; + target.addEventListener('change', saveDraft); + body.input.addEventListener('input', saveDraft); const compose = form([el('label', {}, 'Send to', target), body.node, attachmentPicker(scopePath, body.input), el('p', { class: 'help' }, 'Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.')], 'Send request', async data => { - const current = JSON.stringify([data.get('to'), data.get('body')]); - if (draft && draft !== current) idempotencyKey = crypto.randomUUID(); - draft = current; - await api(scopePath + '/messages', { method: 'POST', body: { to: data.get('to'), body: data.get('body'), mode: 'request', idempotencyKey } }); + saveDraft(); + const saved = getDraft('message'); + await api(scopePath + '/messages', { method: 'POST', body: { to: data.get('to'), body: data.get('body'), mode: 'request', idempotencyKey: saved.key } }); + setDraft('message', null); state.conversationAgent = data.get('to'); state.search = ''; inform('Request saved. Delivery status will update when the app checks its inbox.'); await render(); }); container.append(el('section', { class: 'card' }, el('h2', {}, 'Send a message'), compose)); @@ -450,9 +489,11 @@ async function channelsView() { const query = new URLSearchParams({ channelId: channel.id }); if (state.threadId) query.set('threadId', state.threadId); if (state.channelSearch) query.set('query', state.channelSearch); - const [page, members, directory] = await Promise.all([api(scopePath + '/channel-posts?' + query), api(scopePath + '/members'), api(scopePath + '/sessions')]); + const workspaceId = state.workspace.id; + const token = { stale: () => generation !== state.generation || state.workspace?.id !== workspaceId }; + const [page, members, directory] = await Promise.all([api(scopePath + '/channel-posts?' + query), api(scopePath + '/members'), fetchSessions(scopePath, token)]); const names = new Map(members.map(m => ['human:' + m.userId, m.email])); - for (const session of directory.sessions) names.set('agent:' + session.id, session.displayName); + for (const session of directory) names.set('agent:' + session.id, session.displayName); const list = el('div', { class: 'conversation-list', 'aria-label': 'Channel posts' }); const rendered = new Map(); const append = (page, fresh = false) => { @@ -472,10 +513,19 @@ async function channelsView() { container.append(list); if (page.nextCursor) { let cursor = page.nextCursor; const more = button('Earlier posts', async () => { const nextQuery = new URLSearchParams(query); nextQuery.set('before', cursor); const older = await api(scopePath + '/channel-posts?' + nextQuery); append(older); cursor = older.nextCursor; if (!cursor) more.remove(); }); container.append(more); } const body = field(state.threadId ? 'Your reply' : 'Your post', { name: 'body', multiline: true, required: true, maxlength: 65536 }); - let key = crypto.randomUUID(), draft = ''; + const draftName = `channel\n${channel.id}\n${state.threadId || ''}`; + const restored = getDraft(draftName); + if (restored?.body) body.input.value = restored.body; + const saveDraft = () => { + const previous = getDraft(draftName); + setDraft(draftName, { body: body.input.value, key: previous?.body === body.input.value && previous.key ? previous.key : crypto.randomUUID() }); + }; + body.input.addEventListener('input', saveDraft); container.append(el('section', { class: 'card' }, form([body.node, attachmentPicker(scopePath, body.input), el('p', { class: 'help' }, 'Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.')], state.threadId ? 'Reply in thread' : 'Post to channel', async data => { - const text = data.get('body'); if (draft && draft !== text) key = crypto.randomUUID(); draft = text; - await api(scopePath + '/channel-posts', { method: 'POST', body: { channelId: channel.id, body: text, threadId: state.threadId || undefined, idempotencyKey: key } }); + saveDraft(); + const saved = getDraft(draftName); + await api(scopePath + '/channel-posts', { method: 'POST', body: { channelId: channel.id, body: data.get('body'), threadId: state.threadId || undefined, idempotencyKey: saved.key } }); + setDraft(draftName, null); state.channelSearch = ''; await render(); }))); let live = true, polling = false; diff --git a/web/tests/workspace.spec.js b/web/tests/workspace.spec.js index 752e0cf..aa70072 100644 --- a/web/tests/workspace.spec.js +++ b/web/tests/workspace.spec.js @@ -313,6 +313,174 @@ test('data controls confirm pauses and cleanup, then download a portable archive expect(cleanups.map(c => c.execute)).toEqual([false, true]); }); +test('conversations reach sessions beyond the first page and isolate workspace switches', async ({ page }) => { + await fixture(page); + const sessionRequests = []; + let delayedResponses = 0, delayFirst = 0; + const page1 = [ + { id: 'session-001', displayName: 'Agent Dup', deviceId: 'device-1', deviceName: 'Laptop A', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }, + { id: 'session-002', displayName: 'Agent Dup', deviceId: 'device-2', deviceName: 'Laptop B', reachable: false, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }, + ]; + for (let i = 3; i <= 100; i++) page1.push({ id: `session-${String(i).padStart(3, '0')}`, displayName: `Agent ${i}`, deviceId: 'device-1', deviceName: 'Laptop A', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }); + const page2 = [{ id: 'session-101', displayName: 'Late Agent', deviceId: 'device-3', deviceName: 'Old laptop', reachable: false, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }]; + await page.route('**/api/workspaces', route => route.fulfill({ json: { ok: true, result: [ + { id: 'workspace-1', name: 'My workspace', role: 'owner', memberLimit: 5 }, + { id: 'workspace-2', name: 'Second workspace', role: 'owner', memberLimit: 5 }, + ] } })); + await page.route('**/api/workspaces/workspace-1/sessions*', async route => { + const url = new URL(route.request().url()); + sessionRequests.push(url.pathname + url.search); + if (url.searchParams.get('after')) { + return route.fulfill({ json: { ok: true, result: { sessions: page2 } } }); + } + if (delayFirst) { await new Promise(r => setTimeout(r, delayFirst)); delayedResponses++; } + await route.fulfill({ json: { ok: true, result: { sessions: page1, nextCursor: 'session-100' } } }); + }); + await page.route('**/api/workspaces/workspace-2/sessions*', async route => { + sessionRequests.push(new URL(route.request().url()).pathname); + await route.fulfill({ json: { ok: true, result: { sessions: [{ id: 'ws2-session', displayName: 'Second Workspace Agent', deviceId: 'device-9', deviceName: 'Tablet', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }] } } }); + }); + const messageQueries = []; + await page.route('**/api/workspaces/workspace-1/messages*', async route => { + messageQueries.push(new URL(route.request().url()).search); + await route.fallback(); + }); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const sendTo = page.locator('select[name="to"]'); + await expect(sendTo.locator('option')).toHaveCount(101); + await expect(sendTo.locator('option[value="session-101"]')).toHaveText('Late Agent · offline'); + await expect(sendTo.locator('option[value="session-001"]')).toHaveText('Agent Dup · Laptop A'); + await expect(sendTo.locator('option[value="session-002"]')).toHaveText('Agent Dup · Laptop B · offline'); + expect(sessionRequests.some(u => u.includes('after=session-100'))).toBe(true); + const filter = page.locator('select[aria-label="Filter by session"]'); + await expect(filter.locator('option[value="session-101"]')).toHaveText('Late Agent'); + await filter.selectOption('session-101'); + await expect.poll(() => messageQueries.some(q => q.includes('agentId=session-101')), { timeout: 5000 }).toBe(true); + await expect(page.locator('select[aria-label="Filter by session"]')).toHaveValue('session-101'); + delayFirst = 1200; + const continuationsBefore = sessionRequests.filter(u => u.includes('after=')).length; + await page.getByRole('button', { name: 'Refresh conversation', exact: true }).click(); + await page.locator('select[aria-label="Workspace"]').selectOption('workspace-2'); + await expect(page.locator('select[name="to"]').locator('option')).toHaveCount(1); + await expect(page.locator('select[name="to"]').locator('option[value="ws2-session"]')).toHaveText('Second Workspace Agent'); + await expect.poll(() => delayedResponses, { timeout: 5000 }).toBe(1); + expect(sessionRequests.filter(u => u.includes('after=')).length).toBe(continuationsBefore); + await expect(page.locator('select[name="to"]').locator('option')).toHaveCount(1); + await expect(page.locator('select[aria-label="Filter by session"]').locator('option')).toHaveCount(2); +}); + +test('conversation drafts survive navigation and refresh, stay in their workspace, and clear on send', async ({ page }) => { + await fixture(page); + await page.route('**/api/workspaces', route => route.fulfill({ json: { ok: true, result: [ + { id: 'workspace-1', name: 'My workspace', role: 'owner', memberLimit: 5 }, + { id: 'workspace-2', name: 'Second workspace', role: 'owner', memberLimit: 5 }, + ] } })); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const composer = page.getByLabel('Your message', { exact: true }); + await composer.fill('Please review this draft.'); + await page.getByText('Attach a file', { exact: true }).first().click(); + await page.getByLabel('Attach a file', { exact: true }).setInputFiles({ name: 'review.txt', mimeType: 'text/plain', buffer: Buffer.from('Review content') }); + await page.getByRole('button', { name: 'Upload and attach', exact: true }).click(); + await expect(composer).toHaveValue(/Please review this draft\.[\s\S]*october-bus:\/\/attachments\/att_/); + expect(await page.evaluate(() => JSON.stringify({ ...localStorage, ...sessionStorage }))).not.toContain('Please review this draft.'); + await page.getByRole('button', { name: 'Tasks', exact: true }).click(); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + await expect(composer).toHaveValue(/october-bus:\/\/attachments\/att_/); + await page.getByRole('button', { name: 'Refresh conversation', exact: true }).click(); + await expect(composer).toHaveValue(/october-bus:\/\/attachments\/att_/); + await page.locator('select[aria-label="Workspace"]').selectOption('workspace-2'); + await expect(composer).toHaveValue(''); + await page.locator('select[aria-label="Workspace"]').selectOption('workspace-1'); + await expect(composer).toHaveValue(/Please review this draft\./); + await page.getByRole('button', { name: 'Send request', exact: true }).click(); + await expect(page.getByText(/Please review this draft\./)).toBeVisible(); + await expect(composer).toHaveValue(''); +}); + +test('failed sends keep the draft and retry with the same idempotency key', async ({ page }) => { + await fixture(page); + const postedKeys = []; + await page.route('**/api/workspaces/workspace-1/messages*', async route => { + if (route.request().method() === 'POST' && postedKeys.length === 0) { + postedKeys.push(route.request().postDataJSON().idempotencyKey); + return route.fulfill({ status: 500, json: { ok: false, error: { message: 'Delivery uncertain. Please retry.' } } }); + } + if (route.request().method() === 'POST') postedKeys.push(route.request().postDataJSON().idempotencyKey); + await route.fallback(); + }); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + await page.getByLabel('Your message', { exact: true }).fill('Retry this request.'); + await page.getByRole('button', { name: 'Send request', exact: true }).click(); + await expect(page.getByText('Delivery uncertain. Please retry.', { exact: true })).toBeVisible(); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('Retry this request.'); + await page.getByRole('button', { name: 'Send request', exact: true }).click(); + await expect(page.getByText('Retry this request.', { exact: true })).toBeVisible(); + expect(postedKeys).toHaveLength(2); + expect(postedKeys[0]).toBeTruthy(); + expect(postedKeys[1]).toBe(postedKeys[0]); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue(''); +}); + +test('channel and thread drafts stay independent and clear only on send', async ({ page }) => { + await fixture(page); + await page.goto('/app'); + await page.getByRole('navigation', { name: 'Workspace' }).getByRole('button', { name: 'Channels', exact: true }).click(); + await page.getByRole('button', { name: 'Create a channel', exact: true }).click(); + await page.getByLabel('Channel name', { exact: true }).fill('drafts'); + await page.getByLabel('Description', { exact: true }).fill('Draft discussion'); + await page.getByRole('button', { name: 'Create channel', exact: true }).click(); + await page.getByLabel('Your post', { exact: true }).fill('First post body'); + await page.getByRole('button', { name: 'Post to channel', exact: true }).click(); + await expect(page.getByText('First post body', { exact: true })).toBeVisible(); + await page.getByLabel('Your post', { exact: true }).fill('Second post body'); + await page.getByRole('button', { name: 'Post to channel', exact: true }).click(); + await expect(page.getByText('Second post body', { exact: true })).toBeVisible(); + await expect(page.getByLabel('Your post', { exact: true })).toHaveValue(''); + await page.getByLabel('Your post', { exact: true }).fill('Unsent channel draft'); + await page.getByRole('button', { name: 'Open thread', exact: true }).first().click(); + await expect(page.getByLabel('Your reply', { exact: true })).toHaveValue(''); + await page.getByLabel('Your reply', { exact: true }).fill('Reply draft one'); + await page.getByRole('button', { name: 'Back to channel', exact: true }).click(); + await expect(page.getByLabel('Your post', { exact: true })).toHaveValue('Unsent channel draft'); + await page.getByRole('button', { name: 'Open thread', exact: true }).nth(1).click(); + await expect(page.getByLabel('Your reply', { exact: true })).toHaveValue(''); + await page.getByLabel('Your reply', { exact: true }).fill('Reply draft two'); + await page.getByRole('button', { name: 'Back to channel', exact: true }).click(); + await page.getByRole('button', { name: 'Open thread', exact: true }).first().click(); + await expect(page.getByLabel('Your reply', { exact: true })).toHaveValue('Reply draft one'); + await page.getByRole('button', { name: 'Reply in thread', exact: true }).click(); + await expect(page.getByText('Reply draft one', { exact: true })).toBeVisible(); + await expect(page.getByLabel('Your reply', { exact: true })).toHaveValue(''); + await page.getByRole('button', { name: 'Back to channel', exact: true }).click(); + await expect(page.getByLabel('Your post', { exact: true })).toHaveValue('Unsent channel draft'); +}); + +test('drafts never appear under a different signed-in account', async ({ page }) => { + await fixture(page); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + await page.getByLabel('Your message', { exact: true }).fill('Owner private draft'); + const intruder = { id: 'intruder-id', email: 'intruder@example.test', aud: 'authenticated', role: 'authenticated', email_confirmed_at: '2026-01-01T00:00:00Z' }; + const claims = Buffer.from(JSON.stringify({ sub: intruder.id, aud: 'authenticated', exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64'); + await page.route('**/auth/v1/token*', route => route.fulfill({ json: { + access_token: 'e30.' + claims + '.fixture', refresh_token: 'fixture-refresh-intruder', + expires_in: 3600, expires_at: Math.floor(Date.now() / 1000) + 3600, token_type: 'bearer', user: intruder, + } })); + await page.route('**/api/me', route => route.fulfill({ json: { ok: true, result: intruder } })); + await page.getByRole('button', { name: 'Sign out', exact: true }).click(); + await expect(page.getByRole('heading', { name: 'Sign in to October' })).toBeVisible(); + await page.getByText('Use an existing password', { exact: true }).click(); + await page.getByLabel('Email address', { exact: true }).last().fill('intruder@example.test'); + await page.getByLabel('Password', { exact: true }).fill('not-a-real-password'); + await page.getByRole('button', { name: 'Sign in', exact: true }).click(); + await expect(page.getByText('intruder@example.test', { exact: true })).toBeVisible(); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue(''); +}); + test('workspace deletion requires its name and recovers a failed cancellation', async ({ page }) => { await fixture(page); let deleting = false, deleted = false; From 32bc542fde77b75a8d537bca15a895636ac4f592 Mon Sep 17 00:00:00 2001 From: Harsh Date: Fri, 13 Nov 2026 00:36:16 -0800 Subject: [PATCH 2/3] Address round-1 audit: draft isolation, recipient rules, labels, full paging (#199) Per-view draft keys computed before the first await; detached-composer upload guard; key-matched draft clear on send; explicit-choice recipient release plus unavailable-recipient placeholder; collision-proof session labels; uncapped directory paging with no-progress stop. Seven new Playwright regression tests; bundle rebuilt with web's own build. --- bus/hostedweb/app.js | 43 +++++----- web/src/app.js | 59 ++++++------- web/tests/workspace.spec.js | 166 ++++++++++++++++++++++++++++++++++++ 3 files changed, 217 insertions(+), 51 deletions(-) diff --git a/bus/hostedweb/app.js b/bus/hostedweb/app.js index 8785beb..4038482 100644 --- a/bus/hostedweb/app.js +++ b/bus/hostedweb/app.js @@ -1,28 +1,27 @@ -function he(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s{let n=new Array(128);for(let e=0;e=6;){let r=e.queue>>e.queuedBits-6&63;t(Ge[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let r=e.queue>>e.queuedBits-6&63;t(Ge[r]),e.queuedBits-=6}}function Ht(n,e,t){let r=Ur[n];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function ft(n){let e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{Dr(o,r,t)};for(let o=0;o>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function $r(n,e){for(let t=0;t55295&&r<=56319){let s=(r-55296)*1024&65535;r=(n.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}jr(r,e)}}function Dr(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let r=1;r<6;r+=1)if((n>>7-r&1)===0){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function ce(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;se.push(t)),new Uint8Array(e)}function oe(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};return n.forEach(s=>Jt(s,t,r)),Jt(null,t,r),e.join("")}function Ve(n){return Math.round(Date.now()/1e3)+n}function Xt(){return Symbol("auth-callback")}var q=()=>typeof window<"u"&&typeof document<"u",ge={tested:!1,writable:!1},ze=()=>{if(!q())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ge.tested)return ge.writable;let n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),ge.tested=!0,ge.writable=!0}catch{ge.tested=!0,ge.writable=!1}return ge.writable};function pt(n){let e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}var Je=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),Qt=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",ee=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},K=async(n,e)=>{let t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}},G=async(n,e)=>{await n.removeItem(e)},je=class n{constructor(){this.promise=new n.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};je.promiseConstructor=Promise;function De(n){let e=n.split(".");if(e.length!==3)throw new le("Invalid JWT structure");for(let r=0;r{setTimeout(()=>e(null),n)})}function er(n,e){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await n(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function tr(n){return("0"+n.toString(16)).substr(-2)}function Nr(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,tr).join("")}async function Lr(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function qr(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),n;let t=await Lr(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Mr=/^[a-zA-Z0-9_-]{8,64}$/;function Ne(n){return typeof n=="string"&&Mr.test(n)?n:null}function Kr(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,tr).join("")}let n="";for(let e=0;e<32;e++)n+=Math.floor(Math.random()*16).toString(16);return n}var ye=(n,e)=>`${n}-flow-${e}-code-verifier`,$e=n=>`${n}-flows-code-verifier`;async function wt(n,e){let t=await K(n,$e(e));return Array.isArray(t)?t.filter(r=>Ne(r)!==null):[]}async function Fr(n,e,t,r,s){await ee(n,ye(e,t),r);let i=(await wt(n,e)).filter(o=>o!==t);for(i.push(t);i.length>Bt;){let o=i.shift();await G(n,ye(e,o)),s?.(o)}await ee(n,$e(e),i),await ee(n,`${e}-code-verifier`,r)}async function rr(n,e,t){if(t){let s=await K(n,ye(e,t));return{verifier:typeof s=="string"?s:null,flowId:t}}let r=await K(n,`${e}-code-verifier`);return{verifier:typeof r=="string"?r:null,flowId:null}}async function H(n,e,t){let r=`${e}-code-verifier`;if(!t){await G(n,r);return}let s=ye(e,t),i=await K(n,s);await G(n,s);let o=await wt(n,e),l=o.filter(c=>c!==t);l.length!==o.length&&(l.length>0?await ee(n,$e(e),l):await G(n,$e(e))),i!=null&&i===await K(n,r)&&await G(n,r)}async function sr(n,e){let t=await wt(n,e);for(let r of t)await G(n,ye(e,r));await G(n,$e(e)),await G(n,`${e}-code-verifier`)}function nr(n,e){let t=n.indexOf("#"),r=t===-1?n:n.slice(0,t),s=t===-1?"":n.slice(t),i=r.indexOf("?");if(i!==-1){let l=r.slice(0,i),c=r.slice(i+1).split("&").filter(u=>u!==""&&u!==ne&&!u.startsWith(`${ne}=`));r=c.length>0?`${l}?${c.join("&")}`:l}let o=r.includes("?")?"&":"?";return`${r}${o}${ne}=${encodeURIComponent(e)}${s}`}async function ir(n,e,t=!1,r){let s=Nr(),i=s;t&&(i+="/recovery");let o=Kr();await Fr(n,e,o,i,r);let l=await qr(s);return[l,s===l?"plain":"s256",o]}var Wr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function or(n){let e=n.headers.get(Te);if(!e||!e.match(Wr))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function ar(n){if(!n)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function lr(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Br=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function te(n){if(!Br.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Re(n){if(!n.recoveryCodes)throw new Error("@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).")}function He(){let n={};return new Proxy(n,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){let r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function cr(n,e){return new Proxy(n,{get:(t,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){let i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,s)}return!e.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(t,r,s)}})}function gt(n){return JSON.parse(JSON.stringify(n))}var me=n=>{if(typeof n=="object"&&n!==null){let e=n;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(n)},ur=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function dr(n){var e;if(!Qt(n))throw new we(me(n),0);let t;try{t=await n.json()}catch(i){throw ur.includes(n.status)?new we(n.statusText||`HTTP ${n.status}`,n.status):new F(me(i),i)}if(ur.includes(n.status))throw new we(me(t),n.status);let r,s=or(n);if(s&&s.getTime()>=ut["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Oe(me(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new j}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Oe(me(t),n.status,t.weak_password.reasons);throw new We(me(t),n.status||500,r)}var Gr=(n,e,t,r)=>{let s={method:n,headers:e?.headers||{}};return n==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function g(n,e,t,r){var s;let i=Object.assign({},r?.headers);i[Te]||(i[Te]=ut["2024-01-01"].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);let o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Vr(n,e,t+l,{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function Vr(n,e,t,r,s,i){let o=Gr(e,r,s,i),l;try{l=await n(t,Object.assign({},o))}catch(c){throw new we(me(c),0)}if(l.ok||await dr(l),r?.noResolveJson)return l;try{return await l.json()}catch(c){await dr(c)}}function z(n){var e;let t=null;zr(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=Ve(n.expires_in)));let r=(e=n.user)!==null&&e!==void 0?e:typeof n?.id=="string"?n:null;return{data:{session:t,user:r},error:null}}function yt(n){let e=z(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=n.weak_password),e}function re(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function hr(n){return{data:n,error:null}}function fr(n){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i}=n,o=he(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i},c=Object.assign({},o);return{data:{properties:l,user:c},error:null}}function mt(n){return n}function zr(n){return!!n.access_token&&!!n.refresh_token&&!!n.expires_in}var Ye=["global","local","others"];var _e=class{constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=Je(r),this.experimental=s??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=Ye[0]){if(Ye.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ye.join(", ")}`);try{return await g(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(w(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await g(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:re})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=he(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await g(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:fr,redirectTo:t?.redirectTo})}catch(t){if(w(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await g(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:re})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await g(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:mt});if(h.error)throw h.error;let f=await h.json(),y=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(S=>{let E=parseInt(S.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(S.split(";")[1].split("=")[1]);u[`${A}Page`]=E}),u.total=parseInt(y)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(w(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){te(e);try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:re})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){te(e);try{return await g(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:re})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){te(e);try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:re})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){te(e.userId);try{let{data:t,error:r}=await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _deleteFactor(e){te(e.userId),te(e.id);try{return{data:await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await g(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:mt});if(h.error)throw h.error;let f=await h.json(),y=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(S=>{let E=parseInt(S.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(S.split(";")[1].split("=")[1]);u[`${A}Page`]=E}),u.total=parseInt(y)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(w(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await g(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await g(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await g(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await g(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await g(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:r=>{var s;return{data:{providers:(s=r?.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(t){if(w(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await g(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await g(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await g(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminListPasskeys(e){te(e.userId);try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminDeletePasskey(e){te(e.userId),te(e.passkeyId);try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}};function _t(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}var Jr={debug:!!(globalThis&&ze()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Xe=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};function pr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function vt(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))throw new Error(`@supabase/auth-js: Address "${n}" is invalid.`);return n.toLowerCase()}function wr(n){return parseInt(n,16)}function gr(n){let e=new TextEncoder().encode(n);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function yr(n){var e;let{chainId:t,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:l,requestId:c,resources:u,scheme:h,uri:f,version:y}=n;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(y!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${y}`);if(!((e=n.statement)===null||e===void 0)&&e.includes(` -`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${n.statement}`)}let p=vt(n.address),S=h?`${h}://${r}`:r,E=n.statement?`${n.statement} -`:"",A=`${S} wants you to sign in with your Ethereum account: +function pe(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s{let n=new Array(128);for(let e=0;e=6;){let r=e.queue>>e.queuedBits-6&63;t(Ge[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let r=e.queue>>e.queuedBits-6&63;t(Ge[r]),e.queuedBits-=6}}function Ht(n,e,t){let r=Ur[n];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function ht(n){let e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{Dr(o,r,t)};for(let o=0;o>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function $r(n,e){for(let t=0;t55295&&r<=56319){let s=(r-55296)*1024&65535;r=(n.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}jr(r,e)}}function Dr(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let r=1;r<6;r+=1)if((n>>7-r&1)===0){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function de(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;se.push(t)),new Uint8Array(e)}function le(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};return n.forEach(s=>Jt(s,t,r)),Jt(null,t,r),e.join("")}function Ve(n){return Math.round(Date.now()/1e3)+n}function Xt(){return Symbol("auth-callback")}var K=()=>typeof window<"u"&&typeof document<"u",me={tested:!1,writable:!1},ze=()=>{if(!K())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(me.tested)return me.writable;let n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),me.tested=!0,me.writable=!0}catch{me.tested=!0,me.writable=!1}return me.writable};function ft(n){let e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}var Je=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),Qt=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",re=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},F=async(n,e)=>{let t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}},z=async(n,e)=>{await n.removeItem(e)},$e=class n{constructor(){this.promise=new n.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};$e.promiseConstructor=Promise;function Ne(n){let e=n.split(".");if(e.length!==3)throw new ue("Invalid JWT structure");for(let r=0;r{setTimeout(()=>e(null),n)})}function er(n,e){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await n(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function tr(n){return("0"+n.toString(16)).substr(-2)}function Nr(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,tr).join("")}async function Lr(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function qr(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),n;let t=await Lr(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Mr=/^[a-zA-Z0-9_-]{8,64}$/;function Le(n){return typeof n=="string"&&Mr.test(n)?n:null}function Kr(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,tr).join("")}let n="";for(let e=0;e<32;e++)n+=Math.floor(Math.random()*16).toString(16);return n}var _e=(n,e)=>`${n}-flow-${e}-code-verifier`,De=n=>`${n}-flows-code-verifier`;async function pt(n,e){let t=await F(n,De(e));return Array.isArray(t)?t.filter(r=>Le(r)!==null):[]}async function Fr(n,e,t,r,s){await re(n,_e(e,t),r);let i=(await pt(n,e)).filter(o=>o!==t);for(i.push(t);i.length>Bt;){let o=i.shift();await z(n,_e(e,o)),s?.(o)}await re(n,De(e),i),await re(n,`${e}-code-verifier`,r)}async function rr(n,e,t){if(t){let s=await F(n,_e(e,t));return{verifier:typeof s=="string"?s:null,flowId:t}}let r=await F(n,`${e}-code-verifier`);return{verifier:typeof r=="string"?r:null,flowId:null}}async function Q(n,e,t){let r=`${e}-code-verifier`;if(!t){await z(n,r);return}let s=_e(e,t),i=await F(n,s);await z(n,s);let o=await pt(n,e),l=o.filter(c=>c!==t);l.length!==o.length&&(l.length>0?await re(n,De(e),l):await z(n,De(e))),i!=null&&i===await F(n,r)&&await z(n,r)}async function sr(n,e){let t=await pt(n,e);for(let r of t)await z(n,_e(e,r));await z(n,De(e)),await z(n,`${e}-code-verifier`)}function nr(n,e){let t=n.indexOf("#"),r=t===-1?n:n.slice(0,t),s=t===-1?"":n.slice(t),i=r.indexOf("?");if(i!==-1){let l=r.slice(0,i),c=r.slice(i+1).split("&").filter(u=>u!==""&&u!==oe&&!u.startsWith(`${oe}=`));r=c.length>0?`${l}?${c.join("&")}`:l}let o=r.includes("?")?"&":"?";return`${r}${o}${oe}=${encodeURIComponent(e)}${s}`}async function ir(n,e,t=!1,r){let s=Nr(),i=s;t&&(i+="/recovery");let o=Kr();await Fr(n,e,o,i,r);let l=await qr(s);return[l,s===l?"plain":"s256",o]}var Wr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function or(n){let e=n.headers.get(xe);if(!e||!e.match(Wr))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function ar(n){if(!n)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function lr(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Br=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function se(n){if(!Br.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ae(n){if(!n.recoveryCodes)throw new Error("@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).")}function He(){let n={};return new Proxy(n,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){let r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function cr(n,e){return new Proxy(n,{get:(t,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){let i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,s)}return!e.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(t,r,s)}})}function wt(n){return JSON.parse(JSON.stringify(n))}var ve=n=>{if(typeof n=="object"&&n!==null){let e=n;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(n)},ur=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function dr(n){var e;if(!Qt(n))throw new ge(ve(n),0);let t;try{t=await n.json()}catch(i){throw ur.includes(n.status)?new ge(n.statusText||`HTTP ${n.status}`,n.status):new B(ve(i),i)}if(ur.includes(n.status))throw new ge(ve(t),n.status);let r,s=or(n);if(s&&s.getTime()>=ct["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Pe(ve(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new D}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Pe(ve(t),n.status,t.weak_password.reasons);throw new We(ve(t),n.status||500,r)}var Gr=(n,e,t,r)=>{let s={method:n,headers:e?.headers||{}};return n==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function g(n,e,t,r){var s;let i=Object.assign({},r?.headers);i[xe]||(i[xe]=ct["2024-01-01"].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);let o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Vr(n,e,t+l,{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function Vr(n,e,t,r,s,i){let o=Gr(e,r,s,i),l;try{l=await n(t,Object.assign({},o))}catch(c){throw new ge(ve(c),0)}if(l.ok||await dr(l),r?.noResolveJson)return l;try{return await l.json()}catch(c){await dr(c)}}function H(n){var e;let t=null;zr(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=Ve(n.expires_in)));let r=(e=n.user)!==null&&e!==void 0?e:typeof n?.id=="string"?n:null;return{data:{session:t,user:r},error:null}}function yt(n){let e=H(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=n.weak_password),e}function ne(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function hr(n){return{data:n,error:null}}function fr(n){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i}=n,o=pe(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i},c=Object.assign({},o);return{data:{properties:l,user:c},error:null}}function gt(n){return n}function zr(n){return!!n.access_token&&!!n.refresh_token&&!!n.expires_in}var Ye=["global","local","others"];var be=class{constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=Je(r),this.experimental=s??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=Ye[0]){if(Ye.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ye.join(", ")}`);try{return await g(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(w(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await g(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ne})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=pe(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await g(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:fr,redirectTo:t?.redirectTo})}catch(t){if(w(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await g(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ne})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await g(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:gt});if(h.error)throw h.error;let f=await h.json(),y=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(b=>{let E=parseInt(b.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(b.split(";")[1].split("=")[1]);u[`${A}Page`]=E}),u.total=parseInt(y)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(w(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){se(e);try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ne})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){se(e);try{return await g(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ne})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){se(e);try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ne})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){se(e.userId);try{let{data:t,error:r}=await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _deleteFactor(e){se(e.userId),se(e.id);try{return{data:await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await g(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:gt});if(h.error)throw h.error;let f=await h.json(),y=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(b=>{let E=parseInt(b.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(b.split(";")[1].split("=")[1]);u[`${A}Page`]=E}),u.total=parseInt(y)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(w(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await g(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await g(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await g(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await g(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await g(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:r=>{var s;return{data:{providers:(s=r?.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(t){if(w(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await g(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await g(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await g(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminListPasskeys(e){se(e.userId);try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminDeletePasskey(e){se(e.userId),se(e.passkeyId);try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}};function mt(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}var Jr={debug:!!(globalThis&&ze()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Xe=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};function pr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function _t(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))throw new Error(`@supabase/auth-js: Address "${n}" is invalid.`);return n.toLowerCase()}function wr(n){return parseInt(n,16)}function yr(n){let e=new TextEncoder().encode(n);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function gr(n){var e;let{chainId:t,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:l,requestId:c,resources:u,scheme:h,uri:f,version:y}=n;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(y!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${y}`);if(!((e=n.statement)===null||e===void 0)&&e.includes(` +`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${n.statement}`)}let p=_t(n.address),b=h?`${h}://${r}`:r,E=n.statement?`${n.statement} +`:"",A=`${b} wants you to sign in with your Ethereum account: ${p} -${E}`,x=`URI: ${f} +${E}`,C=`URI: ${f} Version: ${y} Chain ID: ${t}${o?` Nonce: ${o}`:""} -Issued At: ${i.toISOString()}`;if(s&&(x+=` -Expiration Time: ${s.toISOString()}`),l&&(x+=` -Not Before: ${l.toISOString()}`),c&&(x+=` -Request ID: ${c}`),u){let R=` -Resources:`;for(let m of u){if(!m||typeof m!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${m}`);R+=` -- ${m}`}x+=R}return`${A} -${x}`}var U=class extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},ve=class extends U{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function mr({error:n,options:e}){var t,r,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new U({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new U({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new U({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new U({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new U({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new U({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){let o=window.location.hostname;if(bt(o)){if(i.rp.id!==o)return new U({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new U({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function _r({error:n,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){let r=window.location.hostname;if(bt(r)){if(t.rpId!==r)return new U({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}var kt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},et=new kt;function St(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);let{challenge:e,user:t,excludeCredentials:r}=n,s=he(n,["challenge","user","excludeCredentials"]),i=ce(e).buffer,o=Object.assign(Object.assign({},t),{id:ce(t.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c0){i.allowCredentials=new Array(t.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of n)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){let l=r[i];e(l)?r[i]=Qe(l,o):r[i]=Qe(o)}else r[i]=o}return r}function Xr(n,e){return Qe(Hr,n,e||{})}function Qr(n,e){return Qe(Yr,n,e||{})}var Ze=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var o;try{let{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!l)return{data:null,error:c};let u=s??et.createNewAbortSignal();if(l.webauthn.type==="create"){let{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){let f=r;if(f)h.name=`${h.id}:${f}`;else{let p=(await this.client.getUser()).data.user,S=((o=p?.user_metadata)===null||o===void 0?void 0:o.name)||p?.email||p?.id||"User";h.name=`${h.id}:${S}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{let h=Xr(l.webauthn.credential_options.publicKey,i?.create),{data:f,error:y}=await It({publicKey:h,signal:u});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:y}}case"request":{let h=Qr(l.webauthn.credential_options.publicKey,i?.request),{data:f,error:y}=await Tt(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:y}}}}catch(l){return w(l)?{data:null,error:l}:{data:null,error:new F("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ae("rpId is required for WebAuthn authentication")};try{if(!Le())return{data:null,error:new F("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:l};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new F("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ae("rpId is required for WebAuthn registration")};try{if(!Le())return{data:null,error:new F("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var f;return(f=h.data)===null||f===void 0?void 0:f.all.find(y=>y.factor_type==="webauthn"&&y.friendly_name===e&&y.status==="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:l};let{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new F("Unexpected error in register",o)}}}};pr();var Zr={url:Mt,storageKey:Kt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ft,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Ee={},vr=!1,tt=class n{get jwks(){var e,t;return(t=(e=Ee[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Ee[this.storageKey]=Object.assign(Object.assign({},Ee[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Ee[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ee[this.storageKey]=Object.assign(Object.assign({},Ee[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Zr),e);if(this.storageKey=i.storageKey,this.instanceID=(t=n.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,n.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&q()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new _e({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Je(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,vr||(vr=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),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 Ze(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(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:ze()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=_t(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=_t(this.memoryStorage)),q()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ke}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(q()&&(t=pt(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),q()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Vt(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new F("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let i=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:z}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;let i=null;try{let o;if("email"in e){let{email:f,password:y,options:p}=e,S=null,E=null;this.flowType==="pkce"&&([S,E,i]=await this._getCodeChallengeAndMethod()),o=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(p?.emailRedirectTo,i),body:{email:f,password:y,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:S,code_challenge_method:E},xform:z})}else if("phone"in e){let{phone:f,password:y,options:p}=e;o=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:y,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(s=p?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:z})}else throw new fe("You must provide either an email or phone number and a password");let{data:l,error:c}=o;if(c||!l)return await H(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let u=l.session,h=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:h,session:u},error:null})}catch(o){if(await H(this.storage,this.storageKey,i),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:l}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:yt})}else if("phone"in e){let{phone:i,password:o,options:l}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:yt})}else throw new fe("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let i=new ie;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,l,c,u,h,f,y;let p,S;if("message"in e)p=e.message,S=e.signature;else{let{chain:E,wallet:A,statement:x,options:R}=e,m;if(q())if(typeof A=="object")m=A;else{let b=window;if("ethereum"in b&&typeof b.ethereum=="object"&&"request"in b.ethereum&&typeof b.ethereum.request=="function")m=b.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 A!="object"||!R?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");m=A}let P=new URL((t=R?.url)!==null&&t!==void 0?t:window.location.href),M=await m.request({method:"eth_requestAccounts"}).then(b=>b).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!M||M.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let C=vt(M[0]),_=(r=R?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!_){let b=await m.request({method:"eth_chainId"});_=wr(b)}let N={domain:P.host,address:C,statement:x,uri:P.href,version:"1",chainId:_,nonce:(s=R?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=R?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=R?.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=R?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=R?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=R?.signInWithEthereum)===null||h===void 0?void 0:h.resources};p=yr(N),S=await m.request({method:"personal_sign",params:[gr(p),C]})}try{let{data:E,error:A}=await g(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:S},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(y=e.options)===null||y===void 0?void 0:y.captchaToken}}:null),xform:z});if(A)throw A;if(!E||!E.session||!E.user){let x=new ie;return this._returnResult({data:{user:null,session:null},error:x})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:A})}catch(E){if(w(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var t,r,s,i,o,l,c,u,h,f,y,p;let S,E;if("message"in e)S=e.message,E=e.signature;else{let{chain:A,wallet:x,statement:R,options:m}=e,P;if(q())if(typeof x=="object")P=x;else{let C=window;if("solana"in C&&typeof C.solana=="object"&&("signIn"in C.solana&&typeof C.solana.signIn=="function"||"signMessage"in C.solana&&typeof C.solana.signMessage=="function"))P=C.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 x!="object"||!m?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");P=x}let M=new URL((t=m?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in P&&P.signIn){let C=await P.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},m?.signInWithSolana),{version:"1",domain:M.host,uri:M.href}),R?{statement:R}:null)),_;if(Array.isArray(C)&&C[0]&&typeof C[0]=="object")_=C[0];else if(C&&typeof C=="object"&&"signedMessage"in C&&"signature"in C)_=C;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in _&&"signature"in _&&(typeof _.signedMessage=="string"||_.signedMessage instanceof Uint8Array)&&_.signature instanceof Uint8Array)S=typeof _.signedMessage=="string"?_.signedMessage:new TextDecoder().decode(_.signedMessage),E=_.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in P)||typeof P.signMessage!="function"||!("publicKey"in P)||typeof P!="object"||!P.publicKey||!("toBase58"in P.publicKey)||typeof P.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");S=[`${M.host} wants you to sign in with your Solana account:`,P.publicKey.toBase58(),...R?["",R,""]:[""],"Version: 1",`URI: ${M.href}`,`Issued At: ${(s=(r=m?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=m?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${m.signInWithSolana.notBefore}`]:[],...!((o=m?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${m.signInWithSolana.expirationTime}`]:[],...!((l=m?.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${m.signInWithSolana.chainId}`]:[],...!((c=m?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${m.signInWithSolana.nonce}`]:[],...!((u=m?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${m.signInWithSolana.requestId}`]:[],...!((f=(h=m?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||f===void 0)&&f.length?["Resources",...m.signInWithSolana.resources.map(_=>`- ${_}`)]:[]].join(` -`);let C=await P.signMessage(new TextEncoder().encode(S),"utf8");if(!C||!(C instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=C}}try{let{data:A,error:x}=await g(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:S,signature:oe(E)},!((y=e.options)===null||y===void 0)&&y.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:z});if(x)throw x;if(!A||!A.session||!A.user){let R=new ie;return this._returnResult({data:{user:null,session:null},error:R})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:x})}catch(A){if(w(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e,t){let r=t?.flowId!=null,s=r?Ne(t?.flowId):q()?Ne(pt(window.location.href)[ne]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",t?.flowId);let{verifier:i,flowId:o}=r&&!s?{verifier:null,flowId:null}:await rr(this.storage,this.storageKey,s),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new Be;let{data:u,error:h}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:l},xform:z});if(await H(this.storage,this.storageKey,o),h)throw h;if(!u||!u.session||!u.user){let f=new ie;return this._returnResult({data:{user:null,session:null,redirectType:null},error:f})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:h})}catch(u){if(await H(this.storage,this.storageKey,o),w(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:o}=e,l=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:z}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){let h=new ie;return this._returnResult({data:{user:null,session:null},error:h})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;let l=null;try{if("email"in e){let{email:c,options:u}=e,h=null,f=null;this.flowType==="pkce"&&([h,f,l]=await this._getCodeChallengeAndMethod());let{error:y}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(t=u?.data)!==null&&t!==void 0?t:{},create_user:(r=u?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:y})}if("phone"in e){let{phone:c,options:u}=e,{data:h,error:f}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(s=u?.data)!==null&&s!==void 0?s:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(o=u?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:f})}throw new fe("You must provide either an email or phone number.")}catch(c){if(await H(this.storage,this.storageKey,l),w(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:l}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:z});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(s){if(w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());let u=await g(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:this._maybeAppendFlowIdToRedirect((t=e.options)===null||t===void 0?void 0:t.redirectTo,o)}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:hr});return!((s=u.data)===null||s===void 0)&&s.url&&q()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await H(this.storage,this.storageKey,o),w(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new j;let{error:s}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(w(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:o}=e,l=null,c=null;this.flowType==="pkce"&&([l,c,t]=await this._getCodeChallengeAndMethod());let{error:u}=await g(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t)});return u&&await H(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){let{phone:s,type:i,options:o}=e,{data:l,error:c}=await g(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:c})}throw new fe("You must provide either an email or phone number and a type")}catch(r){if(await H(this.storage,this.storageKey,t),w(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,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await K(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let t=await K(this.userStorage,this.storageKey+"-user");e.user=t?.user?t.user:He()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=cr(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return this.lock!=null?t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):t=await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:re}):await this._useSession(async t=>{var r,s,i;let{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new j}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:re})})}catch(t){if(w(t))return Pe(t)&&await this._removeSession(),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new j;let l=i.session,c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());let{data:h,error:f}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:re});if(f)throw f;return l.user=h.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(s){if(await H(this.storage,this.storageKey,r),w(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 j;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:o}=De(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{let{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}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 t=>{var r;if(!e){let{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new j;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!q())throw new pe("No browser detected.");if(e.error||e.error_description||e.error_code)throw new pe(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new xe("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new pe("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new xe("No code detected.");let{data:m,error:P}=await this._exchangeCodeForSession(e.code,{flowId:e[ne]});if(P)throw P;let M=new URL(window.location.href);return M.searchParams.delete("code"),M.searchParams.delete(ne),window.history.replaceState(window.history.state,"",M.toString()),{data:{session:m.session,redirectType:(r=m.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:h}=e;if(!o||!c||!l||!h)throw new pe("No session defined in URL");let f=Math.round(Date.now()/1e3),y=parseInt(c),p=f+y;u&&(p=parseInt(u));let S=p-f;S*1e3<=Z&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${S}s, should have been closer to ${y}s`);let E=p-y;f-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,p,f):f-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,p,f);let{data:A,error:x}=await this._getUser(o);if(x)throw x;let R={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:y,expires_at:p,refresh_token:l,token_type:h,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:R,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=Ne(e[ne]);return t&&await K(this.storage,ye(this.storageKey,t))?!0:!!await K(this.storage,`${this.storageKey}-code-verifier`)}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 t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:o}=t;if(o&&!Pe(o))return this._returnResult({error:o});let l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){let{error:c}=await this.admin.signOut(l,e);if(c&&!(dt(c)&&(c.status===404||c.status===401||c.status===403)||Pe(c)))return e!=="others"&&await s(),this._returnResult({error:c})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=Xt(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),ht(i))return;Pe(i)||Ue(i)||dt(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;this.flowType==="pkce"&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(o){if(await H(this.storage,this.storageKey,i),w(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async o=>{var l,c,u,h,f;let{data:y,error:p}=o;if(p)throw p;let{url:S,flowId:E}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(l=e.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=E,await g(this.fetch,"GET",S,{headers:this.headers,jwt:(f=(h=y.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(i)throw i;return q()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:r},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:l,token:c,access_token:u,nonce:h}=e,f=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:z}),{data:y,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!y||!y.session||!y.user?this._returnResult({data:{user:null,session:null},error:new ie}):(y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("USER_UPDATED",y.session)),this._returnResult({data:y,error:p}))}catch(s){if(await H(this.storage,this.storageKey,null),w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)throw o;return await g(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{let r=Date.now();return await er(async s=>(s>0&&await Zt(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:z})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Ue(i)&&Date.now()+o-r{});let i=await K(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(e);if(l)throw l;if(!o.session)throw new j;let c=await K(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let y={data:null,error:new Ce};return this.refreshingDeferred.resolve(y),y}let h=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await G(this.storage,this.storageKey),this.userStorage&&await G(this.userStorage,this.storageKey+"-user");let y={data:null,error:new Ce};return this.refreshingDeferred.resolve(y),y}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let f={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(f),f}catch(i){if(this._debug(s,"error",i),w(i)){let o={data:null,error:i};if(!Ue(i)){let l=await K(this.storage,this.storageKey);!!(l?.expires_at&&l.expires_at*1e3>Date.now())?this._debug(s,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+qt},(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:e,session:t,broadcast:r});return}let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;lthis._autoRefreshTokenTick(),Z);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/Z);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Z}ms, refresh threshold is ${Se} ticks`),s<=Se&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof Xe)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/Z);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Z}ms, refresh threshold is ${Se} ticks`),s<=Se&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!q()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"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(t,"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(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=r?.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,l));let c=[`provider=${encodeURIComponent(t)}`];if(s&&c.push(`redirect_to=${encodeURIComponent(s)}`),r?.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){let u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r?.queryParams){let u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r?.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:nr(e,t)}async _getCodeChallengeAndMethod(e=!1){return ir(this.storage,this.storageKey,e,t=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",t))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await g(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Et(e.webauthn.credential_response):At(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;let{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:St(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:Rt(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&i.factor_type in s&&Array.isArray(s[i.factor_type])&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:p}=De(e),S=null;p.aal&&(S=p.aal);let E=S,{data:{user:A},error:x}=await this.getUser(e);if(x)return this._returnResult({data:null,error:x});((r=(t=A?.factors)===null||t===void 0?void 0:t.filter(P=>P.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(E="aal2");let m=p.amr||[];return{data:{currentLevel:S,nextLevel:E,currentAuthenticationMethods:m},error:null}}catch(p){if(w(p))return this._returnResult({data:null,error:p});throw p}let{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=De(o.access_token),u=null;c.aal&&(u=c.aal);let h=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let y=c.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:y},error:null}}async _getRecoveryCodesStatus(){Re(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){Re(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:o,error:l}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):this._returnResult({data:o,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verifyRecoveryCode(e){Re(this.experimental);let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let{data:l,error:c}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(c)return this._returnResult({data:null,error:c});let u=Object.assign({expires_at:Ve(l.expires_in)},l);return await this._saveSession(u),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:l,error:null})})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){Re(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){Re(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await g(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await g(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&q()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await g(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&q()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await g(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new j})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await g(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+Gt>s)return r;let{data:i,error:o}=await g(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:p,error:S}=await this.getSession();if(S||!p.session)return this._returnResult({data:null,error:S});r=p.session.access_token}let{header:s,payload:i,signature:o,raw:{header:l,payload:c}}=De(r);if(!t?.allowExpired)try{ar(i.exp)}catch(p){throw new le(p instanceof Error?p.message:"JWT validation failed")}let u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){let{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:s,signature:o},error:null}}let h=lr(s.alg),f=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,f,o,Yt(`${l}.${c}`)))throw new le("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var t,r,s,i;try{if(!Le())return this._returnResult({data:null,error:new F("Browser does not support WebAuthn",null)});let{data:o,error:l}=await this._startPasskeyAuthentication({options:{captchaToken:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}});if(l||!o)return this._returnResult({data:null,error:l});let c=Rt(o.options),u=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:et.createNewAbortSignal(),{data:h,error:f}=await Tt({publicKey:c,signal:u,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(f||!h)return this._returnResult({data:null,error:f??new F("WebAuthn ceremony failed",null)});let y=At(h);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:y})}catch(o){if(w(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var t,r;try{if(!Le())return this._returnResult({data:null,error:new F("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let o=St(s.options),l=(r=(t=e?.options)===null||t===void 0?void 0:t.signal)!==null&&r!==void 0?r:et.createNewAbortSignal(),{data:c,error:u}=await It({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new F("WebAuthn ceremony failed",null)});let h=Et(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await g(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await g(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;try{let{data:r,error:s}=await g(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:r}=await g(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:z});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await g(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await g(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{error:i}=await g(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}};tt.nextInstanceID={};var xt=tt;var es=xt,Ct=es;var ue=document.querySelector("#app"),qe=document.querySelector("#notice"),d={auth:null,config:null,user:null,workspaces:[],workspace:null,tab:"sessions",generation:0,conversationAgent:"",search:"",channelId:"",threadId:"",channelSearch:""},br,st=[];function Rr(){for(let n of st.splice(0))n()}var be=new URLSearchParams(location.search);be.has("billing")&&(d.tab="billing");var $t="agentintercom-pending",$={};try{let n=JSON.parse(sessionStorage.getItem($t)||"{}");n.until>Date.now()&&($=n)}catch{}be.get("authorization_id")&&($.authorization=be.get("authorization_id"));var Er=new URLSearchParams(location.hash.slice(1)),kr=Er.get("invite"),Sr=Er.get("device")||be.get("device_code");Sr&&($.device=Sr,history.replaceState(null,"",location.pathname+location.search));kr&&($.invite=kr,history.replaceState(null,"",location.pathname+location.search));($.authorization||$.invite||$.device)&&sessionStorage.setItem($t,JSON.stringify({...$,until:Date.now()+1200*1e3}));function a(n,e={},...t){let r=document.createElement(n);for(let[s,i]of Object.entries(e))i==null||i===!1||(s.startsWith("on")?r.addEventListener(s.slice(2),i):s==="class"?r.className=i:s==="text"?r.textContent=i:r.setAttribute(s,i===!0?"":String(i)));for(let s of t.flat(1/0))s!=null&&r.append(s instanceof Node?s:document.createTextNode(String(s)));return r}function Y(n,e=!1){clearTimeout(br),qe.textContent=n,qe.hidden=!1,qe.className=e?"error":"",qe.setAttribute("role",e?"alert":"status"),br=setTimeout(()=>{qe.hidden=!0},e?15e3:6e3)}async function Ie(n,e){if(!n?.disabled){n&&(n.disabled=!0);try{return await e()}catch(t){Y(t.message||"Something went wrong. Please try again.",!0)}finally{n&&(n.disabled=!1)}}}function v(n,e,t=""){return a("button",{type:"button",class:t,onclick:r=>Ie(r.currentTarget,e)},n)}function L(n,e={}){let t=a(e.multiline?"textarea":"input",{...e,multiline:null});return{input:t,node:a("label",{},n,t)}}function W(n,e,t){let r=a("button",{type:"submit",class:"primary"},e);return a("form",{onsubmit:s=>{s.preventDefault(),Ie(r,()=>t(new FormData(s.currentTarget)))}},n,r)}var de=()=>a("div",{class:"brand"},a("span",{class:"mark","aria-hidden":!0},"o"),"agent intercom"),V=n=>n?new Date(n).toLocaleString():"\u2014",D=n=>`/api/workspaces/${encodeURIComponent(d.workspace.id)}${n}`;async function k(n,e={}){let t={"Content-Type":"application/json"};if(d.auth&&n!=="/api/config"){let{data:i,error:o}=await d.auth.getSession();if(o)throw o;i.session&&(t.Authorization=`Bearer ${i.session.access_token}`)}let r=await fetch(n,{method:e.method||"GET",credentials:"omit",headers:t,body:e.body==null?void 0:JSON.stringify(e.body),signal:AbortSignal.timeout(e.timeout||15e3)}),s=await r.json();if(!r.ok||s.ok===!1||s.error)throw new Error(s.error?.message||"The request could not be completed. Please try again.");return s.result}async function at(n){await navigator.clipboard.writeText(n),Y("Copied to clipboard.")}var Me=new Map,Ar=()=>`${d.user?.id||""} -${d.workspace?.id||""}`,Ae=n=>Me.get(Ar()+` -`+n),nt=(n,e)=>{let t=Ar()+` -`+n;e==null?Me.delete(t):Me.set(t,e)};function ts(n){if(n)for(let e of[...Me.keys()])e.startsWith(n+` -`)&&Me.delete(e)}async function Ir(n,e){let t=[],r=new Set,s="";for(let i=0;;i++){let o=await k(n+"/sessions"+(s?"?after="+encodeURIComponent(s):""));if(e.stale())break;for(let l of o.sessions)r.has(l.id)||(r.add(l.id),t.push(l));if(s=o.nextCursor,!s||i+1>=50)break}return t}function rs(n){let e=new Map;for(let t of n){let r=t.displayName||t.agentId||t.id;e.set(r,(e.get(r)||0)+1)}return new Map(n.map(t=>{let r=t.displayName||t.agentId||t.id;return[t.id,e.get(r)>1?`${r} \xB7 ${t.deviceName||t.id}`:r]}))}var Ot=new WeakMap;async function Dt(n,e={}){let{data:t,error:r}=await d.auth.getSession();if(r)throw r;if(!t.session)throw new Error("Sign in again to access workspace files.");let s=await fetch(n,{...e,credentials:"omit",redirect:"error",headers:{Authorization:`Bearer ${t.session.access_token}`,"Content-Type":"application/octet-stream"},signal:AbortSignal.timeout(3e4)});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(i.error?.message||"File transfer failed. Please try again.")}return s}async function Tr(n,e){if(e.size>16*1024*1024)throw new Error("Files can be up to 16 MiB.");Ot.has(e)||Ot.set(e,crypto.randomUUID());let t=new URLSearchParams({name:e.name,mediaType:e.type.split(";")[0]||"application/octet-stream",idempotencyKey:Ot.get(e)}),s=await(await Dt(n+"/attachments?"+t,{method:"POST",body:e})).json();if(!s.ok)throw new Error(s.error?.message||"Upload failed.");return s.result}async function xr(n,e,t){let r=await Dt(n+"/attachments/"+encodeURIComponent(e)+"/content"),s=await r.arrayBuffer();if([...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(u=>u.toString(16).padStart(2,"0")).join("")!==r.headers.get("X-Content-SHA256"))throw new Error("File checksum did not match. The download was stopped.");let o=r.headers.get("Content-Disposition")||"";if(!t)try{t=decodeURIComponent(o.match(/filename\*=utf-8''([^;]+)/i)?.[1]||"")||o.match(/filename="([^"]+)"/)?.[1]||o.match(/filename=([^;]+)/)?.[1]}catch{}let l=URL.createObjectURL(new Blob([s],{type:"application/octet-stream"})),c=a("a",{href:l,download:(t||e).replace(/[\\/\x00-\x1f]/g,"_")});document.body.append(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}function Cr(n,e){let t=L("Attach a file",{type:"file"}),r=v("Upload and attach",async()=>{let s=t.input.files[0];if(!s)throw new Error("Choose a file first.");let i=t.input.closest("form")?.querySelector('[type="submit"]');i&&(i.disabled=!0);try{let o=await Tr(n,s);e.value+=`${e.value?` +Issued At: ${i.toISOString()}`;if(s&&(C+=` +Expiration Time: ${s.toISOString()}`),l&&(C+=` +Not Before: ${l.toISOString()}`),c&&(C+=` +Request ID: ${c}`),u){let S=` +Resources:`;for(let m of u){if(!m||typeof m!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${m}`);S+=` +- ${m}`}C+=S}return`${A} +${C}`}var $=class extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},ke=class extends ${constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function mr({error:n,options:e}){var t,r,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new $({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new $({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new $({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new $({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new $({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new $({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new $({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new $({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){let o=window.location.hostname;if(vt(o)){if(i.rp.id!==o)return new $({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new $({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new $({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new $({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new $({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function _r({error:n,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new $({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new $({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){let r=window.location.hostname;if(vt(r)){if(t.rpId!==r)return new $({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new $({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new $({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new $({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}var bt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},et=new bt;function kt(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);let{challenge:e,user:t,excludeCredentials:r}=n,s=pe(n,["challenge","user","excludeCredentials"]),i=de(e).buffer,o=Object.assign(Object.assign({},t),{id:de(t.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c0){i.allowCredentials=new Array(t.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of n)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){let l=r[i];e(l)?r[i]=Qe(l,o):r[i]=Qe(o)}else r[i]=o}return r}function Xr(n,e){return Qe(Hr,n,e||{})}function Qr(n,e){return Qe(Yr,n,e||{})}var Ze=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var o;try{let{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!l)return{data:null,error:c};let u=s??et.createNewAbortSignal();if(l.webauthn.type==="create"){let{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){let f=r;if(f)h.name=`${h.id}:${f}`;else{let p=(await this.client.getUser()).data.user,b=((o=p?.user_metadata)===null||o===void 0?void 0:o.name)||p?.email||p?.id||"User";h.name=`${h.id}:${b}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{let h=Xr(l.webauthn.credential_options.publicKey,i?.create),{data:f,error:y}=await At({publicKey:h,signal:u});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:y}}case"request":{let h=Qr(l.webauthn.credential_options.publicKey,i?.request),{data:f,error:y}=await It(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:y}}}}catch(l){return w(l)?{data:null,error:l}:{data:null,error:new B("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ce("rpId is required for WebAuthn authentication")};try{if(!qe())return{data:null,error:new B("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:l};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new B("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ce("rpId is required for WebAuthn registration")};try{if(!qe())return{data:null,error:new B("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var f;return(f=h.data)===null||f===void 0?void 0:f.all.find(y=>y.factor_type==="webauthn"&&y.friendly_name===e&&y.status==="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:l};let{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new B("Unexpected error in register",o)}}}};pr();var Zr={url:Mt,storageKey:Kt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ft,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Ie={},vr=!1,tt=class n{get jwks(){var e,t;return(t=(e=Ie[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Ie[this.storageKey]=Object.assign(Object.assign({},Ie[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Ie[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ie[this.storageKey]=Object.assign(Object.assign({},Ie[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Zr),e);if(this.storageKey=i.storageKey,this.instanceID=(t=n.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,n.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&K()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new be({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Je(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,vr||(vr=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),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 Ze(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(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:ze()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=mt(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=mt(this.memoryStorage)),K()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ke}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(K()&&(t=ft(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),K()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Vt(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new B("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let i=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:H}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;let i=null;try{let o;if("email"in e){let{email:f,password:y,options:p}=e,b=null,E=null;this.flowType==="pkce"&&([b,E,i]=await this._getCodeChallengeAndMethod()),o=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(p?.emailRedirectTo,i),body:{email:f,password:y,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:b,code_challenge_method:E},xform:H})}else if("phone"in e){let{phone:f,password:y,options:p}=e;o=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:y,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(s=p?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:H})}else throw new we("You must provide either an email or phone number and a password");let{data:l,error:c}=o;if(c||!l)return await Q(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let u=l.session,h=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:h,session:u},error:null})}catch(o){if(await Q(this.storage,this.storageKey,i),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:l}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:yt})}else if("phone"in e){let{phone:i,password:o,options:l}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:yt})}else throw new we("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let i=new ae;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,l,c,u,h,f,y;let p,b;if("message"in e)p=e.message,b=e.signature;else{let{chain:E,wallet:A,statement:C,options:S}=e,m;if(K())if(typeof A=="object")m=A;else{let U=window;if("ethereum"in U&&typeof U.ethereum=="object"&&"request"in U.ethereum&&typeof U.ethereum.request=="function")m=U.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 A!="object"||!S?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");m=A}let x=new URL((t=S?.url)!==null&&t!==void 0?t:window.location.href),q=await m.request({method:"eth_requestAccounts"}).then(U=>U).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!q||q.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let P=_t(q[0]),j=(r=S?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!j){let U=await m.request({method:"eth_chainId"});j=wr(U)}let R={domain:x.host,address:P,statement:C,uri:x.href,version:"1",chainId:j,nonce:(s=S?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=S?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=S?.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=S?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=S?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=S?.signInWithEthereum)===null||h===void 0?void 0:h.resources};p=gr(R),b=await m.request({method:"personal_sign",params:[yr(p),P]})}try{let{data:E,error:A}=await g(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:b},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(y=e.options)===null||y===void 0?void 0:y.captchaToken}}:null),xform:H});if(A)throw A;if(!E||!E.session||!E.user){let C=new ae;return this._returnResult({data:{user:null,session:null},error:C})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:A})}catch(E){if(w(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var t,r,s,i,o,l,c,u,h,f,y,p;let b,E;if("message"in e)b=e.message,E=e.signature;else{let{chain:A,wallet:C,statement:S,options:m}=e,x;if(K())if(typeof C=="object")x=C;else{let P=window;if("solana"in P&&typeof P.solana=="object"&&("signIn"in P.solana&&typeof P.solana.signIn=="function"||"signMessage"in P.solana&&typeof P.solana.signMessage=="function"))x=P.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 C!="object"||!m?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=C}let q=new URL((t=m?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in x&&x.signIn){let P=await x.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},m?.signInWithSolana),{version:"1",domain:q.host,uri:q.href}),S?{statement:S}:null)),j;if(Array.isArray(P)&&P[0]&&typeof P[0]=="object")j=P[0];else if(P&&typeof P=="object"&&"signedMessage"in P&&"signature"in P)j=P;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)b=typeof j.signedMessage=="string"?j.signedMessage:new TextDecoder().decode(j.signedMessage),E=j.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in x)||typeof x.signMessage!="function"||!("publicKey"in x)||typeof x!="object"||!x.publicKey||!("toBase58"in x.publicKey)||typeof x.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");b=[`${q.host} wants you to sign in with your Solana account:`,x.publicKey.toBase58(),...S?["",S,""]:[""],"Version: 1",`URI: ${q.href}`,`Issued At: ${(s=(r=m?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=m?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${m.signInWithSolana.notBefore}`]:[],...!((o=m?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${m.signInWithSolana.expirationTime}`]:[],...!((l=m?.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${m.signInWithSolana.chainId}`]:[],...!((c=m?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${m.signInWithSolana.nonce}`]:[],...!((u=m?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${m.signInWithSolana.requestId}`]:[],...!((f=(h=m?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||f===void 0)&&f.length?["Resources",...m.signInWithSolana.resources.map(j=>`- ${j}`)]:[]].join(` +`);let P=await x.signMessage(new TextEncoder().encode(b),"utf8");if(!P||!(P instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=P}}try{let{data:A,error:C}=await g(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:b,signature:le(E)},!((y=e.options)===null||y===void 0)&&y.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:H});if(C)throw C;if(!A||!A.session||!A.user){let S=new ae;return this._returnResult({data:{user:null,session:null},error:S})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:C})}catch(A){if(w(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e,t){let r=t?.flowId!=null,s=r?Le(t?.flowId):K()?Le(ft(window.location.href)[oe]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",t?.flowId);let{verifier:i,flowId:o}=r&&!s?{verifier:null,flowId:null}:await rr(this.storage,this.storageKey,s),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new Be;let{data:u,error:h}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:l},xform:H});if(await Q(this.storage,this.storageKey,o),h)throw h;if(!u||!u.session||!u.user){let f=new ae;return this._returnResult({data:{user:null,session:null,redirectType:null},error:f})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:h})}catch(u){if(await Q(this.storage,this.storageKey,o),w(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:o}=e,l=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:H}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){let h=new ae;return this._returnResult({data:{user:null,session:null},error:h})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;let l=null;try{if("email"in e){let{email:c,options:u}=e,h=null,f=null;this.flowType==="pkce"&&([h,f,l]=await this._getCodeChallengeAndMethod());let{error:y}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(t=u?.data)!==null&&t!==void 0?t:{},create_user:(r=u?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:y})}if("phone"in e){let{phone:c,options:u}=e,{data:h,error:f}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(s=u?.data)!==null&&s!==void 0?s:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(o=u?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:f})}throw new we("You must provide either an email or phone number.")}catch(c){if(await Q(this.storage,this.storageKey,l),w(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:l}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:H});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(s){if(w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());let u=await g(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:this._maybeAppendFlowIdToRedirect((t=e.options)===null||t===void 0?void 0:t.redirectTo,o)}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:hr});return!((s=u.data)===null||s===void 0)&&s.url&&K()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await Q(this.storage,this.storageKey,o),w(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new D;let{error:s}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(w(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:o}=e,l=null,c=null;this.flowType==="pkce"&&([l,c,t]=await this._getCodeChallengeAndMethod());let{error:u}=await g(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t)});return u&&await Q(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){let{phone:s,type:i,options:o}=e,{data:l,error:c}=await g(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:c})}throw new we("You must provide either an email or phone number and a type")}catch(r){if(await Q(this.storage,this.storageKey,t),w(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,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await F(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let t=await F(this.userStorage,this.storageKey+"-user");e.user=t?.user?t.user:He()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=cr(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return this.lock!=null?t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):t=await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ne}):await this._useSession(async t=>{var r,s,i;let{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new D}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:ne})})}catch(t){if(w(t))return Ue(t)&&await this._removeSession(),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new D;let l=i.session,c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());let{data:h,error:f}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:ne});if(f)throw f;return l.user=h.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(s){if(await Q(this.storage,this.storageKey,r),w(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 D;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:o}=Ne(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{let{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}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 t=>{var r;if(!e){let{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new D;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!K())throw new ye("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ye(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new Ce("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ye("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ce("No code detected.");let{data:m,error:x}=await this._exchangeCodeForSession(e.code,{flowId:e[oe]});if(x)throw x;let q=new URL(window.location.href);return q.searchParams.delete("code"),q.searchParams.delete(oe),window.history.replaceState(window.history.state,"",q.toString()),{data:{session:m.session,redirectType:(r=m.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:h}=e;if(!o||!c||!l||!h)throw new ye("No session defined in URL");let f=Math.round(Date.now()/1e3),y=parseInt(c),p=f+y;u&&(p=parseInt(u));let b=p-f;b*1e3<=te&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${b}s, should have been closer to ${y}s`);let E=p-y;f-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,p,f):f-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,p,f);let{data:A,error:C}=await this._getUser(o);if(C)throw C;let S={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:y,expires_at:p,refresh_token:l,token_type:h,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:S,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=Le(e[oe]);return t&&await F(this.storage,_e(this.storageKey,t))?!0:!!await F(this.storage,`${this.storageKey}-code-verifier`)}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 t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:o}=t;if(o&&!Ue(o))return this._returnResult({error:o});let l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){let{error:c}=await this.admin.signOut(l,e);if(c&&!(ut(c)&&(c.status===404||c.status===401||c.status===403)||Ue(c)))return e!=="others"&&await s(),this._returnResult({error:c})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=Xt(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),dt(i))return;Ue(i)||je(i)||ut(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;this.flowType==="pkce"&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(o){if(await Q(this.storage,this.storageKey,i),w(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async o=>{var l,c,u,h,f;let{data:y,error:p}=o;if(p)throw p;let{url:b,flowId:E}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(l=e.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=E,await g(this.fetch,"GET",b,{headers:this.headers,jwt:(f=(h=y.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(i)throw i;return K()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:r},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:l,token:c,access_token:u,nonce:h}=e,f=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:H}),{data:y,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!y||!y.session||!y.user?this._returnResult({data:{user:null,session:null},error:new ae}):(y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("USER_UPDATED",y.session)),this._returnResult({data:y,error:p}))}catch(s){if(await Q(this.storage,this.storageKey,null),w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)throw o;return await g(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{let r=Date.now();return await er(async s=>(s>0&&await Zt(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:H})),(s,i)=>{let o=200*Math.pow(2,s);return i&&je(i)&&Date.now()+o-r{});let i=await F(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(e);if(l)throw l;if(!o.session)throw new D;let c=await F(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let y={data:null,error:new Oe};return this.refreshingDeferred.resolve(y),y}let h=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await z(this.storage,this.storageKey),this.userStorage&&await z(this.userStorage,this.storageKey+"-user");let y={data:null,error:new Oe};return this.refreshingDeferred.resolve(y),y}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let f={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(f),f}catch(i){if(this._debug(s,"error",i),w(i)){let o={data:null,error:i};if(!je(i)){let l=await F(this.storage,this.storageKey);!!(l?.expires_at&&l.expires_at*1e3>Date.now())?this._debug(s,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+qt},(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:e,session:t,broadcast:r});return}let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;lthis._autoRefreshTokenTick(),te);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/te);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${te}ms, refresh threshold is ${Ee} ticks`),s<=Ee&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof Xe)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/te);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${te}ms, refresh threshold is ${Ee} ticks`),s<=Ee&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!K()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"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(t,"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(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=r?.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,l));let c=[`provider=${encodeURIComponent(t)}`];if(s&&c.push(`redirect_to=${encodeURIComponent(s)}`),r?.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){let u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r?.queryParams){let u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r?.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:nr(e,t)}async _getCodeChallengeAndMethod(e=!1){return ir(this.storage,this.storageKey,e,t=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",t))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await g(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Rt(e.webauthn.credential_response):Et(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;let{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:kt(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:St(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&i.factor_type in s&&Array.isArray(s[i.factor_type])&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:p}=Ne(e),b=null;p.aal&&(b=p.aal);let E=b,{data:{user:A},error:C}=await this.getUser(e);if(C)return this._returnResult({data:null,error:C});((r=(t=A?.factors)===null||t===void 0?void 0:t.filter(x=>x.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(E="aal2");let m=p.amr||[];return{data:{currentLevel:b,nextLevel:E,currentAuthenticationMethods:m},error:null}}catch(p){if(w(p))return this._returnResult({data:null,error:p});throw p}let{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ne(o.access_token),u=null;c.aal&&(u=c.aal);let h=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let y=c.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:y},error:null}}async _getRecoveryCodesStatus(){Ae(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){Ae(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:o,error:l}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):this._returnResult({data:o,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verifyRecoveryCode(e){Ae(this.experimental);let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let{data:l,error:c}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(c)return this._returnResult({data:null,error:c});let u=Object.assign({expires_at:Ve(l.expires_in)},l);return await this._saveSession(u),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:l,error:null})})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){Ae(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){Ae(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await g(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new D})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new D});let o=await g(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&K()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new D});let o=await g(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&K()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await g(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new D})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await g(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new D})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+Gt>s)return r;let{data:i,error:o}=await g(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:p,error:b}=await this.getSession();if(b||!p.session)return this._returnResult({data:null,error:b});r=p.session.access_token}let{header:s,payload:i,signature:o,raw:{header:l,payload:c}}=Ne(r);if(!t?.allowExpired)try{ar(i.exp)}catch(p){throw new ue(p instanceof Error?p.message:"JWT validation failed")}let u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){let{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:s,signature:o},error:null}}let h=lr(s.alg),f=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,f,o,Yt(`${l}.${c}`)))throw new ue("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var t,r,s,i;try{if(!qe())return this._returnResult({data:null,error:new B("Browser does not support WebAuthn",null)});let{data:o,error:l}=await this._startPasskeyAuthentication({options:{captchaToken:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}});if(l||!o)return this._returnResult({data:null,error:l});let c=St(o.options),u=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:et.createNewAbortSignal(),{data:h,error:f}=await It({publicKey:c,signal:u,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(f||!h)return this._returnResult({data:null,error:f??new B("WebAuthn ceremony failed",null)});let y=Et(h);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:y})}catch(o){if(w(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var t,r;try{if(!qe())return this._returnResult({data:null,error:new B("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let o=kt(s.options),l=(r=(t=e?.options)===null||t===void 0?void 0:t.signal)!==null&&r!==void 0?r:et.createNewAbortSignal(),{data:c,error:u}=await At({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new B("WebAuthn ceremony failed",null)});let h=Rt(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new D});let{data:s,error:i}=await g(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new D});let{data:i,error:o}=await g(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;try{let{data:r,error:s}=await g(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:r}=await g(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:H});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new D});let{data:s,error:i}=await g(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new D});let{data:i,error:o}=await g(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new D});let{error:i}=await g(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}};tt.nextInstanceID={};var Tt=tt;var es=Tt,xt=es;var he=document.querySelector("#app"),Me=document.querySelector("#notice"),d={auth:null,config:null,user:null,workspaces:[],workspace:null,tab:"sessions",generation:0,conversationAgent:"",search:"",channelId:"",threadId:"",channelSearch:""},br,st=[];function Rr(){for(let n of st.splice(0))n()}var Se=new URLSearchParams(location.search);Se.has("billing")&&(d.tab="billing");var jt="agentintercom-pending",N={};try{let n=JSON.parse(sessionStorage.getItem(jt)||"{}");n.until>Date.now()&&(N=n)}catch{}Se.get("authorization_id")&&(N.authorization=Se.get("authorization_id"));var Er=new URLSearchParams(location.hash.slice(1)),kr=Er.get("invite"),Sr=Er.get("device")||Se.get("device_code");Sr&&(N.device=Sr,history.replaceState(null,"",location.pathname+location.search));kr&&(N.invite=kr,history.replaceState(null,"",location.pathname+location.search));(N.authorization||N.invite||N.device)&&sessionStorage.setItem(jt,JSON.stringify({...N,until:Date.now()+1200*1e3}));function a(n,e={},...t){let r=document.createElement(n);for(let[s,i]of Object.entries(e))i==null||i===!1||(s.startsWith("on")?r.addEventListener(s.slice(2),i):s==="class"?r.className=i:s==="text"?r.textContent=i:r.setAttribute(s,i===!0?"":String(i)));for(let s of t.flat(1/0))s!=null&&r.append(s instanceof Node?s:document.createTextNode(String(s)));return r}function Y(n,e=!1){clearTimeout(br),Me.textContent=n,Me.hidden=!1,Me.className=e?"error":"",Me.setAttribute("role",e?"alert":"status"),br=setTimeout(()=>{Me.hidden=!0},e?15e3:6e3)}async function Te(n,e){if(!n?.disabled){n&&(n.disabled=!0);try{return await e()}catch(t){Y(t.message||"Something went wrong. Please try again.",!0)}finally{n&&(n.disabled=!1)}}}function _(n,e,t=""){return a("button",{type:"button",class:t,onclick:r=>Te(r.currentTarget,e)},n)}function M(n,e={}){let t=a(e.multiline?"textarea":"input",{...e,multiline:null});return{input:t,node:a("label",{},n,t)}}function V(n,e,t){let r=a("button",{type:"submit",class:"primary"},e);return a("form",{onsubmit:s=>{s.preventDefault(),Te(r,()=>t(new FormData(s.currentTarget)))}},n,r)}var fe=()=>a("div",{class:"brand"},a("span",{class:"mark","aria-hidden":!0},"o"),"agent intercom"),J=n=>n?new Date(n).toLocaleString():"\u2014",L=n=>`/api/workspaces/${encodeURIComponent(d.workspace.id)}${n}`;async function v(n,e={}){let t={"Content-Type":"application/json"};if(d.auth&&n!=="/api/config"){let{data:i,error:o}=await d.auth.getSession();if(o)throw o;i.session&&(t.Authorization=`Bearer ${i.session.access_token}`)}let r=await fetch(n,{method:e.method||"GET",credentials:"omit",headers:t,body:e.body==null?void 0:JSON.stringify(e.body),signal:AbortSignal.timeout(e.timeout||15e3)}),s=await r.json();if(!r.ok||s.ok===!1||s.error)throw new Error(s.error?.message||"The request could not be completed. Please try again.");return s.result}async function ot(n){await navigator.clipboard.writeText(n),Y("Copied to clipboard.")}var G=new Map,$t=n=>`${d.user.id} +${d.workspace.id} +${n}`;function Ar(n){d.conversationAgent=n;let e=$t("message");G.get(e)?.body||G.delete(e)}function ts(n){if(n)for(let e of[...G.keys()])e.startsWith(n+` +`)&&G.delete(e)}async function Ir(n,e){let t=[],r=new Set,s="";for(;;){let i=await v(n+"/sessions"+(s?"?after="+encodeURIComponent(s):""));if(e.stale())break;let o=0;for(let l of i.sessions)r.has(l.id)||(r.add(l.id),t.push(l),o++);if(s=i.nextCursor,!s||!o)break}return t}function rs(n){let e=i=>{let o=new Map;for(let l of i)o.set(l,(o.get(l)||0)+1);return o},t=i=>i.deviceName===i.displayName?i.displayName:`${i.displayName} \xB7 ${i.deviceName}`,r=e(n.map(i=>i.displayName)),s=e(n.map(t));return new Map(n.map(i=>[i.id,r.get(i.displayName)===1?i.displayName:s.get(t(i))===1?t(i):`${t(i)} \xB7 ${i.id}`]))}var Ct=new WeakMap;async function Dt(n,e={}){let{data:t,error:r}=await d.auth.getSession();if(r)throw r;if(!t.session)throw new Error("Sign in again to access workspace files.");let s=await fetch(n,{...e,credentials:"omit",redirect:"error",headers:{Authorization:`Bearer ${t.session.access_token}`,"Content-Type":"application/octet-stream"},signal:AbortSignal.timeout(3e4)});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(i.error?.message||"File transfer failed. Please try again.")}return s}async function Tr(n,e){if(e.size>16*1024*1024)throw new Error("Files can be up to 16 MiB.");Ct.has(e)||Ct.set(e,crypto.randomUUID());let t=new URLSearchParams({name:e.name,mediaType:e.type.split(";")[0]||"application/octet-stream",idempotencyKey:Ct.get(e)}),s=await(await Dt(n+"/attachments?"+t,{method:"POST",body:e})).json();if(!s.ok)throw new Error(s.error?.message||"Upload failed.");return s.result}async function xr(n,e,t){let r=await Dt(n+"/attachments/"+encodeURIComponent(e)+"/content"),s=await r.arrayBuffer();if([...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(u=>u.toString(16).padStart(2,"0")).join("")!==r.headers.get("X-Content-SHA256"))throw new Error("File checksum did not match. The download was stopped.");let o=r.headers.get("Content-Disposition")||"";if(!t)try{t=decodeURIComponent(o.match(/filename\*=utf-8''([^;]+)/i)?.[1]||"")||o.match(/filename="([^"]+)"/)?.[1]||o.match(/filename=([^;]+)/)?.[1]}catch{}let l=URL.createObjectURL(new Blob([s],{type:"application/octet-stream"})),c=a("a",{href:l,download:(t||e).replace(/[\\/\x00-\x1f]/g,"_")});document.body.append(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}function Cr(n,e){let t=M("Attach a file",{type:"file"}),r=_("Upload and attach",async()=>{let s=t.input.files[0];if(!s)throw new Error("Choose a file first.");let i=t.input.closest("form")?.querySelector('[type="submit"]');i&&(i.disabled=!0);try{let o=await Tr(n,s);if(!e.isConnected){Y("File uploaded. Copy its reference from Files to share it.");return}e.value+=`${e.value?` -`:""}${o.name}: ${o.uri}`,e.dispatchEvent(new Event("input",{bubbles:!0})),t.input.value="",Y("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Or(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>v(i?`Download ${i}`:"Download shared file",()=>xr(n,s,i))))}async function ss(){let n=D(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?v("Delete file",()=>se("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),v("Delete permanently",async()=>{await k(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await O()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${V(l.createdAt)}`),a("div",{class:"actions"},v("Download",()=>xr(n,l.id,l.name)),v("Copy reference",()=>at(l.uri)),u)))}},s=await k(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=L("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},W([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await Tr(n,o),await O()})),t),s.nextCursor){let o=s.nextCursor,l=v("More files",async()=>{let c=await k(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function it(n){delete $[n],sessionStorage.setItem($t,JSON.stringify({...$,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}var ns=0;function se(n,e){let t=`modal-title-${++ns}`,r=a("dialog",{"aria-labelledby":t},a("h2",{id:t},n)),s=()=>r.close();return r.append(e(s),a("div",{class:"actions end"},v("Close",s))),r.addEventListener("close",()=>r.remove()),document.body.append(r),r.showModal(),r}function ot(n,e,t){se(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),v("Copy",()=>at(e))))}function Pt(){Rr();let n=d.user?.id;d.user=null,ts(n);let e=L("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),t=W([e.node],"Continue with email",async o=>{let{error:l}=await d.auth.signInWithOtp({email:o.get("email"),options:{emailRedirectTo:location.origin+"/app"+($.authorization?"?authorization_id="+encodeURIComponent($.authorization):$.device?"?device_code="+encodeURIComponent($.device):""),shouldCreateUser:!0}});if(l)throw l;Y("Check your email for an October sign-in link. Open it in this browser."),t.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),r=L("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),s=L("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),i=W([r.node,s.node],"Sign in",async o=>{let{error:l}=await d.auth.signInWithPassword({email:o.get("email"),password:o.get("password")});if(l)throw l;await Q()});ue.replaceChildren(a("main",{id:"main",class:"auth-wrap"},de(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. -A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),t,a("details",{},a("summary",{},"Use an existing password"),i),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function Q(){d.user=await k("/api/me"),d.workspaces=await k("/api/workspaces");let n=be.has("billing")&&be.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,$.invite)return is();if($.authorization)return Ut();if($.device)return jt();if(!d.workspace)return Pr();await O()}function lt(n){let e=L("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return W([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await k("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Pr(){ue.replaceChildren(a("main",{id:"main",class:"auth-wrap"},de(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),lt(O),v("Sign out",Nt))))}async function Nt(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,Pt()}function Lt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Ie(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function Ut(){let n=await k(`/api/oauth/requests/${encodeURIComponent($.authorization)}`),e=d.workspace?.id,r=(e?await k(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await k(`/api/oauth/requests/${encodeURIComponent($.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});it("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Lt(Ut)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},v("Allow connection",()=>o(!0),"primary"),v("Cancel",()=>o(!1)))):lt(Ut);ue.replaceChildren(a("main",{id:"main",class:"consent"},de(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function jt(){let n=await k(`/api/device/authorizations/${encodeURIComponent($.device)}`),e=d.workspace?.id,r=(e?await k(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await k(`/api/device/authorizations/${encodeURIComponent($.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),it("device"),ue.replaceChildren(a("main",{id:"main",class:"consent"},de(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),v("Open workspace",Q,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Lt(jt)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},v("Connect this device",()=>o(!0),"primary"),v("Decline",()=>o(!1)))):lt(jt);ue.replaceChildren(a("main",{id:"main",class:"consent"},de(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function is(){ue.replaceChildren(a("main",{id:"main",class:"consent"},de(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},v("Accept invitation",async()=>{let n=await k("/api/invites/accept",{method:"POST",body:{token:$.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),it("invite"),await Q()},"primary"),v("Use another account",Nt),v("Cancel",async()=>{it("invite"),await Q()})))))}var rt={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function O(){if(Rr(),!d.workspace)return Pr();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(rt).map(([s,[i]])=>v(i,async()=>{d.tab=s,await O()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(rt)[i]===d.tab&&s.setAttribute("aria-current","page")}),ue.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},de(),a("div",{class:"workspace-switch"},Lt(O),v("+ New workspace",()=>se("New workspace",s=>lt(async()=>{s(),await O()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),v("Sign out",Nt,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},rt[d.tab][0]),a("p",{class:"muted"},rt[d.tab][1])),d.tab==="sessions"?v("Connect an app",async()=>{d.tab="connect",await O()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:ws,billing:ps,files:ss,channels:fs,messages:us,tasks:ds,questions:hs,sessions:os,connect:as,members:ls}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),v("Try again",O)))}}async function os(){let n=a("div"),e=a("div",{class:"grid"}),t=await k(D("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${V(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},v("Open conversation",async()=>{d.conversationAgent=i.id,d.tab="messages",await O()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),v("Copy session ID",()=>at(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),v("Connect an app",async()=>{d.tab="connect",await O()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=v("Show more sessions",async()=>{let o=await k(D("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),v("Refresh sessions",O)),n}function as(){let n=d.config.mcpUrl,e=D("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),v("Copy connector URL",()=>at(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),W([L("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await k(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});ot("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${V(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default -agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),W([L("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await k(D("/devices"),{method:"POST",body:{name:t.get("name")}});ot("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function ls(){let n=D(""),[e,t]=await Promise.all([k(D("/members")),k(D("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,v("Save role",async()=>{await k(D(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await Q()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(v(l.userId===d.user.id?"Leave":"Remove",()=>se("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),v("Remove access",async()=>{await k(D(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await Q()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${V(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(v("Replace key",()=>se("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),v("Create replacement key",async()=>{let f=await k(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),ot("Replacement MCP key",f.token,`Update your app\u2019s secret/API key field. Shown once; expires ${V(f.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(v("Revoke",()=>se("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),v("Revoke connection",async()=>{await k(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await O()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${V(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=L("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=W([l.node],"Create invitation",async f=>{let y=await k(D("/invites"),{method:"POST",body:{email:f.get("email"),role:"member"}});ot("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(y.token)}`,`Share this link with ${y.email}. It expires ${V(y.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await k(D("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let f of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},f.email),a("p",{class:"help"},`Expires ${V(f.expiresAt)}`)),v("Revoke invitation",async()=>{await k(D(`/invites/${encodeURIComponent(f.id)}`),{method:"DELETE"}),await O()},"danger")));o.append(h)}return o}async function cs(){if(d.config=await k("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new Ct({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await Q():Pt(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,Pt()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Ie(null,Q),0)})}cs().catch(n=>{ue.replaceChildren(a("main",{id:"main",class:"auth-wrap"},de(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),v("Try again",()=>location.reload()))))});async function us(){let n=d.generation,e=D(""),t=d.workspace.id,r={stale:()=>n!==d.generation||d.workspace?.id!==t},[s,i]=await Promise.all([Ir(e,r),k(e+"/members")]),o=rs(s),l=new Map(s.map(_=>["agent:"+_.id,_.displayName]));for(let _ of i)l.set("human:"+_.userId,_.email);let c=(_,N)=>l.get(_+":"+N)||N,u=new URLSearchParams;d.conversationAgent&&u.set("agentId",d.conversationAgent),d.search&&u.set("query",d.search);let h=a("select",{"aria-label":"Filter by session",onchange:_=>{d.conversationAgent=_.target.value,Ie(null,O)}},a("option",{value:""},"All sessions"),s.map(_=>a("option",{value:_.id,selected:_.id===d.conversationAgent},o.get(_.id)))),f=L("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),y=W([f.node],"Search",async _=>{d.search=_.get("query").trim(),await O()}),p=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",h),y)),S=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),E=new Map,A=!0,x=!1;st.push(()=>{A=!1});let R=_=>_.responseMessageId?"Replied":_.state==="acknowledged"?_.toKind==="human"?"Read":"Acknowledged":_.state==="delivered"?"Delivered to app":_.state==="expired"?"Expired":"Waiting for delivery",m=(_,N=!1)=>{let b=N?[..._.messages].reverse():_.messages;for(let I of b){let X=JSON.stringify(I),T=E.get(I.id);if(T?.fingerprint===X)continue;let B=a("article",{class:"card",id:I.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},c(I.fromKind,I.from))," \u2192 ",c(I.toKind,I.to),a("p",{class:"help"},V(I.createdAt))),a("span",{class:"badge"},R(I))),a("p",{class:"message"},I.body));B.append(Or(e,I.body,I.context)),I.responseTo&&B.append(a("p",{class:"help"},"Reply to ",a("code",{},I.responseTo))),I.toKind==="human"&&I.to===d.user.id&&I.state!=="acknowledged"&&I.state!=="expired"&&B.append(v("Mark read",async()=>{await k(e+"/messages/read",{method:"POST",body:{messageIds:[I.id]}}),await O()},"subtle-button")),T?T.node.replaceWith(B):N?S.prepend(B):S.append(B),E.set(I.id,{fingerprint:X,node:B})}},P=await k(e+"/messages?"+u);m(P);let M=u.toString(),C=setInterval(async()=>{if(d.generation!==n){clearInterval(C);return}if(!(!A||x||document.hidden)){x=!0;try{let _=await k(e+"/messages?"+M);A&&(_.messages.length&&S.querySelector(".empty")?.remove(),m(_,!0))}catch(_){A&&Y("Conversation refresh failed. "+_.message,!0)}finally{x=!1}}},5e3);if(st.push(()=>clearInterval(C)),P.messages.length||S.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),p.append(S),P.nextCursor){let _=P.nextCursor,N=v("Earlier messages",async()=>{u.set("before",_);let b=await k(e+"/messages?"+u);m(b),_=b.nextCursor,_||N.remove()});p.append(N)}if(s.length){let _=a("select",{name:"to",required:!0},s.map(T=>a("option",{value:T.id,selected:T.id===d.conversationAgent},o.get(T.id)+(T.reachable?"":" \xB7 offline")))),N=L("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),b=Ae("message");b?.body&&(N.input.value=b.body),b?.to&&s.some(T=>T.id===b.to)&&(_.value=b.to);let I=()=>{let T=JSON.stringify([_.value,N.input.value]),B=Ae("message");nt("message",{to:_.value,body:N.input.value,fingerprint:T,key:B?.fingerprint===T?B.key:crypto.randomUUID()})};_.addEventListener("change",I),N.input.addEventListener("input",I);let X=W([a("label",{},"Send to",_),N.node,Cr(e,N.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async T=>{I();let B=Ae("message");await k(e+"/messages",{method:"POST",body:{to:T.get("to"),body:T.get("body"),mode:"request",idempotencyKey:B.key}}),nt("message",null),d.conversationAgent=T.get("to"),d.search="",Y("Request saved. Delivery status will update when the app checks its inbox."),await O()});p.append(a("section",{class:"card"},a("h2",{},"Send a message"),X))}else p.append(v("Connect an app",async()=>{d.tab="connect",await O()},"primary"));return p.append(v("Refresh conversation",O)),p}async function ds(){let n=D(""),e=await k(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},V(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=v("More tasks",async()=>{let u=await k(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=L("Task title",{name:"title",maxlength:256,required:!0}),o=L("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),W([i.node,o.node],"Create task",async l=>{await k(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),Y("Task created. An agent can now claim it."),await O()}))),t}async function hs(){let n=D(""),e=await k(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=L("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>v(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",V(i.createdAt)),a("div",{class:"actions"},l),W([o.node],"Send answer",async c=>{await k(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),Y("Answer saved for the requesting session."),await O()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=v("More questions",async()=>{let o=await k(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(v("Refresh questions",O)),t}async function fs(){let n=d.generation,e=D(""),t=await k(e+"/channels"),r=t.find(b=>b.id===d.channelId)||t[0];r?.id!==d.channelId&&(d.threadId=""),d.channelId=r?.id||"";let s=()=>se("Create a channel",b=>W([L("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,L("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async I=>{let X=await k(e+"/channels",{method:"POST",body:{name:I.get("name"),description:I.get("description")}});d.channelId=X.id,d.threadId="",d.channelSearch="",b(),await O()}));if(!r)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),v("Create a channel",s,"primary"));let i=a("select",{"aria-label":"Channel",onchange:b=>{d.channelId=b.target.value,d.threadId="",d.channelSearch="",Ie(null,O)}},t.map(b=>a("option",{value:b.id,selected:b.id===r.id},"#"+b.name))),o=W([L("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async b=>{d.channelSearch=b.get("query").trim(),d.threadId="",await O()}),l=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",i),v("New channel",s)),a("p",{},r.description),a("p",{class:"help"},`${r.subscribers} subscribed sessions. Ask a connected session to join #${r.name} using subscribe_channel to receive future notifications.`),o));d.threadId&&l.append(a("div",{class:"actions"},a("h2",{},"Thread"),v("Back to channel",async()=>{d.threadId="",await O()})));let c=new URLSearchParams({channelId:r.id});d.threadId&&c.set("threadId",d.threadId),d.channelSearch&&c.set("query",d.channelSearch);let u=d.workspace.id,h={stale:()=>n!==d.generation||d.workspace?.id!==u},[f,y,p]=await Promise.all([k(e+"/channel-posts?"+c),k(e+"/members"),Ir(e,h)]),S=new Map(y.map(b=>["human:"+b.userId,b.email]));for(let b of p)S.set("agent:"+b.id,b.displayName);let E=a("div",{class:"conversation-list","aria-label":"Channel posts"}),A=new Map,x=(b,I=!1)=>{let X=I?[...b.posts].reverse():b.posts;for(let T of X){let B=JSON.stringify(T),ct=A.get(T.id);if(ct?.fingerprint===B)continue;let ke=a("article",{class:"card"},a("div",{class:"row"},a("strong",{},S.get(T.authorKind+":"+T.authorId)||T.authorId),a("small",{},V(T.createdAt))),a("p",{class:"message"},T.body));ke.append(Or(e,T.body)),(!d.threadId||d.channelSearch)&&ke.append(v(T.replies?`${T.replies} ${T.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=T.threadId||T.id,d.channelSearch="",await O()})),ct?ct.node.replaceWith(ke):I?E.prepend(ke):E.append(ke),A.set(T.id,{fingerprint:B,node:ke})}};if(x(f),f.posts.length||E.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),l.append(E),f.nextCursor){let b=f.nextCursor,I=v("Earlier posts",async()=>{let X=new URLSearchParams(c);X.set("before",b);let T=await k(e+"/channel-posts?"+X);x(T),b=T.nextCursor,b||I.remove()});l.append(I)}let R=L(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),m=`channel -${r.id} -${d.threadId||""}`,P=Ae(m);P?.body&&(R.input.value=P.body);let M=()=>{let b=Ae(m);nt(m,{body:R.input.value,key:b?.body===R.input.value&&b.key?b.key:crypto.randomUUID()})};R.input.addEventListener("input",M),l.append(a("section",{class:"card"},W([R.node,Cr(e,R.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async b=>{M();let I=Ae(m);await k(e+"/channel-posts",{method:"POST",body:{channelId:r.id,body:b.get("body"),threadId:d.threadId||void 0,idempotencyKey:I.key}}),nt(m,null),d.channelSearch="",await O()})));let C=!0,_=!1,N=setInterval(async()=>{if(d.generation!==n){clearInterval(N);return}if(!(!C||_||document.hidden)){_=!0;try{let b=await k(e+"/channel-posts?"+c);C&&(b.posts.length&&E.querySelector(".empty")?.remove(),x(b,!0))}catch(b){C&&Y("Channel refresh failed. "+b.message,!0)}finally{_=!1}}},5e3);return st.push(()=>{C=!1,clearInterval(N)}),l}async function ps(){let n=D("/billing"),e=await k(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=f=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(f/100),i=f=>f>=1024**3?`${(f/1024**3).toFixed(1)} GiB`:`${(f/1024**2).toFixed(1)} MiB`,o=f=>Number(f).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),be.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${V(e.paidUntil)}.`:r?`Trial ends ${V(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${V(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(f,y){let p=await k(n+"/"+f,{method:"POST",body:y,timeout:3e4}),S=new URL(p.url);if(S.protocol!=="https:"||S.username||S.password||!["checkout.stripe.com","billing.stripe.com"].includes(S.host))throw new Error("Payment destination could not be verified.");location.assign(S.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(v(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),v(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(v("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(v("Check payment status",async()=>{await k(n+"/refresh",{method:"POST",timeout:3e4}),await O(),Y("Payment status checked.")})),e.pendingCheckout&&c.append(v("Close unfinished checkout",async()=>{await k(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await O()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[f,y,p,S]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},f),a("span",{},`${S(y)} / ${S(p)}`)),a("progress",{max:p,value:Math.min(y,p),"aria-label":f})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ws(){let n=D(""),e=d.workspace,t=await k(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),v(d.workspace.paused?"Resume sessions":"Pause sessions",()=>se(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),v("Confirm",async()=>{await k(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await Q()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),v("Download workspace archive",async()=>{let l=await(await Dt(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=L("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),W([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await k(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});se("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),v("Delete eligible history",async()=>{await k(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await O(),Y("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),v(e.deleting?"Retry workspace deletion":"Delete workspace",()=>se("Permanently delete this workspace?",o=>{let l=L("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),W([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await k(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await Q(),u}o(),await Q(),Y("Workspace deleted.")}))}),"danger"))),s} +`:""}${o.name}: ${o.uri}`,e.dispatchEvent(new Event("input",{bubbles:!0})),t.input.value="",Y("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Or(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>_(i?`Download ${i}`:"Download shared file",()=>xr(n,s,i))))}async function ss(){let n=L(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?_("Delete file",()=>ie("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),_("Delete permanently",async()=>{await v(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await O()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${J(l.createdAt)}`),a("div",{class:"actions"},_("Download",()=>xr(n,l.id,l.name)),_("Copy reference",()=>ot(l.uri)),u)))}},s=await v(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=M("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},V([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await Tr(n,o),await O()})),t),s.nextCursor){let o=s.nextCursor,l=_("More files",async()=>{let c=await v(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function nt(n){delete N[n],sessionStorage.setItem(jt,JSON.stringify({...N,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}var ns=0;function ie(n,e){let t=`modal-title-${++ns}`,r=a("dialog",{"aria-labelledby":t},a("h2",{id:t},n)),s=()=>r.close();return r.append(e(s),a("div",{class:"actions end"},_("Close",s))),r.addEventListener("close",()=>r.remove()),document.body.append(r),r.showModal(),r}function it(n,e,t){ie(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),_("Copy",()=>ot(e))))}function Ot(){Rr();let n=d.user?.id;d.user=null,ts(n);let e=M("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),t=V([e.node],"Continue with email",async o=>{let{error:l}=await d.auth.signInWithOtp({email:o.get("email"),options:{emailRedirectTo:location.origin+"/app"+(N.authorization?"?authorization_id="+encodeURIComponent(N.authorization):N.device?"?device_code="+encodeURIComponent(N.device):""),shouldCreateUser:!0}});if(l)throw l;Y("Check your email for an October sign-in link. Open it in this browser."),t.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),r=M("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),s=M("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),i=V([r.node,s.node],"Sign in",async o=>{let{error:l}=await d.auth.signInWithPassword({email:o.get("email"),password:o.get("password")});if(l)throw l;await ee()});he.replaceChildren(a("main",{id:"main",class:"auth-wrap"},fe(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. +A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),t,a("details",{},a("summary",{},"Use an existing password"),i),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function ee(){d.user=await v("/api/me"),d.workspaces=await v("/api/workspaces");let n=Se.has("billing")&&Se.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,N.invite)return is();if(N.authorization)return Pt();if(N.device)return Ut();if(!d.workspace)return Pr();await O()}function at(n){let e=M("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return V([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await v("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Pr(){he.replaceChildren(a("main",{id:"main",class:"auth-wrap"},fe(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),at(O),_("Sign out",Nt))))}async function Nt(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,Ot()}function Lt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Te(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function Pt(){let n=await v(`/api/oauth/requests/${encodeURIComponent(N.authorization)}`),e=d.workspace?.id,r=(e?await v(L("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await v(`/api/oauth/requests/${encodeURIComponent(N.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});nt("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Lt(Pt)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},_("Allow connection",()=>o(!0),"primary"),_("Cancel",()=>o(!1)))):at(Pt);he.replaceChildren(a("main",{id:"main",class:"consent"},fe(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function Ut(){let n=await v(`/api/device/authorizations/${encodeURIComponent(N.device)}`),e=d.workspace?.id,r=(e?await v(L("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await v(`/api/device/authorizations/${encodeURIComponent(N.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),nt("device"),he.replaceChildren(a("main",{id:"main",class:"consent"},fe(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),_("Open workspace",ee,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Lt(Ut)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},_("Connect this device",()=>o(!0),"primary"),_("Decline",()=>o(!1)))):at(Ut);he.replaceChildren(a("main",{id:"main",class:"consent"},fe(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function is(){he.replaceChildren(a("main",{id:"main",class:"consent"},fe(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},_("Accept invitation",async()=>{let n=await v("/api/invites/accept",{method:"POST",body:{token:N.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),nt("invite"),await ee()},"primary"),_("Use another account",Nt),_("Cancel",async()=>{nt("invite"),await ee()})))))}var rt={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function O(){if(Rr(),!d.workspace)return Pr();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(rt).map(([s,[i]])=>_(i,async()=>{d.tab=s,await O()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(rt)[i]===d.tab&&s.setAttribute("aria-current","page")}),he.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},fe(),a("div",{class:"workspace-switch"},Lt(O),_("+ New workspace",()=>ie("New workspace",s=>at(async()=>{s(),await O()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),_("Sign out",Nt,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},rt[d.tab][0]),a("p",{class:"muted"},rt[d.tab][1])),d.tab==="sessions"?_("Connect an app",async()=>{d.tab="connect",await O()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:ws,billing:ps,files:ss,channels:fs,messages:us,tasks:ds,questions:hs,sessions:os,connect:as,members:ls}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),_("Try again",O)))}}async function os(){let n=a("div"),e=a("div",{class:"grid"}),t=await v(L("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${J(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},_("Open conversation",async()=>{Ar(i.id),d.tab="messages",await O()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),_("Copy session ID",()=>ot(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),_("Connect an app",async()=>{d.tab="connect",await O()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=_("Show more sessions",async()=>{let o=await v(L("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),_("Refresh sessions",O)),n}function as(){let n=d.config.mcpUrl,e=L("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),_("Copy connector URL",()=>ot(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),V([M("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await v(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});it("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${J(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default +agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),V([M("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await v(L("/devices"),{method:"POST",body:{name:t.get("name")}});it("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function ls(){let n=L(""),[e,t]=await Promise.all([v(L("/members")),v(L("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await v(L(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await ee()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>ie("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await v(L(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await ee()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${J(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>ie("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let f=await v(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),it("Replacement MCP key",f.token,`Update your app\u2019s secret/API key field. Shown once; expires ${J(f.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>ie("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await v(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await O()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${J(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=M("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=V([l.node],"Create invitation",async f=>{let y=await v(L("/invites"),{method:"POST",body:{email:f.get("email"),role:"member"}});it("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(y.token)}`,`Share this link with ${y.email}. It expires ${J(y.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await v(L("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let f of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},f.email),a("p",{class:"help"},`Expires ${J(f.expiresAt)}`)),_("Revoke invitation",async()=>{await v(L(`/invites/${encodeURIComponent(f.id)}`),{method:"DELETE"}),await O()},"danger")));o.append(h)}return o}async function cs(){if(d.config=await v("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new xt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await ee():Ot(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,Ot()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Te(null,ee),0)})}cs().catch(n=>{he.replaceChildren(a("main",{id:"main",class:"auth-wrap"},fe(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});async function us(){let n=d.generation,e=L(""),t=$t("message"),r=d.workspace.id,s={stale:()=>n!==d.generation||d.workspace?.id!==r},[i,o]=await Promise.all([Ir(e,s),v(e+"/members")]),l=rs(i),c=new Map(i.map(R=>["agent:"+R.id,R.displayName]));for(let R of o)c.set("human:"+R.userId,R.email);let u=(R,U)=>c.get(R+":"+U)||U,h=new URLSearchParams;d.conversationAgent&&h.set("agentId",d.conversationAgent),d.search&&h.set("query",d.search);let f=a("select",{"aria-label":"Filter by session",onchange:R=>{Ar(R.target.value),Te(null,O)}},a("option",{value:""},"All sessions"),i.map(R=>a("option",{value:R.id,selected:R.id===d.conversationAgent},l.get(R.id)))),y=M("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),p=V([y.node],"Search",async R=>{d.search=R.get("query").trim(),await O()}),b=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",f),p)),E=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),A=new Map,C=!0,S=!1;st.push(()=>{C=!1});let m=R=>R.responseMessageId?"Replied":R.state==="acknowledged"?R.toKind==="human"?"Read":"Acknowledged":R.state==="delivered"?"Delivered to app":R.state==="expired"?"Expired":"Waiting for delivery",x=(R,U=!1)=>{let k=U?[...R.messages].reverse():R.messages;for(let T of k){let Z=JSON.stringify(T),I=A.get(T.id);if(I?.fingerprint===Z)continue;let W=a("article",{class:"card",id:T.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},u(T.fromKind,T.from))," \u2192 ",u(T.toKind,T.to),a("p",{class:"help"},J(T.createdAt))),a("span",{class:"badge"},m(T))),a("p",{class:"message"},T.body));W.append(Or(e,T.body,T.context)),T.responseTo&&W.append(a("p",{class:"help"},"Reply to ",a("code",{},T.responseTo))),T.toKind==="human"&&T.to===d.user.id&&T.state!=="acknowledged"&&T.state!=="expired"&&W.append(_("Mark read",async()=>{await v(e+"/messages/read",{method:"POST",body:{messageIds:[T.id]}}),await O()},"subtle-button")),I?I.node.replaceWith(W):U?E.prepend(W):E.append(W),A.set(T.id,{fingerprint:Z,node:W})}},q=await v(e+"/messages?"+h);x(q);let P=h.toString(),j=setInterval(async()=>{if(d.generation!==n){clearInterval(j);return}if(!(!C||S||document.hidden)){S=!0;try{let R=await v(e+"/messages?"+P);C&&(R.messages.length&&E.querySelector(".empty")?.remove(),x(R,!0))}catch(R){C&&Y("Conversation refresh failed. "+R.message,!0)}finally{S=!1}}},5e3);if(st.push(()=>clearInterval(j)),q.messages.length||E.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),b.append(E),q.nextCursor){let R=q.nextCursor,U=_("Earlier messages",async()=>{h.set("before",R);let k=await v(e+"/messages?"+h);x(k),R=k.nextCursor,R||U.remove()});b.append(U)}if(i.length){let R=a("select",{name:"to",required:!0},i.map(I=>a("option",{value:I.id,selected:I.id===d.conversationAgent},l.get(I.id)+(I.reachable?"":" \xB7 offline")))),U=M("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),k=G.get(t);k?.body&&(U.input.value=k.body),k?.body&&k.to&&!i.some(I=>I.id===k.to)?(R.prepend(a("option",{value:""},"Recipient unavailable \u2014 choose a session")),R.value=""):k?.to&&i.some(I=>I.id===k.to)&&(R.value=k.to);let T=()=>{let I=JSON.stringify([R.value,U.input.value]),W=G.get(t);G.set(t,{to:R.value,body:U.input.value,fingerprint:I,key:W?.fingerprint===I?W.key:crypto.randomUUID()})};R.addEventListener("change",T),U.input.addEventListener("input",T);let Z=V([a("label",{},"Send to",R),U.node,Cr(e,U.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async I=>{T();let{key:W}=G.get(t);await v(e+"/messages",{method:"POST",body:{to:I.get("to"),body:I.get("body"),mode:"request",idempotencyKey:W}}),G.get(t)?.key===W&&G.delete(t),d.conversationAgent=I.get("to"),d.search="",Y("Request saved. Delivery status will update when the app checks its inbox."),await O()});b.append(a("section",{class:"card"},a("h2",{},"Send a message"),Z))}else b.append(_("Connect an app",async()=>{d.tab="connect",await O()},"primary"));return b.append(_("Refresh conversation",O)),b}async function ds(){let n=L(""),e=await v(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},J(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await v(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=M("Task title",{name:"title",maxlength:256,required:!0}),o=M("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),V([i.node,o.node],"Create task",async l=>{await v(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),Y("Task created. An agent can now claim it."),await O()}))),t}async function hs(){let n=L(""),e=await v(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=M("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",J(i.createdAt)),a("div",{class:"actions"},l),V([o.node],"Send answer",async c=>{await v(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),Y("Answer saved for the requesting session."),await O()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await v(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",O)),t}async function fs(){let n=d.generation,e=L(""),t=$t("channel"),r=await v(e+"/channels"),s=r.find(k=>k.id===d.channelId)||r[0];s?.id!==d.channelId&&(d.threadId=""),d.channelId=s?.id||"";let i=()=>ie("Create a channel",k=>V([M("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,M("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async T=>{let Z=await v(e+"/channels",{method:"POST",body:{name:T.get("name"),description:T.get("description")}});d.channelId=Z.id,d.threadId="",d.channelSearch="",k(),await O()}));if(!s)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",i,"primary"));let o=a("select",{"aria-label":"Channel",onchange:k=>{d.channelId=k.target.value,d.threadId="",d.channelSearch="",Te(null,O)}},r.map(k=>a("option",{value:k.id,selected:k.id===s.id},"#"+k.name))),l=V([M("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async k=>{d.channelSearch=k.get("query").trim(),d.threadId="",await O()}),c=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",o),_("New channel",i)),a("p",{},s.description),a("p",{class:"help"},`${s.subscribers} subscribed sessions. Ask a connected session to join #${s.name} using subscribe_channel to receive future notifications.`),l));d.threadId&&c.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await O()})));let u=new URLSearchParams({channelId:s.id});d.threadId&&u.set("threadId",d.threadId),d.channelSearch&&u.set("query",d.channelSearch);let h=d.workspace.id,f={stale:()=>n!==d.generation||d.workspace?.id!==h},[y,p,b]=await Promise.all([v(e+"/channel-posts?"+u),v(e+"/members"),Ir(e,f)]),E=new Map(p.map(k=>["human:"+k.userId,k.email]));for(let k of b)E.set("agent:"+k.id,k.displayName);let A=a("div",{class:"conversation-list","aria-label":"Channel posts"}),C=new Map,S=(k,T=!1)=>{let Z=T?[...k.posts].reverse():k.posts;for(let I of Z){let W=JSON.stringify(I),lt=C.get(I.id);if(lt?.fingerprint===W)continue;let Re=a("article",{class:"card"},a("div",{class:"row"},a("strong",{},E.get(I.authorKind+":"+I.authorId)||I.authorId),a("small",{},J(I.createdAt))),a("p",{class:"message"},I.body));Re.append(Or(e,I.body)),(!d.threadId||d.channelSearch)&&Re.append(_(I.replies?`${I.replies} ${I.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=I.threadId||I.id,d.channelSearch="",await O()})),lt?lt.node.replaceWith(Re):T?A.prepend(Re):A.append(Re),C.set(I.id,{fingerprint:W,node:Re})}};if(S(y),y.posts.length||A.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),c.append(A),y.nextCursor){let k=y.nextCursor,T=_("Earlier posts",async()=>{let Z=new URLSearchParams(u);Z.set("before",k);let I=await v(e+"/channel-posts?"+Z);S(I),k=I.nextCursor,k||T.remove()});c.append(T)}let m=M(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),x=t+` +${s.id} +${d.threadId||""}`,q=G.get(x);q?.body&&(m.input.value=q.body);let P=()=>{let k=G.get(x);G.set(x,{body:m.input.value,key:k?.body===m.input.value&&k.key?k.key:crypto.randomUUID()})};m.input.addEventListener("input",P),c.append(a("section",{class:"card"},V([m.node,Cr(e,m.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async k=>{P();let{key:T}=G.get(x);await v(e+"/channel-posts",{method:"POST",body:{channelId:s.id,body:k.get("body"),threadId:d.threadId||void 0,idempotencyKey:T}}),G.get(x)?.key===T&&G.delete(x),d.channelSearch="",await O()})));let j=!0,R=!1,U=setInterval(async()=>{if(d.generation!==n){clearInterval(U);return}if(!(!j||R||document.hidden)){R=!0;try{let k=await v(e+"/channel-posts?"+u);j&&(k.posts.length&&A.querySelector(".empty")?.remove(),S(k,!0))}catch(k){j&&Y("Channel refresh failed. "+k.message,!0)}finally{R=!1}}},5e3);return st.push(()=>{j=!1,clearInterval(U)}),c}async function ps(){let n=L("/billing"),e=await v(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=f=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(f/100),i=f=>f>=1024**3?`${(f/1024**3).toFixed(1)} GiB`:`${(f/1024**2).toFixed(1)} MiB`,o=f=>Number(f).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),Se.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${J(e.paidUntil)}.`:r?`Trial ends ${J(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${J(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(f,y){let p=await v(n+"/"+f,{method:"POST",body:y,timeout:3e4}),b=new URL(p.url);if(b.protocol!=="https:"||b.username||b.password||!["checkout.stripe.com","billing.stripe.com"].includes(b.host))throw new Error("Payment destination could not be verified.");location.assign(b.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await v(n+"/refresh",{method:"POST",timeout:3e4}),await O(),Y("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await v(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await O()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[f,y,p,b]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},f),a("span",{},`${b(y)} / ${b(p)}`)),a("progress",{max:p,value:Math.min(y,p),"aria-label":f})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ws(){let n=L(""),e=d.workspace,t=await v(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>ie(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await v(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await ee()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Dt(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=M("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),V([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await v(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});ie("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await v(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await O(),Y("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>ie("Permanently delete this workspace?",o=>{let l=M("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),V([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await v(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await ee(),u}o(),await ee(),Y("Workspace deleted.")}))}),"danger"))),s} diff --git a/web/src/app.js b/web/src/app.js index aa36ac1..a215fff 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -66,29 +66,27 @@ async function api(url, options = {}) { async function copy(value) { await navigator.clipboard.writeText(value); inform('Copied to clipboard.'); } const drafts = new Map(); -const draftScope = () => `${state.user?.id || ''}\n${state.workspace?.id || ''}`; -const getDraft = key => drafts.get(draftScope() + '\n' + key); -const setDraft = (key, value) => { const mapKey = draftScope() + '\n' + key; if (value == null) drafts.delete(mapKey); else drafts.set(mapKey, value); }; +const draftKey = name => `${state.user.id}\n${state.workspace.id}\n${name}`; +function openConversation(id) { state.conversationAgent = id; const key = draftKey('message'); if (!drafts.get(key)?.body) drafts.delete(key); } function forgetDraftsFor(userId) { if (!userId) return; for (const key of [...drafts.keys()]) if (key.startsWith(userId + '\n')) drafts.delete(key); } async function fetchSessions(scopePath, token) { const sessions = [], seen = new Set(); let cursor = ''; - for (let pages = 0; ; pages++) { + for (;;) { const page = await api(scopePath + '/sessions' + (cursor ? '?after=' + encodeURIComponent(cursor) : '')); if (token.stale()) break; - for (const session of page.sessions) if (!seen.has(session.id)) { seen.add(session.id); sessions.push(session); } + let added = 0; + for (const session of page.sessions) if (!seen.has(session.id)) { seen.add(session.id); sessions.push(session); added++; } cursor = page.nextCursor; - if (!cursor || pages + 1 >= 50) break; + if (!cursor || !added) break; } return sessions; } function sessionLabels(sessions) { - const counts = new Map(); - for (const session of sessions) { const name = session.displayName || session.agentId || session.id; counts.set(name, (counts.get(name) || 0) + 1); } - return new Map(sessions.map(session => { - const name = session.displayName || session.agentId || session.id; - return [session.id, counts.get(name) > 1 ? `${name} · ${session.deviceName || session.id}` : name]; - })); + const tally = labels => { const counts = new Map(); for (const label of labels) counts.set(label, (counts.get(label) || 0) + 1); return counts; }; + const onDevice = s => s.deviceName === s.displayName ? s.displayName : `${s.displayName} · ${s.deviceName}`; + const names = tally(sessions.map(s => s.displayName)), devices = tally(sessions.map(onDevice)); + return new Map(sessions.map(s => [s.id, names.get(s.displayName) === 1 ? s.displayName : devices.get(onDevice(s)) === 1 ? onDevice(s) : `${onDevice(s)} · ${s.id}`])); } const uploadKeys = new WeakMap(); @@ -122,7 +120,7 @@ function attachmentPicker(scopePath, textInput) { const attach = button('Upload and attach', async () => { const selected = file.input.files[0]; if (!selected) throw new Error('Choose a file first.'); const submit = file.input.closest('form')?.querySelector('[type="submit"]'); if (submit) submit.disabled = true; - try { const uploaded = await uploadFile(scopePath, selected); textInput.value += `${textInput.value ? '\n\n' : ''}${uploaded.name}: ${uploaded.uri}`; textInput.dispatchEvent(new Event('input', { bubbles: true })); file.input.value = ''; inform('File attached. Send your message to share the reference.'); } + try { const uploaded = await uploadFile(scopePath, selected); if (!textInput.isConnected) { inform('File uploaded. Copy its reference from Files to share it.'); return; } textInput.value += `${textInput.value ? '\n\n' : ''}${uploaded.name}: ${uploaded.uri}`; textInput.dispatchEvent(new Event('input', { bubbles: true })); file.input.value = ''; inform('File attached. Send your message to share the reference.'); } finally { if (submit) submit.disabled = false; } }); return el('details', {}, el('summary', {}, 'Attach a file'), file.node, attach, el('p', { class: 'help' }, 'Up to 16 MiB. Uploaded files are visible to everyone in this workspace.')); @@ -276,7 +274,7 @@ async function sessionsView() { const append = data => { for (const session of data.sessions) { const online = session.reachable === true; - list.append(el('article', { class: 'card' }, el('div', { class: 'actions' }, el('h2', {}, session.displayName || session.agentId || session.id), el('span', { class: `badge ${online ? 'live' : ''}` }, online ? 'Connected' : 'Offline')), el('p', { class: 'help' }, session.deviceName), el('p', { class: 'help' }, session.deliveryMode === 'poll' ? 'Inbox available when this app checks for messages. It may need you to resume the conversation.' : 'Native listener connected. Your app’s permissions still apply.'), el('small', {}, `Last seen ${date(session.updatedAt)}`), session.wake?.uncertain ? el('p', { class: 'notice-inline' }, 'A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox.') : null, el('div', { class: 'actions' }, button('Open conversation', async () => { state.conversationAgent = session.id; state.tab = 'messages'; await render(); })))); + list.append(el('article', { class: 'card' }, el('div', { class: 'actions' }, el('h2', {}, session.displayName || session.agentId || session.id), el('span', { class: `badge ${online ? 'live' : ''}` }, online ? 'Connected' : 'Offline')), el('p', { class: 'help' }, session.deviceName), el('p', { class: 'help' }, session.deliveryMode === 'poll' ? 'Inbox available when this app checks for messages. It may need you to resume the conversation.' : 'Native listener connected. Your app’s permissions still apply.'), el('small', {}, `Last seen ${date(session.updatedAt)}`), session.wake?.uncertain ? el('p', { class: 'notice-inline' }, 'A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox.') : null, el('div', { class: 'actions' }, button('Open conversation', async () => { openConversation(session.id); state.tab = 'messages'; await render(); })))); if (session.userId === state.user.id) list.lastChild.append(el('details', {}, el('summary', {}, 'Session details'), el('p', { class: 'help' }, 'This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine.'), el('code', {}, session.id), button('Copy session ID', () => copy(session.id)))); } }; @@ -357,6 +355,7 @@ start().catch(error => { root.replaceChildren(el('main', { id: 'main', class: 'a async function messagesView() { const generation = state.generation; const scopePath = path(''); + const messageKey = draftKey('message'); const workspaceId = state.workspace.id; const token = { stale: () => generation !== state.generation || state.workspace?.id !== workspaceId }; const [sessions, members] = await Promise.all([fetchSessions(scopePath, token), api(scopePath + '/members')]); @@ -367,7 +366,7 @@ async function messagesView() { const query = new URLSearchParams(); if (state.conversationAgent) query.set('agentId', state.conversationAgent); if (state.search) query.set('query', state.search); - const filter = el('select', { 'aria-label': 'Filter by session', onchange: e => { state.conversationAgent = e.target.value; action(null, render); } }, el('option', { value: '' }, 'All sessions'), sessions.map(s => el('option', { value: s.id, selected: s.id === state.conversationAgent }, labels.get(s.id)))); + const filter = el('select', { 'aria-label': 'Filter by session', onchange: e => { openConversation(e.target.value); action(null, render); } }, el('option', { value: '' }, 'All sessions'), sessions.map(s => el('option', { value: s.id, selected: s.id === state.conversationAgent }, labels.get(s.id)))); const search = field('Search messages', { name: 'query', value: state.search, type: 'search', maxlength: 256 }); const searchForm = form([search.node], 'Search', async data => { state.search = data.get('query').trim(); await render(); }); const container = el('div', {}, el('div', { class: 'card grid' }, el('label', {}, 'Conversation', filter), searchForm)); @@ -414,21 +413,22 @@ async function messagesView() { if (sessions.length) { const target = el('select', { name: 'to', required: true }, sessions.map(s => el('option', { value: s.id, selected: s.id === state.conversationAgent }, labels.get(s.id) + (s.reachable ? '' : ' · offline')))); const body = field('Your message', { name: 'body', multiline: true, required: true, maxlength: 65536, placeholder: 'What would you like this session to help with?' }); - const restored = getDraft('message'); + const restored = drafts.get(messageKey); if (restored?.body) body.input.value = restored.body; - if (restored?.to && sessions.some(s => s.id === restored.to)) target.value = restored.to; + if (restored?.body && restored.to && !sessions.some(s => s.id === restored.to)) { target.prepend(el('option', { value: '' }, 'Recipient unavailable — choose a session')); target.value = ''; } + else if (restored?.to && sessions.some(s => s.id === restored.to)) target.value = restored.to; const saveDraft = () => { const fingerprint = JSON.stringify([target.value, body.input.value]); - const previous = getDraft('message'); - setDraft('message', { to: target.value, body: body.input.value, fingerprint, key: previous?.fingerprint === fingerprint ? previous.key : crypto.randomUUID() }); + const previous = drafts.get(messageKey); + drafts.set(messageKey, { to: target.value, body: body.input.value, fingerprint, key: previous?.fingerprint === fingerprint ? previous.key : crypto.randomUUID() }); }; target.addEventListener('change', saveDraft); body.input.addEventListener('input', saveDraft); const compose = form([el('label', {}, 'Send to', target), body.node, attachmentPicker(scopePath, body.input), el('p', { class: 'help' }, 'Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.')], 'Send request', async data => { saveDraft(); - const saved = getDraft('message'); - await api(scopePath + '/messages', { method: 'POST', body: { to: data.get('to'), body: data.get('body'), mode: 'request', idempotencyKey: saved.key } }); - setDraft('message', null); + const { key } = drafts.get(messageKey); + await api(scopePath + '/messages', { method: 'POST', body: { to: data.get('to'), body: data.get('body'), mode: 'request', idempotencyKey: key } }); + if (drafts.get(messageKey)?.key === key) drafts.delete(messageKey); state.conversationAgent = data.get('to'); state.search = ''; inform('Request saved. Delivery status will update when the app checks its inbox.'); await render(); }); container.append(el('section', { class: 'card' }, el('h2', {}, 'Send a message'), compose)); @@ -472,6 +472,7 @@ async function questionsView() { async function channelsView() { const generation = state.generation; const scopePath = path(''); + const channelKey = draftKey('channel'); const channels = await api(scopePath + '/channels'); const channel = channels.find(c => c.id === state.channelId) || channels[0]; if (channel?.id !== state.channelId) state.threadId = ''; @@ -516,19 +517,19 @@ async function channelsView() { container.append(list); if (page.nextCursor) { let cursor = page.nextCursor; const more = button('Earlier posts', async () => { const nextQuery = new URLSearchParams(query); nextQuery.set('before', cursor); const older = await api(scopePath + '/channel-posts?' + nextQuery); append(older); cursor = older.nextCursor; if (!cursor) more.remove(); }); container.append(more); } const body = field(state.threadId ? 'Your reply' : 'Your post', { name: 'body', multiline: true, required: true, maxlength: 65536 }); - const draftName = `channel\n${channel.id}\n${state.threadId || ''}`; - const restored = getDraft(draftName); + const draftName = channelKey + `\n${channel.id}\n${state.threadId || ''}`; + const restored = drafts.get(draftName); if (restored?.body) body.input.value = restored.body; const saveDraft = () => { - const previous = getDraft(draftName); - setDraft(draftName, { body: body.input.value, key: previous?.body === body.input.value && previous.key ? previous.key : crypto.randomUUID() }); + const previous = drafts.get(draftName); + drafts.set(draftName, { body: body.input.value, key: previous?.body === body.input.value && previous.key ? previous.key : crypto.randomUUID() }); }; body.input.addEventListener('input', saveDraft); container.append(el('section', { class: 'card' }, form([body.node, attachmentPicker(scopePath, body.input), el('p', { class: 'help' }, 'Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.')], state.threadId ? 'Reply in thread' : 'Post to channel', async data => { saveDraft(); - const saved = getDraft(draftName); - await api(scopePath + '/channel-posts', { method: 'POST', body: { channelId: channel.id, body: data.get('body'), threadId: state.threadId || undefined, idempotencyKey: saved.key } }); - setDraft(draftName, null); + const { key } = drafts.get(draftName); + await api(scopePath + '/channel-posts', { method: 'POST', body: { channelId: channel.id, body: data.get('body'), threadId: state.threadId || undefined, idempotencyKey: key } }); + if (drafts.get(draftName)?.key === key) drafts.delete(draftName); state.channelSearch = ''; await render(); }))); let live = true, polling = false; diff --git a/web/tests/workspace.spec.js b/web/tests/workspace.spec.js index ba5240a..09d4d19 100644 --- a/web/tests/workspace.spec.js +++ b/web/tests/workspace.spec.js @@ -553,3 +553,169 @@ test('confirmation dialogs are named, keyboard-operable and still guard destruct await expect(page.getByText(/MCP app · Revoked/)).toBeVisible(); expect(events.filter(event => event.method === 'DELETE')).toHaveLength(1); }); + +test('duplicate session names always get distinct labels', async ({ page }) => { + await fixture(page); + const sessions = [ + { id: 'dup-1', displayName: 'Claude', deviceId: 'device-1', deviceName: 'Claude', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }, + { id: 'dup-2', displayName: 'Claude', deviceId: 'device-2', deviceName: 'Claude', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }, + { id: 'solo-1', displayName: 'Codex', deviceId: 'device-3', deviceName: 'Codex', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }, + { id: 'laptop-1', displayName: 'Claude', deviceId: 'device-4', deviceName: 'Laptop', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }, + ]; + await page.route('**/api/workspaces/workspace-1/sessions*', route => route.fulfill({ json: { ok: true, result: { sessions } } })); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const sendTo = page.locator('select[name="to"]'); + await expect(sendTo.locator('option')).toHaveCount(4); + await expect(sendTo.locator('option[value="dup-1"]')).toHaveText('Claude · dup-1'); + await expect(sendTo.locator('option[value="dup-2"]')).toHaveText('Claude · dup-2'); + await expect(sendTo.locator('option[value="solo-1"]')).toHaveText('Codex'); + await expect(sendTo.locator('option[value="laptop-1"]')).toHaveText('Claude · Laptop'); + const texts = await sendTo.locator('option').allTextContents(); + expect(new Set(texts).size).toBe(4); +}); + +test('conversations follow the session directory past fifty pages', async ({ page }) => { + await fixture(page); + const total = 55, perPage = 2; + await page.route('**/api/workspaces/workspace-1/sessions*', async route => { + const after = new URL(route.request().url()).searchParams.get('after'); + const index = after ? parseInt(after.slice(1), 10) : 0; + const sessions = []; + for (let i = 0; i < perPage; i++) { + const n = index * perPage + i + 1; + sessions.push({ id: `paged-${n}`, displayName: `Paged ${n}`, deviceId: 'device-1', deviceName: 'Laptop', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }); + } + const result = { sessions }; + if (index + 1 < total) result.nextCursor = 'p' + (index + 1); + await route.fulfill({ json: { ok: true, result } }); + }); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const sendTo = page.locator('select[name="to"]'); + await expect(sendTo.locator('option')).toHaveCount(total * perPage); + await expect(sendTo.locator('option[value="paged-110"]')).toHaveText('Paged 110'); + await expect(page.locator('select[aria-label="Filter by session"]').locator('option[value="paged-110"]')).toHaveText('Paged 110'); +}); + +test('a picked recipient survives navigation but yields to an explicit conversation choice', async ({ page }) => { + await fixture(page); + const sessions = [ + { id: 'session-alpha', displayName: 'Agent Alpha', deviceId: 'device-1', deviceName: 'Laptop', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }, + { id: 'session-beta', displayName: 'Agent Beta', deviceId: 'device-2', deviceName: 'Desktop', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }, + ]; + await page.route('**/api/workspaces/workspace-1/sessions*', route => route.fulfill({ json: { ok: true, result: { sessions } } })); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const sendTo = page.locator('select[name="to"]'); + await sendTo.selectOption('session-beta'); + await page.getByRole('button', { name: 'Tasks', exact: true }).click(); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + await expect(sendTo).toHaveValue('session-beta'); + const composer = page.getByLabel('Your message', { exact: true }); + await composer.fill('x'); + await composer.fill(''); + await page.getByRole('button', { name: 'Sessions', exact: true }).click(); + await page.getByRole('article').filter({ hasText: 'Agent Alpha' }).getByRole('button', { name: 'Open conversation', exact: true }).click(); + await expect(page.locator('select[name="to"]')).toHaveValue('session-alpha'); +}); + +test('a late upload never writes into another workspace draft', async ({ page }) => { + await fixture(page); + await page.route('**/api/workspaces', route => route.fulfill({ json: { ok: true, result: [ + { id: 'workspace-1', name: 'My workspace', role: 'owner', memberLimit: 5 }, + { id: 'workspace-2', name: 'Second workspace', role: 'owner', memberLimit: 5 }, + ] } })); + let release; + const held = new Promise(r => { release = r; }); + let heldCount = 0; + await page.route('**/api/workspaces/workspace-1/attachments*', async route => { + if (route.request().method() === 'POST') { heldCount++; await held; } + await route.fallback(); + }); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + await page.getByLabel('Your message', { exact: true }).fill('Workspace one text'); + await page.getByText('Attach a file', { exact: true }).first().click(); + await page.getByLabel('Attach a file', { exact: true }).setInputFiles({ name: 'late.txt', mimeType: 'text/plain', buffer: Buffer.from('late bytes') }); + await page.getByRole('button', { name: 'Upload and attach', exact: true }).click(); + await expect.poll(() => heldCount, { timeout: 5000 }).toBe(1); + await page.locator('select[aria-label="Workspace"]').selectOption('workspace-2'); + const composer = page.getByLabel('Your message', { exact: true }); + await expect(composer).toHaveValue(''); + await composer.fill('Workspace two text'); + release(); + await expect(page.getByText('File uploaded. Copy its reference from Files to share it.', { exact: true })).toBeVisible(); + await expect(composer).toHaveValue('Workspace two text'); + await page.locator('select[aria-label="Workspace"]').selectOption('workspace-1'); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('Workspace one text'); +}); + +test('text typed while a send is pending survives the send', async ({ page }) => { + const events = await fixture(page); + let release; + const held = new Promise(r => { release = r; }); + let posts = 0; + await page.route('**/api/workspaces/workspace-1/messages*', async route => { + if (route.request().method() === 'POST') { posts++; await held; } + await route.fallback(); + }); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const composer = page.getByLabel('Your message', { exact: true }); + await composer.fill('First text'); + await page.getByRole('button', { name: 'Send request', exact: true }).click(); + await expect.poll(() => posts, { timeout: 5000 }).toBe(1); + await composer.fill('First text plus more'); + release(); + await expect(page.getByText('First text', { exact: true })).toBeVisible(); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('First text plus more'); + expect(events.filter(e => e.method === 'POST' && e.path.endsWith('/messages'))).toHaveLength(1); +}); + +test('a draft addressed to a vanished session blocks sending until a new recipient is chosen', async ({ page }) => { + const events = await fixture(page); + let directory = [ + { id: 'gone-1', displayName: 'Leaving Agent', deviceId: 'device-1', deviceName: 'Laptop', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }, + { id: 'stays-1', displayName: 'Staying Agent', deviceId: 'device-2', deviceName: 'Desktop', reachable: true, deliveryMode: 'poll', updatedAt: '2026-10-24T12:00:00Z' }, + ]; + await page.route('**/api/workspaces/workspace-1/sessions*', route => route.fulfill({ json: { ok: true, result: { sessions: directory } } })); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const sendTo = page.locator('select[name="to"]'); + await sendTo.selectOption('gone-1'); + await page.getByLabel('Your message', { exact: true }).fill('Hello there'); + directory = [directory[1]]; + await page.getByRole('button', { name: 'Refresh conversation', exact: true }).click(); + await expect(sendTo).toHaveValue(''); + await expect(sendTo.locator('option[value=""]')).toHaveText('Recipient unavailable — choose a session'); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('Hello there'); + await page.getByRole('button', { name: 'Send request', exact: true }).click(); + expect(events.filter(e => e.method === 'POST')).toHaveLength(0); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('Hello there'); +}); + +test('a retry after navigation reuses the failed send idempotency key', async ({ page }) => { + await fixture(page); + const postedKeys = []; + await page.route('**/api/workspaces/workspace-1/messages*', async route => { + if (route.request().method() === 'POST' && postedKeys.length === 0) { + postedKeys.push(route.request().postDataJSON().idempotencyKey); + return route.fulfill({ status: 500, json: { ok: false, error: { message: 'Delivery uncertain. Please retry.' } } }); + } + if (route.request().method() === 'POST') postedKeys.push(route.request().postDataJSON().idempotencyKey); + await route.fallback(); + }); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + await page.getByLabel('Your message', { exact: true }).fill('Retry after navigation.'); + await page.getByRole('button', { name: 'Send request', exact: true }).click(); + await expect(page.getByText('Delivery uncertain. Please retry.', { exact: true })).toBeVisible(); + await page.getByRole('button', { name: 'Tasks', exact: true }).click(); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('Retry after navigation.'); + await page.getByRole('button', { name: 'Send request', exact: true }).click(); + await expect(page.getByText('Retry after navigation.', { exact: true })).toBeVisible(); + expect(postedKeys).toHaveLength(2); + expect(postedKeys[1]).toBe(postedKeys[0]); +}); From fbc8aac21a4ec9bffea1256dda2184d3ee320632 Mon Sep 17 00:00:00 2001 From: Harsh Date: Fri, 13 Nov 2026 11:51:40 -0800 Subject: [PATCH 3/3] Address round-2 audit: keep unavailable-recipient guard after draft edits (#199) The recipient guard no longer requires a non-empty saved recipient, so a draft edited while the placeholder is selected keeps the unavailable state across rebuilds instead of falling back to another session. Extends the vanished-session test with the edit-navigate-reselect transition and hardens the late-upload test; regenerates bus/hostedweb/app.js with web's own build. --- bus/hostedweb/app.js | 14 +++++++------- web/src/app.js | 2 +- web/tests/workspace.spec.js | 11 +++++++++++ 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/bus/hostedweb/app.js b/bus/hostedweb/app.js index 4038482..b73a3a2 100644 --- a/bus/hostedweb/app.js +++ b/bus/hostedweb/app.js @@ -11,17 +11,17 @@ Nonce: ${o}`:""} Issued At: ${i.toISOString()}`;if(s&&(C+=` Expiration Time: ${s.toISOString()}`),l&&(C+=` Not Before: ${l.toISOString()}`),c&&(C+=` -Request ID: ${c}`),u){let S=` -Resources:`;for(let m of u){if(!m||typeof m!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${m}`);S+=` -- ${m}`}C+=S}return`${A} -${C}`}var $=class extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},ke=class extends ${constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function mr({error:n,options:e}){var t,r,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new $({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new $({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new $({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new $({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new $({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new $({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new $({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new $({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){let o=window.location.hostname;if(vt(o)){if(i.rp.id!==o)return new $({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new $({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new $({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new $({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new $({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function _r({error:n,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new $({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new $({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){let r=window.location.hostname;if(vt(r)){if(t.rpId!==r)return new $({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new $({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new $({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new $({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}var bt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},et=new bt;function kt(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);let{challenge:e,user:t,excludeCredentials:r}=n,s=pe(n,["challenge","user","excludeCredentials"]),i=de(e).buffer,o=Object.assign(Object.assign({},t),{id:de(t.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c0){i.allowCredentials=new Array(t.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of n)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){let l=r[i];e(l)?r[i]=Qe(l,o):r[i]=Qe(o)}else r[i]=o}return r}function Xr(n,e){return Qe(Hr,n,e||{})}function Qr(n,e){return Qe(Yr,n,e||{})}var Ze=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var o;try{let{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!l)return{data:null,error:c};let u=s??et.createNewAbortSignal();if(l.webauthn.type==="create"){let{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){let f=r;if(f)h.name=`${h.id}:${f}`;else{let p=(await this.client.getUser()).data.user,b=((o=p?.user_metadata)===null||o===void 0?void 0:o.name)||p?.email||p?.id||"User";h.name=`${h.id}:${b}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{let h=Xr(l.webauthn.credential_options.publicKey,i?.create),{data:f,error:y}=await At({publicKey:h,signal:u});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:y}}case"request":{let h=Qr(l.webauthn.credential_options.publicKey,i?.request),{data:f,error:y}=await It(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:y}}}}catch(l){return w(l)?{data:null,error:l}:{data:null,error:new B("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ce("rpId is required for WebAuthn authentication")};try{if(!qe())return{data:null,error:new B("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:l};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new B("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ce("rpId is required for WebAuthn registration")};try{if(!qe())return{data:null,error:new B("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var f;return(f=h.data)===null||f===void 0?void 0:f.all.find(y=>y.factor_type==="webauthn"&&y.friendly_name===e&&y.status==="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:l};let{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new B("Unexpected error in register",o)}}}};pr();var Zr={url:Mt,storageKey:Kt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ft,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Ie={},vr=!1,tt=class n{get jwks(){var e,t;return(t=(e=Ie[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Ie[this.storageKey]=Object.assign(Object.assign({},Ie[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Ie[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ie[this.storageKey]=Object.assign(Object.assign({},Ie[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Zr),e);if(this.storageKey=i.storageKey,this.instanceID=(t=n.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,n.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&K()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new be({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Je(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,vr||(vr=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),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 Ze(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(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:ze()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=mt(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=mt(this.memoryStorage)),K()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ke}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(K()&&(t=ft(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),K()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Vt(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new B("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let i=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:H}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;let i=null;try{let o;if("email"in e){let{email:f,password:y,options:p}=e,b=null,E=null;this.flowType==="pkce"&&([b,E,i]=await this._getCodeChallengeAndMethod()),o=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(p?.emailRedirectTo,i),body:{email:f,password:y,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:b,code_challenge_method:E},xform:H})}else if("phone"in e){let{phone:f,password:y,options:p}=e;o=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:y,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(s=p?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:H})}else throw new we("You must provide either an email or phone number and a password");let{data:l,error:c}=o;if(c||!l)return await Q(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let u=l.session,h=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:h,session:u},error:null})}catch(o){if(await Q(this.storage,this.storageKey,i),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:l}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:yt})}else if("phone"in e){let{phone:i,password:o,options:l}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:yt})}else throw new we("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let i=new ae;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,l,c,u,h,f,y;let p,b;if("message"in e)p=e.message,b=e.signature;else{let{chain:E,wallet:A,statement:C,options:S}=e,m;if(K())if(typeof A=="object")m=A;else{let U=window;if("ethereum"in U&&typeof U.ethereum=="object"&&"request"in U.ethereum&&typeof U.ethereum.request=="function")m=U.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 A!="object"||!S?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");m=A}let x=new URL((t=S?.url)!==null&&t!==void 0?t:window.location.href),q=await m.request({method:"eth_requestAccounts"}).then(U=>U).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!q||q.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let P=_t(q[0]),j=(r=S?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!j){let U=await m.request({method:"eth_chainId"});j=wr(U)}let R={domain:x.host,address:P,statement:C,uri:x.href,version:"1",chainId:j,nonce:(s=S?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=S?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=S?.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=S?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=S?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=S?.signInWithEthereum)===null||h===void 0?void 0:h.resources};p=gr(R),b=await m.request({method:"personal_sign",params:[yr(p),P]})}try{let{data:E,error:A}=await g(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:b},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(y=e.options)===null||y===void 0?void 0:y.captchaToken}}:null),xform:H});if(A)throw A;if(!E||!E.session||!E.user){let C=new ae;return this._returnResult({data:{user:null,session:null},error:C})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:A})}catch(E){if(w(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var t,r,s,i,o,l,c,u,h,f,y,p;let b,E;if("message"in e)b=e.message,E=e.signature;else{let{chain:A,wallet:C,statement:S,options:m}=e,x;if(K())if(typeof C=="object")x=C;else{let P=window;if("solana"in P&&typeof P.solana=="object"&&("signIn"in P.solana&&typeof P.solana.signIn=="function"||"signMessage"in P.solana&&typeof P.solana.signMessage=="function"))x=P.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 C!="object"||!m?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=C}let q=new URL((t=m?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in x&&x.signIn){let P=await x.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},m?.signInWithSolana),{version:"1",domain:q.host,uri:q.href}),S?{statement:S}:null)),j;if(Array.isArray(P)&&P[0]&&typeof P[0]=="object")j=P[0];else if(P&&typeof P=="object"&&"signedMessage"in P&&"signature"in P)j=P;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)b=typeof j.signedMessage=="string"?j.signedMessage:new TextDecoder().decode(j.signedMessage),E=j.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in x)||typeof x.signMessage!="function"||!("publicKey"in x)||typeof x!="object"||!x.publicKey||!("toBase58"in x.publicKey)||typeof x.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");b=[`${q.host} wants you to sign in with your Solana account:`,x.publicKey.toBase58(),...S?["",S,""]:[""],"Version: 1",`URI: ${q.href}`,`Issued At: ${(s=(r=m?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=m?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${m.signInWithSolana.notBefore}`]:[],...!((o=m?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${m.signInWithSolana.expirationTime}`]:[],...!((l=m?.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${m.signInWithSolana.chainId}`]:[],...!((c=m?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${m.signInWithSolana.nonce}`]:[],...!((u=m?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${m.signInWithSolana.requestId}`]:[],...!((f=(h=m?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||f===void 0)&&f.length?["Resources",...m.signInWithSolana.resources.map(j=>`- ${j}`)]:[]].join(` -`);let P=await x.signMessage(new TextEncoder().encode(b),"utf8");if(!P||!(P instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=P}}try{let{data:A,error:C}=await g(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:b,signature:le(E)},!((y=e.options)===null||y===void 0)&&y.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:H});if(C)throw C;if(!A||!A.session||!A.user){let S=new ae;return this._returnResult({data:{user:null,session:null},error:S})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:C})}catch(A){if(w(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e,t){let r=t?.flowId!=null,s=r?Le(t?.flowId):K()?Le(ft(window.location.href)[oe]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",t?.flowId);let{verifier:i,flowId:o}=r&&!s?{verifier:null,flowId:null}:await rr(this.storage,this.storageKey,s),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new Be;let{data:u,error:h}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:l},xform:H});if(await Q(this.storage,this.storageKey,o),h)throw h;if(!u||!u.session||!u.user){let f=new ae;return this._returnResult({data:{user:null,session:null,redirectType:null},error:f})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:h})}catch(u){if(await Q(this.storage,this.storageKey,o),w(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:o}=e,l=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:H}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){let h=new ae;return this._returnResult({data:{user:null,session:null},error:h})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;let l=null;try{if("email"in e){let{email:c,options:u}=e,h=null,f=null;this.flowType==="pkce"&&([h,f,l]=await this._getCodeChallengeAndMethod());let{error:y}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(t=u?.data)!==null&&t!==void 0?t:{},create_user:(r=u?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:y})}if("phone"in e){let{phone:c,options:u}=e,{data:h,error:f}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(s=u?.data)!==null&&s!==void 0?s:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(o=u?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:f})}throw new we("You must provide either an email or phone number.")}catch(c){if(await Q(this.storage,this.storageKey,l),w(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:l}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:H});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(s){if(w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());let u=await g(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:this._maybeAppendFlowIdToRedirect((t=e.options)===null||t===void 0?void 0:t.redirectTo,o)}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:hr});return!((s=u.data)===null||s===void 0)&&s.url&&K()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await Q(this.storage,this.storageKey,o),w(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new D;let{error:s}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(w(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:o}=e,l=null,c=null;this.flowType==="pkce"&&([l,c,t]=await this._getCodeChallengeAndMethod());let{error:u}=await g(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t)});return u&&await Q(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){let{phone:s,type:i,options:o}=e,{data:l,error:c}=await g(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:c})}throw new we("You must provide either an email or phone number and a type")}catch(r){if(await Q(this.storage,this.storageKey,t),w(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,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await F(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let t=await F(this.userStorage,this.storageKey+"-user");e.user=t?.user?t.user:He()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=cr(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return this.lock!=null?t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):t=await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ne}):await this._useSession(async t=>{var r,s,i;let{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new D}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:ne})})}catch(t){if(w(t))return Ue(t)&&await this._removeSession(),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new D;let l=i.session,c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());let{data:h,error:f}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:ne});if(f)throw f;return l.user=h.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(s){if(await Q(this.storage,this.storageKey,r),w(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 D;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:o}=Ne(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{let{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}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 t=>{var r;if(!e){let{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new D;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!K())throw new ye("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ye(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new Ce("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ye("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ce("No code detected.");let{data:m,error:x}=await this._exchangeCodeForSession(e.code,{flowId:e[oe]});if(x)throw x;let q=new URL(window.location.href);return q.searchParams.delete("code"),q.searchParams.delete(oe),window.history.replaceState(window.history.state,"",q.toString()),{data:{session:m.session,redirectType:(r=m.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:h}=e;if(!o||!c||!l||!h)throw new ye("No session defined in URL");let f=Math.round(Date.now()/1e3),y=parseInt(c),p=f+y;u&&(p=parseInt(u));let b=p-f;b*1e3<=te&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${b}s, should have been closer to ${y}s`);let E=p-y;f-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,p,f):f-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,p,f);let{data:A,error:C}=await this._getUser(o);if(C)throw C;let S={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:y,expires_at:p,refresh_token:l,token_type:h,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:S,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=Le(e[oe]);return t&&await F(this.storage,_e(this.storageKey,t))?!0:!!await F(this.storage,`${this.storageKey}-code-verifier`)}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 t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:o}=t;if(o&&!Ue(o))return this._returnResult({error:o});let l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){let{error:c}=await this.admin.signOut(l,e);if(c&&!(ut(c)&&(c.status===404||c.status===401||c.status===403)||Ue(c)))return e!=="others"&&await s(),this._returnResult({error:c})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=Xt(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),dt(i))return;Ue(i)||je(i)||ut(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;this.flowType==="pkce"&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(o){if(await Q(this.storage,this.storageKey,i),w(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async o=>{var l,c,u,h,f;let{data:y,error:p}=o;if(p)throw p;let{url:b,flowId:E}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(l=e.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=E,await g(this.fetch,"GET",b,{headers:this.headers,jwt:(f=(h=y.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(i)throw i;return K()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:r},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:l,token:c,access_token:u,nonce:h}=e,f=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:H}),{data:y,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!y||!y.session||!y.user?this._returnResult({data:{user:null,session:null},error:new ae}):(y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("USER_UPDATED",y.session)),this._returnResult({data:y,error:p}))}catch(s){if(await Q(this.storage,this.storageKey,null),w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)throw o;return await g(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{let r=Date.now();return await er(async s=>(s>0&&await Zt(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:H})),(s,i)=>{let o=200*Math.pow(2,s);return i&&je(i)&&Date.now()+o-r{});let i=await F(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(e);if(l)throw l;if(!o.session)throw new D;let c=await F(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let y={data:null,error:new Oe};return this.refreshingDeferred.resolve(y),y}let h=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await z(this.storage,this.storageKey),this.userStorage&&await z(this.userStorage,this.storageKey+"-user");let y={data:null,error:new Oe};return this.refreshingDeferred.resolve(y),y}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let f={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(f),f}catch(i){if(this._debug(s,"error",i),w(i)){let o={data:null,error:i};if(!je(i)){let l=await F(this.storage,this.storageKey);!!(l?.expires_at&&l.expires_at*1e3>Date.now())?this._debug(s,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+qt},(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:e,session:t,broadcast:r});return}let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;lthis._autoRefreshTokenTick(),te);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/te);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${te}ms, refresh threshold is ${Ee} ticks`),s<=Ee&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof Xe)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/te);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${te}ms, refresh threshold is ${Ee} ticks`),s<=Ee&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!K()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"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(t,"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(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=r?.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,l));let c=[`provider=${encodeURIComponent(t)}`];if(s&&c.push(`redirect_to=${encodeURIComponent(s)}`),r?.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){let u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r?.queryParams){let u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r?.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:nr(e,t)}async _getCodeChallengeAndMethod(e=!1){return ir(this.storage,this.storageKey,e,t=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",t))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await g(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Rt(e.webauthn.credential_response):Et(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;let{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:kt(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:St(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&i.factor_type in s&&Array.isArray(s[i.factor_type])&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:p}=Ne(e),b=null;p.aal&&(b=p.aal);let E=b,{data:{user:A},error:C}=await this.getUser(e);if(C)return this._returnResult({data:null,error:C});((r=(t=A?.factors)===null||t===void 0?void 0:t.filter(x=>x.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(E="aal2");let m=p.amr||[];return{data:{currentLevel:b,nextLevel:E,currentAuthenticationMethods:m},error:null}}catch(p){if(w(p))return this._returnResult({data:null,error:p});throw p}let{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ne(o.access_token),u=null;c.aal&&(u=c.aal);let h=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let y=c.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:y},error:null}}async _getRecoveryCodesStatus(){Ae(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){Ae(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:o,error:l}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):this._returnResult({data:o,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verifyRecoveryCode(e){Ae(this.experimental);let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let{data:l,error:c}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(c)return this._returnResult({data:null,error:c});let u=Object.assign({expires_at:Ve(l.expires_in)},l);return await this._saveSession(u),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:l,error:null})})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){Ae(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){Ae(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await g(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new D})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new D});let o=await g(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&K()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new D});let o=await g(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&K()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await g(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new D})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await g(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new D})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+Gt>s)return r;let{data:i,error:o}=await g(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:p,error:b}=await this.getSession();if(b||!p.session)return this._returnResult({data:null,error:b});r=p.session.access_token}let{header:s,payload:i,signature:o,raw:{header:l,payload:c}}=Ne(r);if(!t?.allowExpired)try{ar(i.exp)}catch(p){throw new ue(p instanceof Error?p.message:"JWT validation failed")}let u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){let{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:s,signature:o},error:null}}let h=lr(s.alg),f=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,f,o,Yt(`${l}.${c}`)))throw new ue("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var t,r,s,i;try{if(!qe())return this._returnResult({data:null,error:new B("Browser does not support WebAuthn",null)});let{data:o,error:l}=await this._startPasskeyAuthentication({options:{captchaToken:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}});if(l||!o)return this._returnResult({data:null,error:l});let c=St(o.options),u=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:et.createNewAbortSignal(),{data:h,error:f}=await It({publicKey:c,signal:u,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(f||!h)return this._returnResult({data:null,error:f??new B("WebAuthn ceremony failed",null)});let y=Et(h);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:y})}catch(o){if(w(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var t,r;try{if(!qe())return this._returnResult({data:null,error:new B("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let o=kt(s.options),l=(r=(t=e?.options)===null||t===void 0?void 0:t.signal)!==null&&r!==void 0?r:et.createNewAbortSignal(),{data:c,error:u}=await At({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new B("WebAuthn ceremony failed",null)});let h=Rt(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new D});let{data:s,error:i}=await g(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new D});let{data:i,error:o}=await g(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;try{let{data:r,error:s}=await g(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:r}=await g(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:H});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new D});let{data:s,error:i}=await g(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new D});let{data:i,error:o}=await g(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new D});let{error:i}=await g(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}};tt.nextInstanceID={};var Tt=tt;var es=Tt,xt=es;var he=document.querySelector("#app"),Me=document.querySelector("#notice"),d={auth:null,config:null,user:null,workspaces:[],workspace:null,tab:"sessions",generation:0,conversationAgent:"",search:"",channelId:"",threadId:"",channelSearch:""},br,st=[];function Rr(){for(let n of st.splice(0))n()}var Se=new URLSearchParams(location.search);Se.has("billing")&&(d.tab="billing");var jt="agentintercom-pending",N={};try{let n=JSON.parse(sessionStorage.getItem(jt)||"{}");n.until>Date.now()&&(N=n)}catch{}Se.get("authorization_id")&&(N.authorization=Se.get("authorization_id"));var Er=new URLSearchParams(location.hash.slice(1)),kr=Er.get("invite"),Sr=Er.get("device")||Se.get("device_code");Sr&&(N.device=Sr,history.replaceState(null,"",location.pathname+location.search));kr&&(N.invite=kr,history.replaceState(null,"",location.pathname+location.search));(N.authorization||N.invite||N.device)&&sessionStorage.setItem(jt,JSON.stringify({...N,until:Date.now()+1200*1e3}));function a(n,e={},...t){let r=document.createElement(n);for(let[s,i]of Object.entries(e))i==null||i===!1||(s.startsWith("on")?r.addEventListener(s.slice(2),i):s==="class"?r.className=i:s==="text"?r.textContent=i:r.setAttribute(s,i===!0?"":String(i)));for(let s of t.flat(1/0))s!=null&&r.append(s instanceof Node?s:document.createTextNode(String(s)));return r}function Y(n,e=!1){clearTimeout(br),Me.textContent=n,Me.hidden=!1,Me.className=e?"error":"",Me.setAttribute("role",e?"alert":"status"),br=setTimeout(()=>{Me.hidden=!0},e?15e3:6e3)}async function Te(n,e){if(!n?.disabled){n&&(n.disabled=!0);try{return await e()}catch(t){Y(t.message||"Something went wrong. Please try again.",!0)}finally{n&&(n.disabled=!1)}}}function _(n,e,t=""){return a("button",{type:"button",class:t,onclick:r=>Te(r.currentTarget,e)},n)}function M(n,e={}){let t=a(e.multiline?"textarea":"input",{...e,multiline:null});return{input:t,node:a("label",{},n,t)}}function V(n,e,t){let r=a("button",{type:"submit",class:"primary"},e);return a("form",{onsubmit:s=>{s.preventDefault(),Te(r,()=>t(new FormData(s.currentTarget)))}},n,r)}var fe=()=>a("div",{class:"brand"},a("span",{class:"mark","aria-hidden":!0},"o"),"agent intercom"),J=n=>n?new Date(n).toLocaleString():"\u2014",L=n=>`/api/workspaces/${encodeURIComponent(d.workspace.id)}${n}`;async function v(n,e={}){let t={"Content-Type":"application/json"};if(d.auth&&n!=="/api/config"){let{data:i,error:o}=await d.auth.getSession();if(o)throw o;i.session&&(t.Authorization=`Bearer ${i.session.access_token}`)}let r=await fetch(n,{method:e.method||"GET",credentials:"omit",headers:t,body:e.body==null?void 0:JSON.stringify(e.body),signal:AbortSignal.timeout(e.timeout||15e3)}),s=await r.json();if(!r.ok||s.ok===!1||s.error)throw new Error(s.error?.message||"The request could not be completed. Please try again.");return s.result}async function ot(n){await navigator.clipboard.writeText(n),Y("Copied to clipboard.")}var G=new Map,$t=n=>`${d.user.id} +Request ID: ${c}`),u){let k=` +Resources:`;for(let m of u){if(!m||typeof m!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${m}`);k+=` +- ${m}`}C+=k}return`${A} +${C}`}var $=class extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},ke=class extends ${constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function mr({error:n,options:e}){var t,r,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new $({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new $({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new $({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new $({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new $({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new $({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new $({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new $({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){let o=window.location.hostname;if(vt(o)){if(i.rp.id!==o)return new $({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new $({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new $({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new $({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new $({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function _r({error:n,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new $({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new $({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){let r=window.location.hostname;if(vt(r)){if(t.rpId!==r)return new $({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new $({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new $({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new $({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}var bt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},et=new bt;function kt(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);let{challenge:e,user:t,excludeCredentials:r}=n,s=pe(n,["challenge","user","excludeCredentials"]),i=de(e).buffer,o=Object.assign(Object.assign({},t),{id:de(t.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c0){i.allowCredentials=new Array(t.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of n)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){let l=r[i];e(l)?r[i]=Qe(l,o):r[i]=Qe(o)}else r[i]=o}return r}function Xr(n,e){return Qe(Hr,n,e||{})}function Qr(n,e){return Qe(Yr,n,e||{})}var Ze=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var o;try{let{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!l)return{data:null,error:c};let u=s??et.createNewAbortSignal();if(l.webauthn.type==="create"){let{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){let f=r;if(f)h.name=`${h.id}:${f}`;else{let p=(await this.client.getUser()).data.user,b=((o=p?.user_metadata)===null||o===void 0?void 0:o.name)||p?.email||p?.id||"User";h.name=`${h.id}:${b}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{let h=Xr(l.webauthn.credential_options.publicKey,i?.create),{data:f,error:y}=await At({publicKey:h,signal:u});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:y}}case"request":{let h=Qr(l.webauthn.credential_options.publicKey,i?.request),{data:f,error:y}=await It(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:y}}}}catch(l){return w(l)?{data:null,error:l}:{data:null,error:new B("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ce("rpId is required for WebAuthn authentication")};try{if(!qe())return{data:null,error:new B("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:l};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new B("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ce("rpId is required for WebAuthn registration")};try{if(!qe())return{data:null,error:new B("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var f;return(f=h.data)===null||f===void 0?void 0:f.all.find(y=>y.factor_type==="webauthn"&&y.friendly_name===e&&y.status==="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:l};let{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new B("Unexpected error in register",o)}}}};pr();var Zr={url:Mt,storageKey:Kt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ft,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Ie={},vr=!1,tt=class n{get jwks(){var e,t;return(t=(e=Ie[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Ie[this.storageKey]=Object.assign(Object.assign({},Ie[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Ie[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ie[this.storageKey]=Object.assign(Object.assign({},Ie[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Zr),e);if(this.storageKey=i.storageKey,this.instanceID=(t=n.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,n.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&K()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new be({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Je(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,vr||(vr=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),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 Ze(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(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:ze()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=mt(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=mt(this.memoryStorage)),K()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ke}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(K()&&(t=ft(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),K()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Vt(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new B("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let i=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:H}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;let i=null;try{let o;if("email"in e){let{email:f,password:y,options:p}=e,b=null,E=null;this.flowType==="pkce"&&([b,E,i]=await this._getCodeChallengeAndMethod()),o=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(p?.emailRedirectTo,i),body:{email:f,password:y,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:b,code_challenge_method:E},xform:H})}else if("phone"in e){let{phone:f,password:y,options:p}=e;o=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:y,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(s=p?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:H})}else throw new we("You must provide either an email or phone number and a password");let{data:l,error:c}=o;if(c||!l)return await Q(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let u=l.session,h=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:h,session:u},error:null})}catch(o){if(await Q(this.storage,this.storageKey,i),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:l}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:yt})}else if("phone"in e){let{phone:i,password:o,options:l}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:yt})}else throw new we("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let i=new ae;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,l,c,u,h,f,y;let p,b;if("message"in e)p=e.message,b=e.signature;else{let{chain:E,wallet:A,statement:C,options:k}=e,m;if(K())if(typeof A=="object")m=A;else{let U=window;if("ethereum"in U&&typeof U.ethereum=="object"&&"request"in U.ethereum&&typeof U.ethereum.request=="function")m=U.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 A!="object"||!k?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");m=A}let x=new URL((t=k?.url)!==null&&t!==void 0?t:window.location.href),q=await m.request({method:"eth_requestAccounts"}).then(U=>U).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!q||q.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let P=_t(q[0]),j=(r=k?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!j){let U=await m.request({method:"eth_chainId"});j=wr(U)}let R={domain:x.host,address:P,statement:C,uri:x.href,version:"1",chainId:j,nonce:(s=k?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=k?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=k?.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=k?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=k?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=k?.signInWithEthereum)===null||h===void 0?void 0:h.resources};p=gr(R),b=await m.request({method:"personal_sign",params:[yr(p),P]})}try{let{data:E,error:A}=await g(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:b},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(y=e.options)===null||y===void 0?void 0:y.captchaToken}}:null),xform:H});if(A)throw A;if(!E||!E.session||!E.user){let C=new ae;return this._returnResult({data:{user:null,session:null},error:C})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:A})}catch(E){if(w(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var t,r,s,i,o,l,c,u,h,f,y,p;let b,E;if("message"in e)b=e.message,E=e.signature;else{let{chain:A,wallet:C,statement:k,options:m}=e,x;if(K())if(typeof C=="object")x=C;else{let P=window;if("solana"in P&&typeof P.solana=="object"&&("signIn"in P.solana&&typeof P.solana.signIn=="function"||"signMessage"in P.solana&&typeof P.solana.signMessage=="function"))x=P.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 C!="object"||!m?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=C}let q=new URL((t=m?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in x&&x.signIn){let P=await x.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},m?.signInWithSolana),{version:"1",domain:q.host,uri:q.href}),k?{statement:k}:null)),j;if(Array.isArray(P)&&P[0]&&typeof P[0]=="object")j=P[0];else if(P&&typeof P=="object"&&"signedMessage"in P&&"signature"in P)j=P;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)b=typeof j.signedMessage=="string"?j.signedMessage:new TextDecoder().decode(j.signedMessage),E=j.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in x)||typeof x.signMessage!="function"||!("publicKey"in x)||typeof x!="object"||!x.publicKey||!("toBase58"in x.publicKey)||typeof x.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");b=[`${q.host} wants you to sign in with your Solana account:`,x.publicKey.toBase58(),...k?["",k,""]:[""],"Version: 1",`URI: ${q.href}`,`Issued At: ${(s=(r=m?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=m?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${m.signInWithSolana.notBefore}`]:[],...!((o=m?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${m.signInWithSolana.expirationTime}`]:[],...!((l=m?.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${m.signInWithSolana.chainId}`]:[],...!((c=m?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${m.signInWithSolana.nonce}`]:[],...!((u=m?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${m.signInWithSolana.requestId}`]:[],...!((f=(h=m?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||f===void 0)&&f.length?["Resources",...m.signInWithSolana.resources.map(j=>`- ${j}`)]:[]].join(` +`);let P=await x.signMessage(new TextEncoder().encode(b),"utf8");if(!P||!(P instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=P}}try{let{data:A,error:C}=await g(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:b,signature:le(E)},!((y=e.options)===null||y===void 0)&&y.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:H});if(C)throw C;if(!A||!A.session||!A.user){let k=new ae;return this._returnResult({data:{user:null,session:null},error:k})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:C})}catch(A){if(w(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e,t){let r=t?.flowId!=null,s=r?Le(t?.flowId):K()?Le(ft(window.location.href)[oe]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",t?.flowId);let{verifier:i,flowId:o}=r&&!s?{verifier:null,flowId:null}:await rr(this.storage,this.storageKey,s),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new Be;let{data:u,error:h}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:l},xform:H});if(await Q(this.storage,this.storageKey,o),h)throw h;if(!u||!u.session||!u.user){let f=new ae;return this._returnResult({data:{user:null,session:null,redirectType:null},error:f})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:h})}catch(u){if(await Q(this.storage,this.storageKey,o),w(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:o}=e,l=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:H}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){let h=new ae;return this._returnResult({data:{user:null,session:null},error:h})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;let l=null;try{if("email"in e){let{email:c,options:u}=e,h=null,f=null;this.flowType==="pkce"&&([h,f,l]=await this._getCodeChallengeAndMethod());let{error:y}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(t=u?.data)!==null&&t!==void 0?t:{},create_user:(r=u?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:y})}if("phone"in e){let{phone:c,options:u}=e,{data:h,error:f}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(s=u?.data)!==null&&s!==void 0?s:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(o=u?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:f})}throw new we("You must provide either an email or phone number.")}catch(c){if(await Q(this.storage,this.storageKey,l),w(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:l}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:H});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(s){if(w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());let u=await g(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:this._maybeAppendFlowIdToRedirect((t=e.options)===null||t===void 0?void 0:t.redirectTo,o)}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:hr});return!((s=u.data)===null||s===void 0)&&s.url&&K()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await Q(this.storage,this.storageKey,o),w(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new D;let{error:s}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(w(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:o}=e,l=null,c=null;this.flowType==="pkce"&&([l,c,t]=await this._getCodeChallengeAndMethod());let{error:u}=await g(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t)});return u&&await Q(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){let{phone:s,type:i,options:o}=e,{data:l,error:c}=await g(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:c})}throw new we("You must provide either an email or phone number and a type")}catch(r){if(await Q(this.storage,this.storageKey,t),w(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,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await F(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let t=await F(this.userStorage,this.storageKey+"-user");e.user=t?.user?t.user:He()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=cr(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return this.lock!=null?t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):t=await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ne}):await this._useSession(async t=>{var r,s,i;let{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new D}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:ne})})}catch(t){if(w(t))return Ue(t)&&await this._removeSession(),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new D;let l=i.session,c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());let{data:h,error:f}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:ne});if(f)throw f;return l.user=h.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(s){if(await Q(this.storage,this.storageKey,r),w(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 D;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:o}=Ne(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{let{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}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 t=>{var r;if(!e){let{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new D;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!K())throw new ye("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ye(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new Ce("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ye("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ce("No code detected.");let{data:m,error:x}=await this._exchangeCodeForSession(e.code,{flowId:e[oe]});if(x)throw x;let q=new URL(window.location.href);return q.searchParams.delete("code"),q.searchParams.delete(oe),window.history.replaceState(window.history.state,"",q.toString()),{data:{session:m.session,redirectType:(r=m.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:h}=e;if(!o||!c||!l||!h)throw new ye("No session defined in URL");let f=Math.round(Date.now()/1e3),y=parseInt(c),p=f+y;u&&(p=parseInt(u));let b=p-f;b*1e3<=te&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${b}s, should have been closer to ${y}s`);let E=p-y;f-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,p,f):f-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,p,f);let{data:A,error:C}=await this._getUser(o);if(C)throw C;let k={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:y,expires_at:p,refresh_token:l,token_type:h,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=Le(e[oe]);return t&&await F(this.storage,_e(this.storageKey,t))?!0:!!await F(this.storage,`${this.storageKey}-code-verifier`)}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 t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:o}=t;if(o&&!Ue(o))return this._returnResult({error:o});let l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){let{error:c}=await this.admin.signOut(l,e);if(c&&!(ut(c)&&(c.status===404||c.status===401||c.status===403)||Ue(c)))return e!=="others"&&await s(),this._returnResult({error:c})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=Xt(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),dt(i))return;Ue(i)||je(i)||ut(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;this.flowType==="pkce"&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(o){if(await Q(this.storage,this.storageKey,i),w(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async o=>{var l,c,u,h,f;let{data:y,error:p}=o;if(p)throw p;let{url:b,flowId:E}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(l=e.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=E,await g(this.fetch,"GET",b,{headers:this.headers,jwt:(f=(h=y.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(i)throw i;return K()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:r},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:l,token:c,access_token:u,nonce:h}=e,f=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:H}),{data:y,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!y||!y.session||!y.user?this._returnResult({data:{user:null,session:null},error:new ae}):(y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("USER_UPDATED",y.session)),this._returnResult({data:y,error:p}))}catch(s){if(await Q(this.storage,this.storageKey,null),w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)throw o;return await g(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{let r=Date.now();return await er(async s=>(s>0&&await Zt(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:H})),(s,i)=>{let o=200*Math.pow(2,s);return i&&je(i)&&Date.now()+o-r{});let i=await F(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(e);if(l)throw l;if(!o.session)throw new D;let c=await F(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let y={data:null,error:new Oe};return this.refreshingDeferred.resolve(y),y}let h=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await z(this.storage,this.storageKey),this.userStorage&&await z(this.userStorage,this.storageKey+"-user");let y={data:null,error:new Oe};return this.refreshingDeferred.resolve(y),y}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let f={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(f),f}catch(i){if(this._debug(s,"error",i),w(i)){let o={data:null,error:i};if(!je(i)){let l=await F(this.storage,this.storageKey);!!(l?.expires_at&&l.expires_at*1e3>Date.now())?this._debug(s,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+qt},(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:e,session:t,broadcast:r});return}let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;lthis._autoRefreshTokenTick(),te);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/te);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${te}ms, refresh threshold is ${Ee} ticks`),s<=Ee&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof Xe)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/te);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${te}ms, refresh threshold is ${Ee} ticks`),s<=Ee&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!K()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"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(t,"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(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=r?.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,l));let c=[`provider=${encodeURIComponent(t)}`];if(s&&c.push(`redirect_to=${encodeURIComponent(s)}`),r?.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){let u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r?.queryParams){let u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r?.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:nr(e,t)}async _getCodeChallengeAndMethod(e=!1){return ir(this.storage,this.storageKey,e,t=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",t))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await g(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Rt(e.webauthn.credential_response):Et(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;let{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:kt(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:St(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&i.factor_type in s&&Array.isArray(s[i.factor_type])&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:p}=Ne(e),b=null;p.aal&&(b=p.aal);let E=b,{data:{user:A},error:C}=await this.getUser(e);if(C)return this._returnResult({data:null,error:C});((r=(t=A?.factors)===null||t===void 0?void 0:t.filter(x=>x.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(E="aal2");let m=p.amr||[];return{data:{currentLevel:b,nextLevel:E,currentAuthenticationMethods:m},error:null}}catch(p){if(w(p))return this._returnResult({data:null,error:p});throw p}let{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ne(o.access_token),u=null;c.aal&&(u=c.aal);let h=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let y=c.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:y},error:null}}async _getRecoveryCodesStatus(){Ae(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){Ae(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:o,error:l}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):this._returnResult({data:o,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verifyRecoveryCode(e){Ae(this.experimental);let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let{data:l,error:c}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(c)return this._returnResult({data:null,error:c});let u=Object.assign({expires_at:Ve(l.expires_in)},l);return await this._saveSession(u),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:l,error:null})})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){Ae(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){Ae(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await g(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await g(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new D})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new D});let o=await g(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&K()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new D});let o=await g(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&K()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await g(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new D})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await g(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new D})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+Gt>s)return r;let{data:i,error:o}=await g(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:p,error:b}=await this.getSession();if(b||!p.session)return this._returnResult({data:null,error:b});r=p.session.access_token}let{header:s,payload:i,signature:o,raw:{header:l,payload:c}}=Ne(r);if(!t?.allowExpired)try{ar(i.exp)}catch(p){throw new ue(p instanceof Error?p.message:"JWT validation failed")}let u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){let{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:s,signature:o},error:null}}let h=lr(s.alg),f=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,f,o,Yt(`${l}.${c}`)))throw new ue("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var t,r,s,i;try{if(!qe())return this._returnResult({data:null,error:new B("Browser does not support WebAuthn",null)});let{data:o,error:l}=await this._startPasskeyAuthentication({options:{captchaToken:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}});if(l||!o)return this._returnResult({data:null,error:l});let c=St(o.options),u=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:et.createNewAbortSignal(),{data:h,error:f}=await It({publicKey:c,signal:u,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(f||!h)return this._returnResult({data:null,error:f??new B("WebAuthn ceremony failed",null)});let y=Et(h);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:y})}catch(o){if(w(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var t,r;try{if(!qe())return this._returnResult({data:null,error:new B("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let o=kt(s.options),l=(r=(t=e?.options)===null||t===void 0?void 0:t.signal)!==null&&r!==void 0?r:et.createNewAbortSignal(),{data:c,error:u}=await At({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new B("WebAuthn ceremony failed",null)});let h=Rt(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new D});let{data:s,error:i}=await g(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new D});let{data:i,error:o}=await g(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;try{let{data:r,error:s}=await g(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:r}=await g(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:H});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new D});let{data:s,error:i}=await g(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new D});let{data:i,error:o}=await g(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new D});let{error:i}=await g(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}};tt.nextInstanceID={};var Tt=tt;var es=Tt,xt=es;var he=document.querySelector("#app"),Me=document.querySelector("#notice"),d={auth:null,config:null,user:null,workspaces:[],workspace:null,tab:"sessions",generation:0,conversationAgent:"",search:"",channelId:"",threadId:"",channelSearch:""},br,st=[];function Rr(){for(let n of st.splice(0))n()}var Se=new URLSearchParams(location.search);Se.has("billing")&&(d.tab="billing");var jt="agentintercom-pending",N={};try{let n=JSON.parse(sessionStorage.getItem(jt)||"{}");n.until>Date.now()&&(N=n)}catch{}Se.get("authorization_id")&&(N.authorization=Se.get("authorization_id"));var Er=new URLSearchParams(location.hash.slice(1)),kr=Er.get("invite"),Sr=Er.get("device")||Se.get("device_code");Sr&&(N.device=Sr,history.replaceState(null,"",location.pathname+location.search));kr&&(N.invite=kr,history.replaceState(null,"",location.pathname+location.search));(N.authorization||N.invite||N.device)&&sessionStorage.setItem(jt,JSON.stringify({...N,until:Date.now()+1200*1e3}));function a(n,e={},...t){let r=document.createElement(n);for(let[s,i]of Object.entries(e))i==null||i===!1||(s.startsWith("on")?r.addEventListener(s.slice(2),i):s==="class"?r.className=i:s==="text"?r.textContent=i:r.setAttribute(s,i===!0?"":String(i)));for(let s of t.flat(1/0))s!=null&&r.append(s instanceof Node?s:document.createTextNode(String(s)));return r}function Y(n,e=!1){clearTimeout(br),Me.textContent=n,Me.hidden=!1,Me.className=e?"error":"",Me.setAttribute("role",e?"alert":"status"),br=setTimeout(()=>{Me.hidden=!0},e?15e3:6e3)}async function Te(n,e){if(!n?.disabled){n&&(n.disabled=!0);try{return await e()}catch(t){Y(t.message||"Something went wrong. Please try again.",!0)}finally{n&&(n.disabled=!1)}}}function _(n,e,t=""){return a("button",{type:"button",class:t,onclick:r=>Te(r.currentTarget,e)},n)}function M(n,e={}){let t=a(e.multiline?"textarea":"input",{...e,multiline:null});return{input:t,node:a("label",{},n,t)}}function V(n,e,t){let r=a("button",{type:"submit",class:"primary"},e);return a("form",{onsubmit:s=>{s.preventDefault(),Te(r,()=>t(new FormData(s.currentTarget)))}},n,r)}var fe=()=>a("div",{class:"brand"},a("span",{class:"mark","aria-hidden":!0},"o"),"agent intercom"),J=n=>n?new Date(n).toLocaleString():"\u2014",L=n=>`/api/workspaces/${encodeURIComponent(d.workspace.id)}${n}`;async function v(n,e={}){let t={"Content-Type":"application/json"};if(d.auth&&n!=="/api/config"){let{data:i,error:o}=await d.auth.getSession();if(o)throw o;i.session&&(t.Authorization=`Bearer ${i.session.access_token}`)}let r=await fetch(n,{method:e.method||"GET",credentials:"omit",headers:t,body:e.body==null?void 0:JSON.stringify(e.body),signal:AbortSignal.timeout(e.timeout||15e3)}),s=await r.json();if(!r.ok||s.ok===!1||s.error)throw new Error(s.error?.message||"The request could not be completed. Please try again.");return s.result}async function ot(n){await navigator.clipboard.writeText(n),Y("Copied to clipboard.")}var G=new Map,$t=n=>`${d.user.id} ${d.workspace.id} ${n}`;function Ar(n){d.conversationAgent=n;let e=$t("message");G.get(e)?.body||G.delete(e)}function ts(n){if(n)for(let e of[...G.keys()])e.startsWith(n+` `)&&G.delete(e)}async function Ir(n,e){let t=[],r=new Set,s="";for(;;){let i=await v(n+"/sessions"+(s?"?after="+encodeURIComponent(s):""));if(e.stale())break;let o=0;for(let l of i.sessions)r.has(l.id)||(r.add(l.id),t.push(l),o++);if(s=i.nextCursor,!s||!o)break}return t}function rs(n){let e=i=>{let o=new Map;for(let l of i)o.set(l,(o.get(l)||0)+1);return o},t=i=>i.deviceName===i.displayName?i.displayName:`${i.displayName} \xB7 ${i.deviceName}`,r=e(n.map(i=>i.displayName)),s=e(n.map(t));return new Map(n.map(i=>[i.id,r.get(i.displayName)===1?i.displayName:s.get(t(i))===1?t(i):`${t(i)} \xB7 ${i.id}`]))}var Ct=new WeakMap;async function Dt(n,e={}){let{data:t,error:r}=await d.auth.getSession();if(r)throw r;if(!t.session)throw new Error("Sign in again to access workspace files.");let s=await fetch(n,{...e,credentials:"omit",redirect:"error",headers:{Authorization:`Bearer ${t.session.access_token}`,"Content-Type":"application/octet-stream"},signal:AbortSignal.timeout(3e4)});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(i.error?.message||"File transfer failed. Please try again.")}return s}async function Tr(n,e){if(e.size>16*1024*1024)throw new Error("Files can be up to 16 MiB.");Ct.has(e)||Ct.set(e,crypto.randomUUID());let t=new URLSearchParams({name:e.name,mediaType:e.type.split(";")[0]||"application/octet-stream",idempotencyKey:Ct.get(e)}),s=await(await Dt(n+"/attachments?"+t,{method:"POST",body:e})).json();if(!s.ok)throw new Error(s.error?.message||"Upload failed.");return s.result}async function xr(n,e,t){let r=await Dt(n+"/attachments/"+encodeURIComponent(e)+"/content"),s=await r.arrayBuffer();if([...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(u=>u.toString(16).padStart(2,"0")).join("")!==r.headers.get("X-Content-SHA256"))throw new Error("File checksum did not match. The download was stopped.");let o=r.headers.get("Content-Disposition")||"";if(!t)try{t=decodeURIComponent(o.match(/filename\*=utf-8''([^;]+)/i)?.[1]||"")||o.match(/filename="([^"]+)"/)?.[1]||o.match(/filename=([^;]+)/)?.[1]}catch{}let l=URL.createObjectURL(new Blob([s],{type:"application/octet-stream"})),c=a("a",{href:l,download:(t||e).replace(/[\\/\x00-\x1f]/g,"_")});document.body.append(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}function Cr(n,e){let t=M("Attach a file",{type:"file"}),r=_("Upload and attach",async()=>{let s=t.input.files[0];if(!s)throw new Error("Choose a file first.");let i=t.input.closest("form")?.querySelector('[type="submit"]');i&&(i.disabled=!0);try{let o=await Tr(n,s);if(!e.isConnected){Y("File uploaded. Copy its reference from Files to share it.");return}e.value+=`${e.value?` `:""}${o.name}: ${o.uri}`,e.dispatchEvent(new Event("input",{bubbles:!0})),t.input.value="",Y("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Or(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>_(i?`Download ${i}`:"Download shared file",()=>xr(n,s,i))))}async function ss(){let n=L(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?_("Delete file",()=>ie("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),_("Delete permanently",async()=>{await v(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await O()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${J(l.createdAt)}`),a("div",{class:"actions"},_("Download",()=>xr(n,l.id,l.name)),_("Copy reference",()=>ot(l.uri)),u)))}},s=await v(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=M("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},V([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await Tr(n,o),await O()})),t),s.nextCursor){let o=s.nextCursor,l=_("More files",async()=>{let c=await v(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function nt(n){delete N[n],sessionStorage.setItem(jt,JSON.stringify({...N,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}var ns=0;function ie(n,e){let t=`modal-title-${++ns}`,r=a("dialog",{"aria-labelledby":t},a("h2",{id:t},n)),s=()=>r.close();return r.append(e(s),a("div",{class:"actions end"},_("Close",s))),r.addEventListener("close",()=>r.remove()),document.body.append(r),r.showModal(),r}function it(n,e,t){ie(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),_("Copy",()=>ot(e))))}function Ot(){Rr();let n=d.user?.id;d.user=null,ts(n);let e=M("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),t=V([e.node],"Continue with email",async o=>{let{error:l}=await d.auth.signInWithOtp({email:o.get("email"),options:{emailRedirectTo:location.origin+"/app"+(N.authorization?"?authorization_id="+encodeURIComponent(N.authorization):N.device?"?device_code="+encodeURIComponent(N.device):""),shouldCreateUser:!0}});if(l)throw l;Y("Check your email for an October sign-in link. Open it in this browser."),t.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),r=M("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),s=M("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),i=V([r.node,s.node],"Sign in",async o=>{let{error:l}=await d.auth.signInWithPassword({email:o.get("email"),password:o.get("password")});if(l)throw l;await ee()});he.replaceChildren(a("main",{id:"main",class:"auth-wrap"},fe(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),t,a("details",{},a("summary",{},"Use an existing password"),i),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function ee(){d.user=await v("/api/me"),d.workspaces=await v("/api/workspaces");let n=Se.has("billing")&&Se.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,N.invite)return is();if(N.authorization)return Pt();if(N.device)return Ut();if(!d.workspace)return Pr();await O()}function at(n){let e=M("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return V([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await v("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Pr(){he.replaceChildren(a("main",{id:"main",class:"auth-wrap"},fe(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),at(O),_("Sign out",Nt))))}async function Nt(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,Ot()}function Lt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Te(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function Pt(){let n=await v(`/api/oauth/requests/${encodeURIComponent(N.authorization)}`),e=d.workspace?.id,r=(e?await v(L("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await v(`/api/oauth/requests/${encodeURIComponent(N.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});nt("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Lt(Pt)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},_("Allow connection",()=>o(!0),"primary"),_("Cancel",()=>o(!1)))):at(Pt);he.replaceChildren(a("main",{id:"main",class:"consent"},fe(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function Ut(){let n=await v(`/api/device/authorizations/${encodeURIComponent(N.device)}`),e=d.workspace?.id,r=(e?await v(L("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await v(`/api/device/authorizations/${encodeURIComponent(N.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),nt("device"),he.replaceChildren(a("main",{id:"main",class:"consent"},fe(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),_("Open workspace",ee,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Lt(Ut)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},_("Connect this device",()=>o(!0),"primary"),_("Decline",()=>o(!1)))):at(Ut);he.replaceChildren(a("main",{id:"main",class:"consent"},fe(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function is(){he.replaceChildren(a("main",{id:"main",class:"consent"},fe(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},_("Accept invitation",async()=>{let n=await v("/api/invites/accept",{method:"POST",body:{token:N.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),nt("invite"),await ee()},"primary"),_("Use another account",Nt),_("Cancel",async()=>{nt("invite"),await ee()})))))}var rt={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function O(){if(Rr(),!d.workspace)return Pr();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(rt).map(([s,[i]])=>_(i,async()=>{d.tab=s,await O()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(rt)[i]===d.tab&&s.setAttribute("aria-current","page")}),he.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},fe(),a("div",{class:"workspace-switch"},Lt(O),_("+ New workspace",()=>ie("New workspace",s=>at(async()=>{s(),await O()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),_("Sign out",Nt,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},rt[d.tab][0]),a("p",{class:"muted"},rt[d.tab][1])),d.tab==="sessions"?_("Connect an app",async()=>{d.tab="connect",await O()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:ws,billing:ps,files:ss,channels:fs,messages:us,tasks:ds,questions:hs,sessions:os,connect:as,members:ls}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),_("Try again",O)))}}async function os(){let n=a("div"),e=a("div",{class:"grid"}),t=await v(L("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${J(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},_("Open conversation",async()=>{Ar(i.id),d.tab="messages",await O()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),_("Copy session ID",()=>ot(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),_("Connect an app",async()=>{d.tab="connect",await O()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=_("Show more sessions",async()=>{let o=await v(L("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),_("Refresh sessions",O)),n}function as(){let n=d.config.mcpUrl,e=L("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),_("Copy connector URL",()=>ot(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),V([M("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await v(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});it("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${J(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default -agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),V([M("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await v(L("/devices"),{method:"POST",body:{name:t.get("name")}});it("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function ls(){let n=L(""),[e,t]=await Promise.all([v(L("/members")),v(L("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await v(L(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await ee()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>ie("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await v(L(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await ee()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${J(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>ie("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let f=await v(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),it("Replacement MCP key",f.token,`Update your app\u2019s secret/API key field. Shown once; expires ${J(f.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>ie("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await v(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await O()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${J(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=M("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=V([l.node],"Create invitation",async f=>{let y=await v(L("/invites"),{method:"POST",body:{email:f.get("email"),role:"member"}});it("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(y.token)}`,`Share this link with ${y.email}. It expires ${J(y.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await v(L("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let f of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},f.email),a("p",{class:"help"},`Expires ${J(f.expiresAt)}`)),_("Revoke invitation",async()=>{await v(L(`/invites/${encodeURIComponent(f.id)}`),{method:"DELETE"}),await O()},"danger")));o.append(h)}return o}async function cs(){if(d.config=await v("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new xt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await ee():Ot(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,Ot()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Te(null,ee),0)})}cs().catch(n=>{he.replaceChildren(a("main",{id:"main",class:"auth-wrap"},fe(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});async function us(){let n=d.generation,e=L(""),t=$t("message"),r=d.workspace.id,s={stale:()=>n!==d.generation||d.workspace?.id!==r},[i,o]=await Promise.all([Ir(e,s),v(e+"/members")]),l=rs(i),c=new Map(i.map(R=>["agent:"+R.id,R.displayName]));for(let R of o)c.set("human:"+R.userId,R.email);let u=(R,U)=>c.get(R+":"+U)||U,h=new URLSearchParams;d.conversationAgent&&h.set("agentId",d.conversationAgent),d.search&&h.set("query",d.search);let f=a("select",{"aria-label":"Filter by session",onchange:R=>{Ar(R.target.value),Te(null,O)}},a("option",{value:""},"All sessions"),i.map(R=>a("option",{value:R.id,selected:R.id===d.conversationAgent},l.get(R.id)))),y=M("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),p=V([y.node],"Search",async R=>{d.search=R.get("query").trim(),await O()}),b=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",f),p)),E=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),A=new Map,C=!0,S=!1;st.push(()=>{C=!1});let m=R=>R.responseMessageId?"Replied":R.state==="acknowledged"?R.toKind==="human"?"Read":"Acknowledged":R.state==="delivered"?"Delivered to app":R.state==="expired"?"Expired":"Waiting for delivery",x=(R,U=!1)=>{let k=U?[...R.messages].reverse():R.messages;for(let T of k){let Z=JSON.stringify(T),I=A.get(T.id);if(I?.fingerprint===Z)continue;let W=a("article",{class:"card",id:T.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},u(T.fromKind,T.from))," \u2192 ",u(T.toKind,T.to),a("p",{class:"help"},J(T.createdAt))),a("span",{class:"badge"},m(T))),a("p",{class:"message"},T.body));W.append(Or(e,T.body,T.context)),T.responseTo&&W.append(a("p",{class:"help"},"Reply to ",a("code",{},T.responseTo))),T.toKind==="human"&&T.to===d.user.id&&T.state!=="acknowledged"&&T.state!=="expired"&&W.append(_("Mark read",async()=>{await v(e+"/messages/read",{method:"POST",body:{messageIds:[T.id]}}),await O()},"subtle-button")),I?I.node.replaceWith(W):U?E.prepend(W):E.append(W),A.set(T.id,{fingerprint:Z,node:W})}},q=await v(e+"/messages?"+h);x(q);let P=h.toString(),j=setInterval(async()=>{if(d.generation!==n){clearInterval(j);return}if(!(!C||S||document.hidden)){S=!0;try{let R=await v(e+"/messages?"+P);C&&(R.messages.length&&E.querySelector(".empty")?.remove(),x(R,!0))}catch(R){C&&Y("Conversation refresh failed. "+R.message,!0)}finally{S=!1}}},5e3);if(st.push(()=>clearInterval(j)),q.messages.length||E.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),b.append(E),q.nextCursor){let R=q.nextCursor,U=_("Earlier messages",async()=>{h.set("before",R);let k=await v(e+"/messages?"+h);x(k),R=k.nextCursor,R||U.remove()});b.append(U)}if(i.length){let R=a("select",{name:"to",required:!0},i.map(I=>a("option",{value:I.id,selected:I.id===d.conversationAgent},l.get(I.id)+(I.reachable?"":" \xB7 offline")))),U=M("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),k=G.get(t);k?.body&&(U.input.value=k.body),k?.body&&k.to&&!i.some(I=>I.id===k.to)?(R.prepend(a("option",{value:""},"Recipient unavailable \u2014 choose a session")),R.value=""):k?.to&&i.some(I=>I.id===k.to)&&(R.value=k.to);let T=()=>{let I=JSON.stringify([R.value,U.input.value]),W=G.get(t);G.set(t,{to:R.value,body:U.input.value,fingerprint:I,key:W?.fingerprint===I?W.key:crypto.randomUUID()})};R.addEventListener("change",T),U.input.addEventListener("input",T);let Z=V([a("label",{},"Send to",R),U.node,Cr(e,U.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async I=>{T();let{key:W}=G.get(t);await v(e+"/messages",{method:"POST",body:{to:I.get("to"),body:I.get("body"),mode:"request",idempotencyKey:W}}),G.get(t)?.key===W&&G.delete(t),d.conversationAgent=I.get("to"),d.search="",Y("Request saved. Delivery status will update when the app checks its inbox."),await O()});b.append(a("section",{class:"card"},a("h2",{},"Send a message"),Z))}else b.append(_("Connect an app",async()=>{d.tab="connect",await O()},"primary"));return b.append(_("Refresh conversation",O)),b}async function ds(){let n=L(""),e=await v(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},J(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await v(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=M("Task title",{name:"title",maxlength:256,required:!0}),o=M("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),V([i.node,o.node],"Create task",async l=>{await v(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),Y("Task created. An agent can now claim it."),await O()}))),t}async function hs(){let n=L(""),e=await v(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=M("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",J(i.createdAt)),a("div",{class:"actions"},l),V([o.node],"Send answer",async c=>{await v(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),Y("Answer saved for the requesting session."),await O()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await v(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",O)),t}async function fs(){let n=d.generation,e=L(""),t=$t("channel"),r=await v(e+"/channels"),s=r.find(k=>k.id===d.channelId)||r[0];s?.id!==d.channelId&&(d.threadId=""),d.channelId=s?.id||"";let i=()=>ie("Create a channel",k=>V([M("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,M("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async T=>{let Z=await v(e+"/channels",{method:"POST",body:{name:T.get("name"),description:T.get("description")}});d.channelId=Z.id,d.threadId="",d.channelSearch="",k(),await O()}));if(!s)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",i,"primary"));let o=a("select",{"aria-label":"Channel",onchange:k=>{d.channelId=k.target.value,d.threadId="",d.channelSearch="",Te(null,O)}},r.map(k=>a("option",{value:k.id,selected:k.id===s.id},"#"+k.name))),l=V([M("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async k=>{d.channelSearch=k.get("query").trim(),d.threadId="",await O()}),c=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",o),_("New channel",i)),a("p",{},s.description),a("p",{class:"help"},`${s.subscribers} subscribed sessions. Ask a connected session to join #${s.name} using subscribe_channel to receive future notifications.`),l));d.threadId&&c.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await O()})));let u=new URLSearchParams({channelId:s.id});d.threadId&&u.set("threadId",d.threadId),d.channelSearch&&u.set("query",d.channelSearch);let h=d.workspace.id,f={stale:()=>n!==d.generation||d.workspace?.id!==h},[y,p,b]=await Promise.all([v(e+"/channel-posts?"+u),v(e+"/members"),Ir(e,f)]),E=new Map(p.map(k=>["human:"+k.userId,k.email]));for(let k of b)E.set("agent:"+k.id,k.displayName);let A=a("div",{class:"conversation-list","aria-label":"Channel posts"}),C=new Map,S=(k,T=!1)=>{let Z=T?[...k.posts].reverse():k.posts;for(let I of Z){let W=JSON.stringify(I),lt=C.get(I.id);if(lt?.fingerprint===W)continue;let Re=a("article",{class:"card"},a("div",{class:"row"},a("strong",{},E.get(I.authorKind+":"+I.authorId)||I.authorId),a("small",{},J(I.createdAt))),a("p",{class:"message"},I.body));Re.append(Or(e,I.body)),(!d.threadId||d.channelSearch)&&Re.append(_(I.replies?`${I.replies} ${I.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=I.threadId||I.id,d.channelSearch="",await O()})),lt?lt.node.replaceWith(Re):T?A.prepend(Re):A.append(Re),C.set(I.id,{fingerprint:W,node:Re})}};if(S(y),y.posts.length||A.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),c.append(A),y.nextCursor){let k=y.nextCursor,T=_("Earlier posts",async()=>{let Z=new URLSearchParams(u);Z.set("before",k);let I=await v(e+"/channel-posts?"+Z);S(I),k=I.nextCursor,k||T.remove()});c.append(T)}let m=M(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),x=t+` +agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),V([M("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await v(L("/devices"),{method:"POST",body:{name:t.get("name")}});it("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function ls(){let n=L(""),[e,t]=await Promise.all([v(L("/members")),v(L("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await v(L(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await ee()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>ie("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await v(L(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await ee()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${J(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>ie("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let f=await v(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),it("Replacement MCP key",f.token,`Update your app\u2019s secret/API key field. Shown once; expires ${J(f.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>ie("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await v(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await O()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${J(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=M("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=V([l.node],"Create invitation",async f=>{let y=await v(L("/invites"),{method:"POST",body:{email:f.get("email"),role:"member"}});it("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(y.token)}`,`Share this link with ${y.email}. It expires ${J(y.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await v(L("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let f of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},f.email),a("p",{class:"help"},`Expires ${J(f.expiresAt)}`)),_("Revoke invitation",async()=>{await v(L(`/invites/${encodeURIComponent(f.id)}`),{method:"DELETE"}),await O()},"danger")));o.append(h)}return o}async function cs(){if(d.config=await v("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new xt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await ee():Ot(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,Ot()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Te(null,ee),0)})}cs().catch(n=>{he.replaceChildren(a("main",{id:"main",class:"auth-wrap"},fe(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});async function us(){let n=d.generation,e=L(""),t=$t("message"),r=d.workspace.id,s={stale:()=>n!==d.generation||d.workspace?.id!==r},[i,o]=await Promise.all([Ir(e,s),v(e+"/members")]),l=rs(i),c=new Map(i.map(R=>["agent:"+R.id,R.displayName]));for(let R of o)c.set("human:"+R.userId,R.email);let u=(R,U)=>c.get(R+":"+U)||U,h=new URLSearchParams;d.conversationAgent&&h.set("agentId",d.conversationAgent),d.search&&h.set("query",d.search);let f=a("select",{"aria-label":"Filter by session",onchange:R=>{Ar(R.target.value),Te(null,O)}},a("option",{value:""},"All sessions"),i.map(R=>a("option",{value:R.id,selected:R.id===d.conversationAgent},l.get(R.id)))),y=M("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),p=V([y.node],"Search",async R=>{d.search=R.get("query").trim(),await O()}),b=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",f),p)),E=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),A=new Map,C=!0,k=!1;st.push(()=>{C=!1});let m=R=>R.responseMessageId?"Replied":R.state==="acknowledged"?R.toKind==="human"?"Read":"Acknowledged":R.state==="delivered"?"Delivered to app":R.state==="expired"?"Expired":"Waiting for delivery",x=(R,U=!1)=>{let S=U?[...R.messages].reverse():R.messages;for(let T of S){let Z=JSON.stringify(T),I=A.get(T.id);if(I?.fingerprint===Z)continue;let W=a("article",{class:"card",id:T.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},u(T.fromKind,T.from))," \u2192 ",u(T.toKind,T.to),a("p",{class:"help"},J(T.createdAt))),a("span",{class:"badge"},m(T))),a("p",{class:"message"},T.body));W.append(Or(e,T.body,T.context)),T.responseTo&&W.append(a("p",{class:"help"},"Reply to ",a("code",{},T.responseTo))),T.toKind==="human"&&T.to===d.user.id&&T.state!=="acknowledged"&&T.state!=="expired"&&W.append(_("Mark read",async()=>{await v(e+"/messages/read",{method:"POST",body:{messageIds:[T.id]}}),await O()},"subtle-button")),I?I.node.replaceWith(W):U?E.prepend(W):E.append(W),A.set(T.id,{fingerprint:Z,node:W})}},q=await v(e+"/messages?"+h);x(q);let P=h.toString(),j=setInterval(async()=>{if(d.generation!==n){clearInterval(j);return}if(!(!C||k||document.hidden)){k=!0;try{let R=await v(e+"/messages?"+P);C&&(R.messages.length&&E.querySelector(".empty")?.remove(),x(R,!0))}catch(R){C&&Y("Conversation refresh failed. "+R.message,!0)}finally{k=!1}}},5e3);if(st.push(()=>clearInterval(j)),q.messages.length||E.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),b.append(E),q.nextCursor){let R=q.nextCursor,U=_("Earlier messages",async()=>{h.set("before",R);let S=await v(e+"/messages?"+h);x(S),R=S.nextCursor,R||U.remove()});b.append(U)}if(i.length){let R=a("select",{name:"to",required:!0},i.map(I=>a("option",{value:I.id,selected:I.id===d.conversationAgent},l.get(I.id)+(I.reachable?"":" \xB7 offline")))),U=M("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),S=G.get(t);S?.body&&(U.input.value=S.body),S?.body&&!i.some(I=>I.id===S.to)?(R.prepend(a("option",{value:""},"Recipient unavailable \u2014 choose a session")),R.value=""):S?.to&&i.some(I=>I.id===S.to)&&(R.value=S.to);let T=()=>{let I=JSON.stringify([R.value,U.input.value]),W=G.get(t);G.set(t,{to:R.value,body:U.input.value,fingerprint:I,key:W?.fingerprint===I?W.key:crypto.randomUUID()})};R.addEventListener("change",T),U.input.addEventListener("input",T);let Z=V([a("label",{},"Send to",R),U.node,Cr(e,U.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async I=>{T();let{key:W}=G.get(t);await v(e+"/messages",{method:"POST",body:{to:I.get("to"),body:I.get("body"),mode:"request",idempotencyKey:W}}),G.get(t)?.key===W&&G.delete(t),d.conversationAgent=I.get("to"),d.search="",Y("Request saved. Delivery status will update when the app checks its inbox."),await O()});b.append(a("section",{class:"card"},a("h2",{},"Send a message"),Z))}else b.append(_("Connect an app",async()=>{d.tab="connect",await O()},"primary"));return b.append(_("Refresh conversation",O)),b}async function ds(){let n=L(""),e=await v(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},J(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await v(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=M("Task title",{name:"title",maxlength:256,required:!0}),o=M("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),V([i.node,o.node],"Create task",async l=>{await v(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),Y("Task created. An agent can now claim it."),await O()}))),t}async function hs(){let n=L(""),e=await v(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=M("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",J(i.createdAt)),a("div",{class:"actions"},l),V([o.node],"Send answer",async c=>{await v(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),Y("Answer saved for the requesting session."),await O()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await v(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",O)),t}async function fs(){let n=d.generation,e=L(""),t=$t("channel"),r=await v(e+"/channels"),s=r.find(S=>S.id===d.channelId)||r[0];s?.id!==d.channelId&&(d.threadId=""),d.channelId=s?.id||"";let i=()=>ie("Create a channel",S=>V([M("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,M("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async T=>{let Z=await v(e+"/channels",{method:"POST",body:{name:T.get("name"),description:T.get("description")}});d.channelId=Z.id,d.threadId="",d.channelSearch="",S(),await O()}));if(!s)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",i,"primary"));let o=a("select",{"aria-label":"Channel",onchange:S=>{d.channelId=S.target.value,d.threadId="",d.channelSearch="",Te(null,O)}},r.map(S=>a("option",{value:S.id,selected:S.id===s.id},"#"+S.name))),l=V([M("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async S=>{d.channelSearch=S.get("query").trim(),d.threadId="",await O()}),c=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",o),_("New channel",i)),a("p",{},s.description),a("p",{class:"help"},`${s.subscribers} subscribed sessions. Ask a connected session to join #${s.name} using subscribe_channel to receive future notifications.`),l));d.threadId&&c.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await O()})));let u=new URLSearchParams({channelId:s.id});d.threadId&&u.set("threadId",d.threadId),d.channelSearch&&u.set("query",d.channelSearch);let h=d.workspace.id,f={stale:()=>n!==d.generation||d.workspace?.id!==h},[y,p,b]=await Promise.all([v(e+"/channel-posts?"+u),v(e+"/members"),Ir(e,f)]),E=new Map(p.map(S=>["human:"+S.userId,S.email]));for(let S of b)E.set("agent:"+S.id,S.displayName);let A=a("div",{class:"conversation-list","aria-label":"Channel posts"}),C=new Map,k=(S,T=!1)=>{let Z=T?[...S.posts].reverse():S.posts;for(let I of Z){let W=JSON.stringify(I),lt=C.get(I.id);if(lt?.fingerprint===W)continue;let Re=a("article",{class:"card"},a("div",{class:"row"},a("strong",{},E.get(I.authorKind+":"+I.authorId)||I.authorId),a("small",{},J(I.createdAt))),a("p",{class:"message"},I.body));Re.append(Or(e,I.body)),(!d.threadId||d.channelSearch)&&Re.append(_(I.replies?`${I.replies} ${I.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=I.threadId||I.id,d.channelSearch="",await O()})),lt?lt.node.replaceWith(Re):T?A.prepend(Re):A.append(Re),C.set(I.id,{fingerprint:W,node:Re})}};if(k(y),y.posts.length||A.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),c.append(A),y.nextCursor){let S=y.nextCursor,T=_("Earlier posts",async()=>{let Z=new URLSearchParams(u);Z.set("before",S);let I=await v(e+"/channel-posts?"+Z);k(I),S=I.nextCursor,S||T.remove()});c.append(T)}let m=M(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),x=t+` ${s.id} -${d.threadId||""}`,q=G.get(x);q?.body&&(m.input.value=q.body);let P=()=>{let k=G.get(x);G.set(x,{body:m.input.value,key:k?.body===m.input.value&&k.key?k.key:crypto.randomUUID()})};m.input.addEventListener("input",P),c.append(a("section",{class:"card"},V([m.node,Cr(e,m.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async k=>{P();let{key:T}=G.get(x);await v(e+"/channel-posts",{method:"POST",body:{channelId:s.id,body:k.get("body"),threadId:d.threadId||void 0,idempotencyKey:T}}),G.get(x)?.key===T&&G.delete(x),d.channelSearch="",await O()})));let j=!0,R=!1,U=setInterval(async()=>{if(d.generation!==n){clearInterval(U);return}if(!(!j||R||document.hidden)){R=!0;try{let k=await v(e+"/channel-posts?"+u);j&&(k.posts.length&&A.querySelector(".empty")?.remove(),S(k,!0))}catch(k){j&&Y("Channel refresh failed. "+k.message,!0)}finally{R=!1}}},5e3);return st.push(()=>{j=!1,clearInterval(U)}),c}async function ps(){let n=L("/billing"),e=await v(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=f=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(f/100),i=f=>f>=1024**3?`${(f/1024**3).toFixed(1)} GiB`:`${(f/1024**2).toFixed(1)} MiB`,o=f=>Number(f).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),Se.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${J(e.paidUntil)}.`:r?`Trial ends ${J(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${J(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(f,y){let p=await v(n+"/"+f,{method:"POST",body:y,timeout:3e4}),b=new URL(p.url);if(b.protocol!=="https:"||b.username||b.password||!["checkout.stripe.com","billing.stripe.com"].includes(b.host))throw new Error("Payment destination could not be verified.");location.assign(b.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await v(n+"/refresh",{method:"POST",timeout:3e4}),await O(),Y("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await v(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await O()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[f,y,p,b]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},f),a("span",{},`${b(y)} / ${b(p)}`)),a("progress",{max:p,value:Math.min(y,p),"aria-label":f})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ws(){let n=L(""),e=d.workspace,t=await v(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>ie(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await v(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await ee()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Dt(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=M("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),V([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await v(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});ie("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await v(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await O(),Y("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>ie("Permanently delete this workspace?",o=>{let l=M("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),V([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await v(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await ee(),u}o(),await ee(),Y("Workspace deleted.")}))}),"danger"))),s} +${d.threadId||""}`,q=G.get(x);q?.body&&(m.input.value=q.body);let P=()=>{let S=G.get(x);G.set(x,{body:m.input.value,key:S?.body===m.input.value&&S.key?S.key:crypto.randomUUID()})};m.input.addEventListener("input",P),c.append(a("section",{class:"card"},V([m.node,Cr(e,m.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async S=>{P();let{key:T}=G.get(x);await v(e+"/channel-posts",{method:"POST",body:{channelId:s.id,body:S.get("body"),threadId:d.threadId||void 0,idempotencyKey:T}}),G.get(x)?.key===T&&G.delete(x),d.channelSearch="",await O()})));let j=!0,R=!1,U=setInterval(async()=>{if(d.generation!==n){clearInterval(U);return}if(!(!j||R||document.hidden)){R=!0;try{let S=await v(e+"/channel-posts?"+u);j&&(S.posts.length&&A.querySelector(".empty")?.remove(),k(S,!0))}catch(S){j&&Y("Channel refresh failed. "+S.message,!0)}finally{R=!1}}},5e3);return st.push(()=>{j=!1,clearInterval(U)}),c}async function ps(){let n=L("/billing"),e=await v(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=f=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(f/100),i=f=>f>=1024**3?`${(f/1024**3).toFixed(1)} GiB`:`${(f/1024**2).toFixed(1)} MiB`,o=f=>Number(f).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),Se.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${J(e.paidUntil)}.`:r?`Trial ends ${J(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${J(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(f,y){let p=await v(n+"/"+f,{method:"POST",body:y,timeout:3e4}),b=new URL(p.url);if(b.protocol!=="https:"||b.username||b.password||!["checkout.stripe.com","billing.stripe.com"].includes(b.host))throw new Error("Payment destination could not be verified.");location.assign(b.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await v(n+"/refresh",{method:"POST",timeout:3e4}),await O(),Y("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await v(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await O()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[f,y,p,b]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},f),a("span",{},`${b(y)} / ${b(p)}`)),a("progress",{max:p,value:Math.min(y,p),"aria-label":f})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ws(){let n=L(""),e=d.workspace,t=await v(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>ie(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await v(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await ee()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Dt(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=M("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),V([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await v(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});ie("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await v(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await O(),Y("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>ie("Permanently delete this workspace?",o=>{let l=M("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),V([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await v(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await ee(),u}o(),await ee(),Y("Workspace deleted.")}))}),"danger"))),s} diff --git a/web/src/app.js b/web/src/app.js index a215fff..cfe7d34 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -415,7 +415,7 @@ async function messagesView() { const body = field('Your message', { name: 'body', multiline: true, required: true, maxlength: 65536, placeholder: 'What would you like this session to help with?' }); const restored = drafts.get(messageKey); if (restored?.body) body.input.value = restored.body; - if (restored?.body && restored.to && !sessions.some(s => s.id === restored.to)) { target.prepend(el('option', { value: '' }, 'Recipient unavailable — choose a session')); target.value = ''; } + if (restored?.body && !sessions.some(s => s.id === restored.to)) { target.prepend(el('option', { value: '' }, 'Recipient unavailable — choose a session')); target.value = ''; } else if (restored?.to && sessions.some(s => s.id === restored.to)) target.value = restored.to; const saveDraft = () => { const fingerprint = JSON.stringify([target.value, body.input.value]); diff --git a/web/tests/workspace.spec.js b/web/tests/workspace.spec.js index 09d4d19..ad17fb3 100644 --- a/web/tests/workspace.spec.js +++ b/web/tests/workspace.spec.js @@ -649,6 +649,8 @@ test('a late upload never writes into another workspace draft', async ({ page }) await expect(composer).toHaveValue('Workspace two text'); await page.locator('select[aria-label="Workspace"]').selectOption('workspace-1'); await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('Workspace one text'); + await page.locator('select[aria-label="Workspace"]').selectOption('workspace-2'); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('Workspace two text'); }); test('text typed while a send is pending survives the send', async ({ page }) => { @@ -693,6 +695,15 @@ test('a draft addressed to a vanished session blocks sending until a new recipie await page.getByRole('button', { name: 'Send request', exact: true }).click(); expect(events.filter(e => e.method === 'POST')).toHaveLength(0); await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('Hello there'); + await page.getByLabel('Your message', { exact: true }).fill('Hello there, edited'); + await page.getByRole('button', { name: 'Tasks', exact: true }).click(); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('Hello there, edited'); + await expect(sendTo).toHaveValue(''); + await sendTo.selectOption('stays-1'); + await page.getByRole('button', { name: 'Send request', exact: true }).click(); + await expect(page.getByText('Hello there, edited', { exact: true })).toBeVisible(); + expect(events.filter(e => e.method === 'POST' && e.path.endsWith('/messages')).at(-1).body.to).toBe('stays-1'); }); test('a retry after navigation reuses the failed send idempotency key', async ({ page }) => {