orquesta-embed 0.1.37 → 0.1.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/version.d.ts +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/vanilla.js +1 -1
- package/dist/vanilla.min.js +1 -1
- package/package.json +1 -1
package/dist/vanilla.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Orquesta=function(e){"use strict";function t(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(r[n[s]]=e[n[s]])}return r}function r(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}l((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class n extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class s extends n{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class i extends n{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class o extends n{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var a;!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(a||(a={}));class l{constructor(e,{headers:t={},customFetch:r,region:n=a.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return r(this,arguments,void 0,function*(e,t={}){var r;let n,a;try{const{headers:l,method:c,body:h,signal:u,timeout:d}=t;let p={},{region:m}=t;m||(m=this.region);const g=new URL(`${this.url}/${e}`);let f;m&&"any"!==m&&(p["x-region"]=m,g.searchParams.set("forceFunctionRegion",m)),h&&(l&&!Object.prototype.hasOwnProperty.call(l,"Content-Type")||!l)?"undefined"!=typeof Blob&&h instanceof Blob||h instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",f=h):"string"==typeof h?(p["Content-Type"]="text/plain",f=h):"undefined"!=typeof FormData&&h instanceof FormData?f=h:(p["Content-Type"]="application/json",f=JSON.stringify(h)):f=!h||"string"==typeof h||"undefined"!=typeof Blob&&h instanceof Blob||h instanceof ArrayBuffer||"undefined"!=typeof FormData&&h instanceof FormData?h:JSON.stringify(h);let b=u;d&&(a=new AbortController,n=setTimeout(()=>a.abort(),d),u?(b=a.signal,u.addEventListener("abort",()=>a.abort())):b=a.signal);const w=yield this.fetch(g.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),l),body:f,signal:b}).catch(e=>{throw new s(e)}),y=w.headers.get("x-relay-error");if(y&&"true"===y)throw new i(w);if(!w.ok)throw new o(w);let v,x=(null!==(r=w.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return v="application/json"===x?yield w.json():"application/octet-stream"===x||"application/pdf"===x?yield w.blob():"text/event-stream"===x?w:"multipart/form-data"===x?yield w.formData():yield w.text(),{data:v,error:null,response:w}}catch(e){return{data:null,error:e,response:e instanceof o||e instanceof i?e.context:void 0}}finally{n&&clearTimeout(n)}})}}var c=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},h=class{constructor(e){var t,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var r=this;void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let n=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,n=null,s=null,i=e.status,o=e.statusText;if(e.ok){var a,l;if("HEAD"!==r.method){var h;const t=await e.text();""===t||(n="text/csv"===r.headers.get("Accept")||r.headers.get("Accept")&&(null===(h=r.headers.get("Accept"))||void 0===h?void 0:h.includes("application/vnd.pgrst.plan+text"))?t:JSON.parse(t))}const c=null===(a=r.headers.get("Prefer"))||void 0===a?void 0:a.match(/count=(exact|planned|estimated)/),u=null===(l=e.headers.get("content-range"))||void 0===l?void 0:l.split("/");c&&u&&u.length>1&&(s=parseInt(u[1])),r.isMaybeSingle&&"GET"===r.method&&Array.isArray(n)&&(n.length>1?(t={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,s=null,i=406,o="Not Acceptable"):n=1===n.length?n[0]:null)}else{var u;const s=await e.text();try{t=JSON.parse(s),Array.isArray(t)&&404===e.status&&(n=[],t=null,i=200,o="OK")}catch(r){404===e.status&&""===s?(i=204,o="No Content"):t={message:s}}if(t&&r.isMaybeSingle&&(null==t||null===(u=t.details)||void 0===u?void 0:u.includes("0 rows"))&&(t=null,i=200,o="OK"),t&&r.shouldThrowOnError)throw new c(t)}return{error:t,data:n,count:s,status:i,statusText:o}});return this.shouldThrowOnError||(n=n.catch(e=>{var t;let r="";const n=null==e?void 0:e.cause;if(n){var s,i,o,a;const t=null!==(s=null==n?void 0:n.message)&&void 0!==s?s:"",l=null!==(i=null==n?void 0:n.code)&&void 0!==i?i:"";r=`${null!==(o=null==e?void 0:e.name)&&void 0!==o?o:"FetchError"}: ${null==e?void 0:e.message}`,r+=`\n\nCaused by: ${null!==(a=null==n?void 0:n.name)&&void 0!==a?a:"Error"}: ${t}`,l&&(r+=` (${l})`),(null==n?void 0:n.stack)&&(r+=`\n${n.stack}`)}else{var l;r=null!==(l=null==e?void 0:e.stack)&&void 0!==l?l:""}return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:r,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),n.then(e,t)}returns(){return this}overrideTypes(){return this}},u=class extends h{select(e){let t=!1;const r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:n,referencedTable:s=n}={}){const i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const n=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:n=r}={}){const s=void 0===n?"offset":`${n}.offset`,i=void 0===n?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:n=!1,wal:s=!1,format:i="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,r?"settings":null,n?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=null!==(o=this.headers.get("Accept"))&&void 0!==o?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const d=new RegExp("[,()]");var p=class extends u{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&d.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&d.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:n}={}){let s="";"plain"===n?s="pl":"phrase"===n?s="ph":"websearch"===n&&(s="w");const i=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${s}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},m=class{constructor(e,{headers:t={},schema:r,fetch:n}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:r=!1,count:n}=null!=t?t:{},s=r?"HEAD":"GET";let i=!1;const o=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new p({method:s,url:a,headers:l,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){var n;const{url:s,headers:i}=this.cloneRequestState();if(t&&i.append("Prefer",`count=${t}`),r||i.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);s.searchParams.set("columns",e.join(","))}}return new p({method:"POST",url:s,headers:i,schema:this.schema,body:e,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:n,defaultToNull:s=!0}={}){var i;const{url:o,headers:a}=this.cloneRequestState();if(a.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&o.searchParams.set("on_conflict",t),n&&a.append("Prefer",`count=${n}`),s||a.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);o.searchParams.set("columns",e.join(","))}}return new p({method:"POST",url:o,headers:a,schema:this.schema,body:e,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}update(e,{count:t}={}){var r;const{url:n,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new p({method:"PATCH",url:n,headers:s,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:e}={}){var t;const{url:r,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new p({method:"DELETE",url:r,headers:n,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch})}},g=class e{constructor(e,{headers:t={},schema:r,fetch:n}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=n}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");return new m(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:n=!1,count:s}={}){var i;let o;const a=new URL(`${this.url}/rpc/${e}`);let l;const c=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(c)),h=r&&Object.values(t).some(c);h?(o="POST",l=t):r||n?(o=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{a.searchParams.append(e,t)})):(o="POST",l=t);const u=new Headers(this.headers);return h?u.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&u.set("Prefer",`count=${s}`),new p({method:o,url:a,headers:u,schema:this.schemaName,body:l,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}};class f{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const t=globalThis.process;if(t){const e=t.versions;if(e&&e.node){const t=e.node,r=parseInt(t.replace(/^v/,"").split(".")[0]);return r>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const b="1.0.0",w=b,y=1e4;var v,x,_,k,S,C;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(v||(v={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(x||(x={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(_||(_={})),function(e){e.websocket="websocket"}(k||(k={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(S||(S={}));class E{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const n=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var t,r;const n=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:{},s=(new TextEncoder).encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,s)}_encodeUserBroadcastPush(e,t,r){var n,s;const i=e.topic,o=null!==(n=e.ref)&&void 0!==n?n:"",a=null!==(s=e.join_ref)&&void 0!==s?s:"",l=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=0===Object.keys(c).length?"":JSON.stringify(c);if(a.length>255)throw new Error(`joinRef length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const u=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+o.length+i.length+l.length+h.length,d=new ArrayBuffer(this.HEADER_LENGTH+u);let p=new DataView(d),m=0;p.setUint8(m++,this.KINDS.userBroadcastPush),p.setUint8(m++,a.length),p.setUint8(m++,o.length),p.setUint8(m++,i.length),p.setUint8(m++,l.length),p.setUint8(m++,h.length),p.setUint8(m++,t),Array.from(a,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(o,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(i,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(l,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(h,e=>p.setUint8(m++,e.charCodeAt(0)));var g=new Uint8Array(d.byteLength+r.byteLength);return g.set(new Uint8Array(d),0),g.set(new Uint8Array(r),d.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e)){return t(this._binaryDecode(e))}if("string"==typeof e){const r=JSON.parse(e),[n,s,i,o,a]=r;return t({join_ref:n,ref:s,topic:i,event:o,payload:a})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),n=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,n)}_decodeUserBroadcast(e,t,r){const n=t.getUint8(1),s=t.getUint8(2),i=t.getUint8(3),o=t.getUint8(4);let a=this.HEADER_LENGTH+4;const l=r.decode(e.slice(a,a+n));a+=n;const c=r.decode(e.slice(a,a+s));a+=s;const h=r.decode(e.slice(a,a+i));a+=i;const u=e.slice(a,e.byteLength),d=o===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:c,payload:d};return i>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}class T{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(C||(C={}));const O=(e,t,r={})=>{var n;const s=null!==(n=r.skipTypes)&&void 0!==n?n:[];return t?Object.keys(t).reduce((r,n)=>(r[n]=R(n,e,t,s),r),{}):{}},R=(e,t,r,n)=>{const s=t.find(t=>t.name===e),i=null==s?void 0:s.type,o=r[e];return i&&!n.includes(i)?q(i,o):A(o)},q=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return P(t,r)}switch(e){case C.bool:return $(t);case C.float4:case C.float8:case C.int2:case C.int4:case C.int8:case C.numeric:case C.oid:return I(t);case C.json:case C.jsonb:return j(t);case C.timestamp:return N(t);case C.abstime:case C.date:case C.daterange:case C.int4range:case C.int8range:case C.money:case C.reltime:case C.text:case C.time:case C.timestamptz:case C.timetz:case C.tsrange:case C.tstzrange:default:return A(t)}},A=e=>e,$=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},I=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},j=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}return e},P=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,n=e[r];if("{"===e[0]&&"}"===n){let n;const s=e.slice(1,r);try{n=JSON.parse("["+s+"]")}catch(e){n=s?s.split(","):[]}return n.map(e=>q(t,e))}return e},N=e=>"string"==typeof e?e.replace(" ","T"):e,U=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class L{constructor(e,t,r={},n=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null===(r=this.receivedResp)||void 0===r?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var B,M,z,D;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(B||(B={}));class H{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{const{onJoin:t,onLeave:r,onSync:n}=this.caller;this.joinRef=this.channel._joinRef(),this.state=H.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=H.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],n()}),this.channel._on(r.diff,{},e=>{const{onJoin:t,onLeave:r,onSync:n}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=H.syncDiff(this.state,e,t,r),n())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,n){const s=this.cloneDeep(e),i=this.transformState(t),o={},a={};return this.map(s,(e,t)=>{i[e]||(a[e]=t)}),this.map(i,(e,t)=>{const r=s[e];if(r){const n=t.map(e=>e.presence_ref),s=r.map(e=>e.presence_ref),i=t.filter(e=>s.indexOf(e.presence_ref)<0),l=r.filter(e=>n.indexOf(e.presence_ref)<0);i.length>0&&(o[e]=i),l.length>0&&(a[e]=l)}else o[e]=t}),this.syncDiff(s,{joins:o,leaves:a},r,n)}static syncDiff(e,t,r,n){const{joins:s,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),n||(n=()=>{}),this.map(s,(t,n)=>{var s;const i=null!==(s=e[t])&&void 0!==s?s:[];if(e[t]=this.cloneDeep(n),i.length>0){const r=e[t].map(e=>e.presence_ref),n=i.filter(e=>r.indexOf(e.presence_ref)<0);e[t].unshift(...n)}r(t,i,n)}),this.map(i,(t,r)=>{let s=e[t];if(!s)return;const i=r.map(e=>e.presence_ref);s=s.filter(e=>i.indexOf(e.presence_ref)<0),e[t]=s,n(t,s,r),0===s.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const n=e[r];return t[r]="metas"in n?n.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):n,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(M||(M={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(z||(z={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(D||(D={}));class F{constructor(e,t={config:{}},r){var n,s;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=x.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new L(this,_.join,this.params,this.timeout),this.rejoinTimer=new T(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=x.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=x.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this._on(_.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new H(this),this.broadcastEndpointURL=U(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(s=null===(n=this.params.config)||void 0===n?void 0:n.broadcast)||void 0===s?void 0:s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,n,s;if(this.socket.isConnected()||this.socket.connect(),this.state==x.closed){const{config:{broadcast:i,presence:o,private:a}}=this.params,l=null!==(n=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==n?n:[],c=!!this.bindings[z.PRESENCE]&&this.bindings[z.PRESENCE].length>0||!0===(null===(s=this.params.config.presence)||void 0===s?void 0:s.enabled),h={},u={broadcast:i,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:l,private:a};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(D.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(D.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var r;if(this.socket._isManualToken()||this.socket.setAuth(),void 0!==t){const n=this.bindings.postgres_changes,s=null!==(r=null==n?void 0:n.length)&&void 0!==r?r:0,i=[];for(let r=0;r<s;r++){const s=n[r],{filter:{event:o,schema:a,table:l,filter:c}}=s,h=t&&t[r];if(!(h&&h.event===o&&F.isFilterValueEqual(h.schema,a)&&F.isFilterValueEqual(h.table,l)&&F.isFilterValueEqual(h.filter,c)))return this.unsubscribe(),this.state=x.errored,void(null==e||e(D.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));i.push(Object.assign(Object.assign({},s),{id:h.id}))}return this.bindings.postgres_changes=i,void(e&&e(D.SUBSCRIBED))}null==e||e(D.SUBSCRIBED)}).receive("error",t=>{this.state=x.errored,null==e||e(D.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(D.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===x.joined&&e===z.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var n;if(null==t)return Promise.reject("Payload is required for httpSend()");const s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);const i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!==(n=r.timeout)&&void 0!==n?n:this.timeout);if(202===o.status)return{success:!0};let a=o.statusText;try{const e=await o.json();a=e.error||e.message||a}catch(e){}return Promise.reject(new Error(a))}async send(e,t={}){var r,n;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var n,s,i;const o=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(i=null===(s=null===(n=this.params)||void 0===n?void 0:n.config)||void 0===s?void 0:s.broadcast)||void 0===i?void 0:i.ack)||r("ok"),o.receive("ok",()=>r("ok")),o.receive("error",()=>r("error")),o.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:s,payload:i}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:i,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);return await(null===(n=e.body)||void 0===n?void 0:n.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=x.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(_.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(n=>{r=new L(this,_.leave,{},e),r.receive("ok",()=>{t(),n("ok")}).receive("timeout",()=>{t(),n("timed out")}).receive("error",()=>{n("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{null==r||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=x.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const n=new AbortController,s=setTimeout(()=>n.abort(),r),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(s),i}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new L(this,e,t,r);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var n,s;const i=e.toLocaleLowerCase(),{close:o,error:a,leave:l,join:c}=_;if(r&&[o,a,l,c].indexOf(i)>=0&&r!==this._joinRef())return;let h=this._onMessage(i,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?null===(n=this.bindings.postgres_changes)||void 0===n||n.filter(e=>{var t,r,n;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(n=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===n?void 0:n.toLocaleLowerCase())===i}).map(e=>e.callback(h,r)):null===(s=this.bindings[i])||void 0===s||s.filter(e=>{var r,n,s,o,a,l,c,h;if(["broadcast","presence","postgres_changes"].includes(i)){if("id"in e){const i=e.id,l=null===(r=e.filter)||void 0===r?void 0:r.event;return i&&(null===(n=t.ids)||void 0===n?void 0:n.includes(i))&&("*"===l||(null==l?void 0:l.toLocaleLowerCase())===(null===(s=t.data)||void 0===s?void 0:s.type.toLocaleLowerCase()))&&(!(null===(o=e.filter)||void 0===o?void 0:o.table)||e.filter.table===(null===(a=t.data)||void 0===a?void 0:a.table))}{const r=null===(c=null===(l=null==e?void 0:e.filter)||void 0===l?void 0:l.event)||void 0===c?void 0:c.toLocaleLowerCase();return"*"===r||r===(null===(h=null==t?void 0:t.event)||void 0===h?void 0:h.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===i}).map(e=>{if("object"==typeof h&&"ids"in h){const e=h.data,{schema:t,table:r,commit_timestamp:n,type:s,errors:i}=e,o={schema:t,table:r,commit_timestamp:n,eventType:s,new:{},old:{},errors:i};h=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===x.closed}_isJoined(){return this.state===x.joined}_isJoining(){return this.state===x.joining}_isLeaving(){return this.state===x.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const n=e.toLocaleLowerCase(),s={type:n,filter:t,callback:r};return this.bindings[n]?this.bindings[n].push(s):this.bindings[n]=[s],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(e=>{var n;return!((null===(n=e.type)||void 0===n?void 0:n.toLocaleLowerCase())===r&&F.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(_.close,{},e)}_onError(e){this._on(_.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=x.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=O(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=O(e.columns,e.old_record)),t}}const W=()=>{},K=25e3,J=10,G=100,V=[1e3,2e3,5e3,1e4];class X{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=y,this.transport=null,this.heartbeatIntervalMs=K,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=W,this.ref=0,this.reconnectTimer=null,this.vsn=w,this.logger=W,this.conn=null,this.sendBuffer=[],this.serializer=new E,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${k.websocket}`,this.httpEndpoint=U(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=f.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case v.connecting:return S.Connecting;case v.open:return S.Open;case v.closing:return S.Closing;default:return S.Closed}}isConnected(){return this.connectionState()===S.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const r=`realtime:${e}`,n=this.getChannels().find(e=>e.topic===r);if(n)return n;{const r=new F(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){const{topic:t,event:r,payload:n,ref:s}=e,i=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${r} (${s})`,n),this.isConnected()?i():this.sendBuffer.push(i)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},G)}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event&&e.ref&&e.ref===this.pendingHeartbeatRef){const t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error",t)}catch(e){this.log("error","error in heartbeat callback",e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:t,event:r,payload:n,ref:s}=e,i=s?`(${s})`:"",o=n.status||"";this.log("receive",`${o} ${t} ${r} ${i}`.trim(),n),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,n,s)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===v.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===v.open||this.conn.readyState===v.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`);(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(_.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const r={access_token:t,version:"realtime-js/2.90.1"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push(_.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new T(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},J)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,n,s,i,o,a,l,c,h,u,d;switch(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(r=null==e?void 0:e.timeout)&&void 0!==r?r:y,this.heartbeatIntervalMs=null!==(n=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==n?n:K,this.worker=null!==(s=null==e?void 0:e.worker)&&void 0!==s&&s,this.accessToken=null!==(i=null==e?void 0:e.accessToken)&&void 0!==i?i:null,this.heartbeatCallback=null!==(o=null==e?void 0:e.heartbeatCallback)&&void 0!==o?o:W,this.vsn=null!==(a=null==e?void 0:e.vsn)&&void 0!==a?a:w,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(l=null==e?void 0:e.reconnectAfterMs)&&void 0!==l?l:e=>V[e-1]||1e4,this.vsn){case b:this.encode=null!==(c=null==e?void 0:e.encode)&&void 0!==c?c:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(h=null==e?void 0:e.decode)&&void 0!==h?h:(e,t)=>t(JSON.parse(e));break;case"2.0.0":this.encode=null!==(u=null==e?void 0:e.encode)&&void 0!==u?u:this.serializer.encode.bind(this.serializer),this.decode=null!==(d=null==e?void 0:e.decode)&&void 0!==d?d:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}var Y=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function Q(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:s,body:i,headers:o}){const a=function(e,t,r){const n=new URL(t,e);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&n.searchParams.set(e,t);return n.toString()}(e.baseUrl,n,s),l=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),c=await t(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),h=await c.text(),u=(c.headers.get("content-type")||"").includes("application/json"),d=u&&h?JSON.parse(h):h;if(!c.ok){const e=u?d:void 0,t=e?.error;throw new Y(t?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:c.status,headers:c.headers,data:d}}}}function Z(e){return e.join("")}var ee=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:Z(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){const r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Z(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Z(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Z(e.namespace)}`}),!0}catch(e){if(e instanceof Y&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof Y&&409===e.status)return;throw e}}};function te(e){return e.join("")}var re=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const r={};this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof Y&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof Y&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},ne=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Q({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new ee(this.client,t),this.tableOps=new re(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},se=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function ie(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var oe=class extends se{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},ae=class extends se{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};const le=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),ce=e=>{if(Array.isArray(e))return e.map(e=>ce(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,r])=>{const n=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[n]=ce(r)}),t};function he(e){return(he="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ue(e){var t=function(e,t){if("object"!=he(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=he(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==he(t)?t:t+""}function de(e,t,r){return(t=ue(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function pe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function me(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?pe(Object(r),!0).forEach(function(t){de(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):pe(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const ge=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null===(t=e.error)||void 0===t?void 0:t.message)||JSON.stringify(e)},fe=async(e,t,r)=>{e instanceof await Response&&!(null==r?void 0:r.noResolveJson)?e.json().then(r=>{const n=e.status||500,s=(null==r?void 0:r.statusCode)||n+"";t(new oe(ge(r),n,s))}).catch(e=>{t(new ae(ge(e),e))}):t(new ae(ge(e),e))},be=(e,t,r,n)=>{const s={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&n?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(n)?(s.headers=me({"Content-Type":"application/json"},null==t?void 0:t.headers),s.body=JSON.stringify(n)):s.body=n,(null==t?void 0:t.duplex)&&(s.duplex=t.duplex),me(me({},s),r)):s};async function we(e,t,r,n,s,i){return new Promise((o,a)=>{e(r,be(t,n,s,i)).then(e=>{if(!e.ok)throw e;return(null==n?void 0:n.noResolveJson)?e:e.json()}).then(e=>o(e)).catch(e=>fe(e,a,n))})}async function ye(e,t,r,n){return we(e,"GET",t,r,n)}async function ve(e,t,r,n,s){return we(e,"POST",t,n,s,r)}async function xe(e,t,r,n,s){return we(e,"PUT",t,n,s,r)}async function _e(e,t,r,n,s){return we(e,"DELETE",t,n,s,r)}var ke=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}};let Se;Se=Symbol.toStringTag;var Ce=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Se]="BlobDownloadBuilder",this.promise=null}asStream(){return new ke(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await(await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}};const Ee={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Te={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Oe=class{constructor(e,t={},r,n){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=le(n)}throwOnError(){return this.shouldThrowOnError=!0,this}async uploadOrUpdate(e,t,r,n){var s=this;try{let i;const o=me(me({},Te),n);let a=me(me({},s.headers),"POST"===e&&{"x-upsert":String(o.upsert)});const l=o.metadata;"undefined"!=typeof Blob&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=s.toBase64(s.encodeMetadata(l))),("undefined"!=typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!o.duplex&&(o.duplex="half")),(null==n?void 0:n.headers)&&(a=me(me({},a),n.headers));const c=s._removeEmptyFolders(t),h=s._getFinalPath(c),u=await("PUT"==e?xe:ve)(s.fetch,`${s.url}/object/${h}`,i,me({headers:a},(null==o?void 0:o.duplex)?{duplex:o.duplex}:{}));return{data:{path:c,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,n){var s=this;const i=s._removeEmptyFolders(e),o=s._getFinalPath(i),a=new URL(s.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let e;const t=me({upsert:Te.upsert},n),o=me(me({},s.headers),{"x-upsert":String(t.upsert)});return"undefined"!=typeof Blob&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r,e.append("cacheControl",t.cacheControl)):(e=r,o["cache-control"]=`max-age=${t.cacheControl}`,o["content-type"]=t.contentType),{data:{path:i,fullPath:(await xe(s.fetch,a.toString(),e,{headers:o})).Key},error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createSignedUploadUrl(e,t){var r=this;try{let n=r._getFinalPath(e);const s=me({},r.headers);(null==t?void 0:t.upsert)&&(s["x-upsert"]="true");const i=await ve(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:s}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new se("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var n=this;try{return{data:await ve(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:n.headers}),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async copy(e,t,r){var n=this;try{return{data:{path:(await ve(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:n.headers})).Key},error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createSignedUrl(e,t,r){var n=this;try{let s=n._getFinalPath(e),i=await ve(n.fetch,`${n.url}/object/sign/${s}`,me({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:n.headers});const o=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return i={signedUrl:encodeURI(`${n.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createSignedUrls(e,t,r){var n=this;try{const s=await ve(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:t,paths:e},{headers:n.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:s.map(e=>me(me({},e),{},{signedUrl:e.signedURL?encodeURI(`${n.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}download(e,t){const r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",n=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),s=n?`?${n}`:"",i=this._getFinalPath(e);return new Ce(()=>ye(this.fetch,`${this.url}/${r}/${i}${s}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}async info(e){var t=this;const r=t._getFinalPath(e);try{return{data:ce(await ye(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async exists(e){var t=this;const r=t._getFinalPath(e);try{return await async function(e,t,r,n){return we(e,"HEAD",t,me(me({},r),{},{noResolveJson:!0}),n)}(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e)&&e instanceof ae){const t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){const r=this._getFinalPath(e),n=[],s=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==s&&n.push(s);const i=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&n.push(o);let a=n.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${a}`)}}}async remove(e){var t=this;try{return{data:await _e(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async list(e,t,r){var n=this;try{const s=me(me(me({},Ee),t),{},{prefix:e||""});return{data:await ve(n.fetch,`${n.url}/object/list/${n.bucketId}`,s,{headers:n.headers},r),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async listV2(e,t){var r=this;try{const n=me({},e);return{data:await ve(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},t),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};const Re="2.90.1",qe={"X-Client-Info":`storage-js/${Re}`};var Ae=class{constructor(e,t={},r,n){this.shouldThrowOnError=!1;const s=new URL(e);(null==n?void 0:n.useNewHostname)&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase.")),this.url=s.href.replace(/\/$/,""),this.headers=me(me({},qe),t),this.fetch=le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async listBuckets(e){var t=this;try{const r=t.listBucketOptionsToQueryString(e);return{data:await ye(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await ye(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createBucket(e,t={public:!1}){var r=this;try{return{data:await ve(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async updateBucket(e,t){var r=this;try{return{data:await xe(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async emptyBucket(e){var t=this;try{return{data:await ve(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await _e(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},$e=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=me(me({},qe),t),this.fetch=le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await ve(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async listBuckets(e){var t=this;try{const r=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&r.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);const n=r.toString(),s=n?`${t.url}/bucket?${n}`:`${t.url}/bucket`;return{data:await ye(t.fetch,s,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await _e(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}from(e){var t=this;if(!(e=>!(!e||"string"!=typeof e)&&!(0===e.length||e.length>100)&&e.trim()===e&&!e.includes("/")&&!e.includes("\\")&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e))(e))throw new se("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new ne({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(e,t){const r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(n)throw e;return{data:null,error:e}}}}})}};const Ie={"X-Client-Info":`storage-js/${Re}`,"Content-Type":"application/json"};var je=class extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}};function Pe(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}var Ne=class extends je{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Ue=class extends je{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}};const Le=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Be=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Me=(e,t,r,n)=>{const s={method:e,headers:(null==t?void 0:t.headers)||{}};return n?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(n)?(s.headers=me({"Content-Type":"application/json"},null==t?void 0:t.headers),s.body=JSON.stringify(n)):s.body=n,me(me({},s),r)):s};async function ze(e,t,r,n,s,i){return new Promise((o,a)=>{e(r,Me(t,n,s,i)).then(e=>{if(!e.ok)throw e;if(null==n?void 0:n.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>o(e)).catch(e=>(async(e,t,r)=>{if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==r?void 0:r.noResolveJson)){const r=e.status||500,n=e;if("function"==typeof n.json)n.json().then(e=>{const n=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new Ne(Be(e),r,n))}).catch(()=>{const e=r+"";t(new Ne(n.statusText||`HTTP ${r} error`,r,e))});else{const e=r+"";t(new Ne(n.statusText||`HTTP ${r} error`,r,e))}}else t(new Ue(Be(e),e))})(e,a,n))})}async function De(e,t,r,n,s){return ze(e,"POST",t,n,s,r)}var He=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=me(me({},Ie),t),this.fetch=Le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createIndex(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async getIndex(e,t){var r=this;try{return{data:await De(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async listIndexes(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async deleteIndex(e,t){var r=this;try{return{data:await De(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}},Fe=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=me(me({},Ie),t),this.fetch=Le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async putVectors(e){var t=this;try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:await De(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async getVectors(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async listVectors(e){var t=this;try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:await De(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async queryVectors(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async deleteVectors(e){var t=this;try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:await De(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}},We=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=me(me({},Ie),t),this.fetch=Le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async listBuckets(e={}){var t=this;try{return{data:await De(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}},Ke=class extends We{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Je(this.url,this.headers,e,this.fetch)}async createBucket(e){return(()=>super.createBucket)().call(this,e)}async getBucket(e){return(()=>super.getBucket)().call(this,e)}async listBuckets(e={}){return(()=>super.listBuckets)().call(this,e)}async deleteBucket(e){return(()=>super.deleteBucket)().call(this,e)}},Je=class extends He{constructor(e,t,r,n){super(e,t,n),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,me(me({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,me(me({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return(()=>super.getIndex)().call(this,this.vectorBucketName,e)}async deleteIndex(e){return(()=>super.deleteIndex)().call(this,this.vectorBucketName,e)}index(e){return new Ge(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Ge=class extends Fe{constructor(e,t,r,n,s){super(e,t,s),this.vectorBucketName=r,this.indexName=n}async putVectors(e){var t=this;return(()=>super.putVectors)().call(t,me(me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,me(me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,me(me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,me(me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,me(me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},Ve=class extends Ae{constructor(e,t={},r,n){super(e,t,r,n)}from(e){return new Oe(this.url,this.headers,e,this.fetch)}get vectors(){return new Ke(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new $e(this.url+"/iceberg",this.headers,this.fetch)}};const Xe="2.90.1",Ye=3e4,Qe=9e4,Ze={"X-Client-Info":`gotrue-js/${Xe}`},et="X-Supabase-Api-Version",tt={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},rt=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class nt extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function st(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class it extends nt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class ot extends nt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class at extends nt{constructor(e,t,r,n){super(e,r,n),this.name=t,this.status=r}}class lt extends at{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class ct extends at{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ht extends at{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ut extends at{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class dt extends at{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class pt extends at{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class mt extends at{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function gt(e){return st(e)&&"AuthRetryableFetchError"===e.name}class ft extends at{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class bt extends at{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),yt=" \t\n\r=".split(""),vt=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<yt.length;t+=1)e[yt[t].charCodeAt(0)]=-2;for(let t=0;t<wt.length;t+=1)e[wt[t].charCodeAt(0)]=t;return e})();function xt(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(wt[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(wt[e]),t.queuedBits-=6}}function _t(e,t,r){const n=vt[e];if(!(n>-1)){if(-2===n)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|n,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function kt(e){const t=[],r=e=>{t.push(String.fromCodePoint(e))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return void r(e);for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,n,r)};for(let t=0;t<e.length;t+=1)_t(e.charCodeAt(t),s,i);return t.join("")}function St(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function Ct(e){const t=[],r={queue:0,queuedBits:0},n=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)_t(e.charCodeAt(t),r,n);return new Uint8Array(t)}function Et(e){const t=[];return function(e,t){for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>55295&&n<=56319){const t=1024*(n-55296)&65535;n=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}St(n,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function Tt(e){const t=[],r={queue:0,queuedBits:0},n=e=>{t.push(e)};return e.forEach(e=>xt(e,r,n)),xt(null,r,n),t.join("")}const Ot=()=>"undefined"!=typeof window&&"undefined"!=typeof document,Rt={tested:!1,writable:!1},qt=()=>{if(!Ot())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(Rt.tested)return Rt.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Rt.tested=!0,Rt.writable=!0}catch(e){Rt.tested=!0,Rt.writable=!1}return Rt.writable};const At=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),$t=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},It=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},jt=async(e,t)=>{await e.removeItem(t)};class Pt{constructor(){this.promise=new Pt.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function Nt(e){const t=e.split(".");if(3!==t.length)throw new bt("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!rt.test(t[e]))throw new bt("JWT not in base64url format");return{header:JSON.parse(kt(t[0])),payload:JSON.parse(kt(t[1])),signature:Ct(t[2]),raw:{header:t[0],payload:t[1]}}}function Ut(e){return("0"+e.toString(16)).substr(-2)}async function Lt(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(r);return Array.from(n).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Bt(e,t,r=!1){const n=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let n=0;n<56;n++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,Ut).join("")}();let s=n;r&&(s+="/PASSWORD_RECOVERY"),await $t(e,`${t}-code-verifier`,s);const i=await Lt(n);return[i,n===i?"plain":"s256"]}Pt.promiseConstructor=Promise;const Mt=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const zt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Dt(e){if(!zt.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ht(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)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 Ft(e){return JSON.parse(JSON.stringify(e))}const Wt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Kt=[502,503,504];async function Jt(e){var t,r;if(!("object"==typeof(r=e)&&null!==r&&"status"in r&&"ok"in r&&"json"in r&&"function"==typeof r.json))throw new mt(Wt(e),0);if(Kt.includes(e.status))throw new mt(Wt(e),e.status);let n,s;try{n=await e.json()}catch(e){throw new ot(Wt(e),e)}const i=function(e){const t=e.headers.get(et);if(!t)return null;if(!t.match(Mt))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=tt.timestamp&&"object"==typeof n&&n&&"string"==typeof n.code?s=n.code:"object"==typeof n&&n&&"string"==typeof n.error_code&&(s=n.error_code),s){if("weak_password"===s)throw new ft(Wt(n),e.status,(null===(t=n.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===s)throw new lt}else if("object"==typeof n&&n&&"object"==typeof n.weak_password&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new ft(Wt(n),e.status,n.weak_password.reasons);throw new it(Wt(n),e.status||500,s)}async function Gt(e,t,r,n){var s;const i=Object.assign({},null==n?void 0:n.headers);i[et]||(i[et]=tt.name),(null==n?void 0:n.jwt)&&(i.Authorization=`Bearer ${n.jwt}`);const o=null!==(s=null==n?void 0:n.query)&&void 0!==s?s:{};(null==n?void 0:n.redirectTo)&&(o.redirect_to=n.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await async function(e,t,r,n,s,i){const o=((e,t,r,n)=>{const s={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),r))})(t,n,s,i);let a;try{a=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new mt(Wt(e),0)}a.ok||await Jt(a);if(null==n?void 0:n.noResolveJson)return a;try{return await a.json()}catch(e){await Jt(e)}}(e,t,r+a,{headers:i,noResolveJson:null==n?void 0:n.noResolveJson},{},null==n?void 0:n.body);return(null==n?void 0:n.xform)?null==n?void 0:n.xform(l):{data:Object.assign({},l),error:null}}function Vt(e){var t;let r=null;var n;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=(n=e.expires_in,Math.round(Date.now()/1e3)+n)));return{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function Xt(e){const t=Vt(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function Yt(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function Qt(e){return{data:e,error:null}}function Zt(e){const{action_link:r,email_otp:n,hashed_token:s,redirect_to:i,verification_type:o}=e,a=t(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:r,email_otp:n,hashed_token:s,redirect_to:i,verification_type:o},user:Object.assign({},a)},error:null}}function er(e){return e}const tr=["global","local","others"];class rr{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=At(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=tr[0]){if(tr.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${tr.join(", ")}`);try{return await Gt(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(st(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await Gt(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Yt})}catch(e){if(st(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:r}=e,n=t(e,["options"]),s=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(s.new_email=null==n?void 0:n.newEmail,delete s.newEmail),await Gt(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Zt,redirectTo:null==r?void 0:r.redirectTo})}catch(e){if(st(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await Gt(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Yt})}catch(e){if(st(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,n,s,i,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await Gt(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(s=null===(n=null==e?void 0:e.perPage)||void 0===n?void 0:n.toString())&&void 0!==s?s:""},xform:er});if(c.error)throw c.error;const h=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(st(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Dt(e);try{return await Gt(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Yt})}catch(e){if(st(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Dt(e);try{return await Gt(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Yt})}catch(e){if(st(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Dt(e);try{return await Gt(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Yt})}catch(e){if(st(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Dt(e.userId);try{const{data:t,error:r}=await Gt(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(st(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Dt(e.userId),Dt(e.id);try{return{data:await Gt(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(st(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,n,s,i,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await Gt(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(s=null===(n=null==e?void 0:e.perPage)||void 0===n?void 0:n.toString())&&void 0!==s?s:""},xform:er});if(c.error)throw c.error;const h=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(st(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await Gt(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(st(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await Gt(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(st(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await Gt(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(st(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await Gt(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(st(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await Gt(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(st(e))return{data:null,error:e};throw e}}}function nr(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}const sr=!!(globalThis&&qt()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class ir extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class or extends ir{}async function ar(e,t,r){sr&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const n=new globalThis.AbortController;return t>0&&setTimeout(()=>{n.abort(),sr&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async n=>{if(!n){if(0===t)throw sr&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new or(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(sr)try{const e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}sr&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,n.name);try{return await r()}finally{sr&&console.log("@supabase/gotrue-js: navigatorLock: released",e,n.name)}}))}function lr(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function cr(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class hr extends Error{constructor({message:e,code:t,cause:r,name:n}){var s;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!==(s=null!=n?n:r instanceof Error?r.name:void 0)&&void 0!==s?s:"Unknown Error",this.code=t}}class ur extends hr{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function dr({error:e,options:t}){var r,n,s;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new hr({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(r=i.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey))return new hr({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(n=i.authenticatorSelection)||void 0===n?void 0:n.userVerification))return new hr({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(s=i.authenticatorSelection)||void 0===s?void 0:s.userVerification))return new hr({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new hr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new hr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===i.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new hr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new hr({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!yr(t))return new hr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(i.rp.id!==t)return new hr({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new hr({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new hr({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new hr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function pr({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new hr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new hr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!yr(t))return new hr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new hr({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new hr({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new hr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const mr=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function gr(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:r,user:n,excludeCredentials:s}=e,i=t(e,["challenge","user","excludeCredentials"]),o=Ct(r).buffer,a=Object.assign(Object.assign({},n),{id:Ct(n.id).buffer}),l=Object.assign(Object.assign({},i),{challenge:o,user:a});if(s&&s.length>0){l.excludeCredentials=new Array(s.length);for(let e=0;e<s.length;e++){const t=s[e];l.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:Ct(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return l}function fr(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:r,allowCredentials:n}=e,s=t(e,["challenge","allowCredentials"]),i=Ct(r).buffer,o=Object.assign(Object.assign({},s),{challenge:i});if(n&&n.length>0){o.allowCredentials=new Array(n.length);for(let e=0;e<n.length;e++){const t=n[e];o.allowCredentials[e]=Object.assign(Object.assign({},t),{id:Ct(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function br(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e;return{id:e.id,rawId:e.id,response:{attestationObject:Tt(new Uint8Array(e.response.attestationObject)),clientDataJSON:Tt(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function wr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e,n=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Tt(new Uint8Array(s.authenticatorData)),clientDataJSON:Tt(new Uint8Array(s.clientDataJSON)),signature:Tt(new Uint8Array(s.signature)),userHandle:s.userHandle?Tt(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function yr(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function vr(){var e,t;return!!(Ot()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const xr={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},_r={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function kr(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),n={};for(const s of e)if(s)for(const e in s){const i=s[e];if(void 0!==i)if(Array.isArray(i))n[e]=i;else if(r(i))n[e]=i;else if(t(i)){const r=n[e];t(r)?n[e]=kr(r,i):n[e]=kr(i)}else n[e]=i}return n}class Sr{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:n},s){try{const{data:i,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!i)return{data:null,error:o};const a=null!=n?n:mr.createNewAbortSignal();if("create"===i.webauthn.type){const{user:e}=i.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${r}`),e.displayName||(e.displayName=e.name)}switch(i.webauthn.type){case"create":{const t=function(e,t){return kr(xr,e,t||{})}(i.webauthn.credential_options.publicKey,null==s?void 0:s.create),{data:r,error:n}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new ur("Browser returned unexpected credential type",t)}:{data:null,error:new ur("Empty credential response",t)}}catch(t){return{data:null,error:dr({error:t,options:e})}}}({publicKey:t,signal:a});return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:n}}case"request":{const t=function(e,t){return kr(_r,e,t||{})}(i.webauthn.credential_options.publicKey,null==s?void 0:s.request),{data:r,error:n}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new ur("Browser returned unexpected credential type",t)}:{data:null,error:new ur("Empty credential response",t)}}catch(t){return{data:null,error:pr({error:t,options:e})}}}(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:t,signal:a}));return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:n}}}}catch(e){return st(e)?{data:null,error:e}:{data:null,error:new ot("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:n}={}},s){if(!t)return{data:null,error:new nt("rpId is required for WebAuthn authentication")};try{if(!vr())return{data:null,error:new ot("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:n},{request:s});if(!i)return{data:null,error:o};const{webauthn:a}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:a.type,rpId:t,rpOrigins:r,credential_response:a.credential_response}})}catch(e){return st(e)?{data:null,error:e}:{data:null,error:new ot("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:n}={}},s){if(!t)return{data:null,error:new nt("rpId is required for WebAuthn registration")};try{if(!vr())return{data:null,error:new ot("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(t=>{var r;return null===(r=t.data)||void 0===r?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:o};const{data:a,error:l}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:n},{create:s});return a?this._verify({factorId:i.id,challengeId:a.challengeId,webauthn:{rpId:t,rpOrigins:r,type:a.webauthn.type,credential_response:a.webauthn.credential_response}}):{data:null,error:l}}catch(e){return st(e)?{data:null,error:e}:{data:null,error:new ot("Unexpected error in register",e)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const Cr={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ze,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function Er(e,t,r){return await r()}const Tr={};class Or{get jwks(){var e,t;return null!==(t=null===(e=Tr[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){Tr[this.storageKey]=Object.assign(Object.assign({},Tr[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=Tr[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Tr[this.storageKey]=Object.assign(Object.assign({},Tr[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const s=Object.assign(Object.assign({},Cr),e);if(this.storageKey=s.storageKey,this.instanceID=null!==(t=Or.nextInstanceID[this.storageKey])&&void 0!==t?t:0,Or.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,"function"==typeof s.debug&&(this.logger=s.debug),this.instanceID>0&&Ot()){const e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new rr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=At(s.fetch),this.lock=s.lock||Er,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&Ot()&&(null===(r=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===r?void 0:r.locks)?this.lock=ar:this.lock=Er,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new Sr(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(s.storage?this.storage=s.storage:qt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=nr(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=nr(this.memoryStorage)),Ot()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(n=this.broadcastChannel)||void 0===n||n.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Xe}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(Ot()&&(t=function(e){const t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),Ot()&&this.detectSessionInUrl&&"none"!==r){const{data:n,error:s}=await this._getSessionFromURL(t,r);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),function(e){return st(e)&&"AuthImplicitGrantRedirectError"===e.name}(s)){const t=null===(e=s.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:s}}return{error:s}}const{session:i,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",o),await this._saveSession(i),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return st(e)?this._returnResult({error:e}):this._returnResult({error:new ot("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,n;try{const s=await Gt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==r?r:{},gotrue_meta_security:{captcha_token:null===(n=null==e?void 0:e.options)||void 0===n?void 0:n.captchaToken}},xform:Vt}),{data:i,error:o}=s;if(o||!i)return this._returnResult({data:{user:null,session:null},error:o});const a=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,n;try{let s;if("email"in e){const{email:r,password:n,options:i}=e;let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Bt(this.storage,this.storageKey)),s=await Gt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==i?void 0:i.emailRedirectTo,body:{email:r,password:n,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:o,code_challenge_method:a},xform:Vt})}else{if(!("phone"in e))throw new ht("You must provide either an email or phone number and a password");{const{phone:t,password:i,options:o}=e;s=await Gt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:i,data:null!==(r=null==o?void 0:o.data)&&void 0!==r?r:{},channel:null!==(n=null==o?void 0:o.channel)&&void 0!==n?n:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:Vt})}}const{data:i,error:o}=s;if(o||!i)return await jt(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const a=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:r,password:n,options:s}=e;t=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},xform:Xt})}else{if(!("phone"in e))throw new ht("You must provide either an email or phone number and a password");{const{phone:r,password:n,options:s}=e;t=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},xform:Xt})}}const{data:r,error:n}=t;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!r||!r.session||!r.user){const e=new ct;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:n})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(n=e.options)||void 0===n?void 0:n.queryParams,skipBrowserRedirect:null===(s=e.options)||void 0===s?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{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,n,s,i,o,a,l,c,h,u;let d,p;if("message"in e)d=e.message,p=e.signature;else{const{chain:h,wallet:u,statement:m,options:g}=e;let f;if(Ot())if("object"==typeof u)f=u;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)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.");f=e.ethereum}else{if("object"!=typeof u||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");f=u}const b=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href),w=await f.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!w||0===w.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const y=lr(w[0]);let v=null===(r=null==g?void 0:g.signInWithEthereum)||void 0===r?void 0:r.chainId;if(!v){const e=await f.request({method:"eth_chainId"});v=parseInt(e,16)}d=function(e){var t;const{chainId:r,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:h,uri:u,version:d}=e;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)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(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const p=`${h?`${h}://${n}`:n} wants you to sign in with your Ethereum account:\n${lr(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let m=`URI: ${u}\nVersion: ${d}\nChain ID: ${r}${o?`\nNonce: ${o}`:""}\nIssued At: ${i.toISOString()}`;if(s&&(m+=`\nExpiration Time: ${s.toISOString()}`),a&&(m+=`\nNot Before: ${a.toISOString()}`),l&&(m+=`\nRequest ID: ${l}`),c){let e="\nResources:";for(const t of c){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}m+=e}return`${p}\n${m}`}({domain:b.host,address:y,statement:m,uri:b.href,version:"1",chainId:v,nonce:null===(n=null==g?void 0:g.signInWithEthereum)||void 0===n?void 0:n.nonce,issuedAt:null!==(i=null===(s=null==g?void 0:g.signInWithEthereum)||void 0===s?void 0:s.issuedAt)&&void 0!==i?i:new Date,expirationTime:null===(o=null==g?void 0:g.signInWithEthereum)||void 0===o?void 0:o.expirationTime,notBefore:null===(a=null==g?void 0:g.signInWithEthereum)||void 0===a?void 0:a.notBefore,requestId:null===(l=null==g?void 0:g.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(c=null==g?void 0:g.signInWithEthereum)||void 0===c?void 0:c.resources}),p=await f.request({method:"personal_sign",params:[cr(d),y]})}try{const{data:t,error:r}=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:p},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(u=e.options)||void 0===u?void 0:u.captchaToken}}:null),xform:Vt});if(r)throw r;if(!t||!t.session||!t.user){const e=new ct;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,n,s,i,o,a,l,c,h,u,d;let p,m;if("message"in e)p=e.message,m=e.signature;else{const{chain:u,wallet:d,statement:g,options:f}=e;let b;if(Ot())if("object"==typeof d)b=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))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.");b=e.solana}else{if("object"!=typeof d||!(null==f?void 0:f.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=d}const w=new URL(null!==(t=null==f?void 0:f.url)&&void 0!==t?t:window.location.href);if("signIn"in b&&b.signIn){const e=await b.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==f?void 0:f.signInWithSolana),{version:"1",domain:w.host,uri:w.href}),g?{statement:g}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");p="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),m=t.signature}else{if(!("signMessage"in b&&"function"==typeof b.signMessage&&"publicKey"in b&&"object"==typeof b&&b.publicKey&&"toBase58"in b.publicKey&&"function"==typeof b.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${w.host} wants you to sign in with your Solana account:`,b.publicKey.toBase58(),...g?["",g,""]:[""],"Version: 1",`URI: ${w.href}`,`Issued At: ${null!==(n=null===(r=null==f?void 0:f.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==n?n:(new Date).toISOString()}`,...(null===(s=null==f?void 0:f.signInWithSolana)||void 0===s?void 0:s.notBefore)?[`Not Before: ${f.signInWithSolana.notBefore}`]:[],...(null===(i=null==f?void 0:f.signInWithSolana)||void 0===i?void 0:i.expirationTime)?[`Expiration Time: ${f.signInWithSolana.expirationTime}`]:[],...(null===(o=null==f?void 0:f.signInWithSolana)||void 0===o?void 0:o.chainId)?[`Chain ID: ${f.signInWithSolana.chainId}`]:[],...(null===(a=null==f?void 0:f.signInWithSolana)||void 0===a?void 0:a.nonce)?[`Nonce: ${f.signInWithSolana.nonce}`]:[],...(null===(l=null==f?void 0:f.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${f.signInWithSolana.requestId}`]:[],...(null===(h=null===(c=null==f?void 0:f.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===h?void 0:h.length)?["Resources",...f.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await b.signMessage((new TextEncoder).encode(p),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=e}}try{const{data:t,error:r}=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:Tt(m)},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:Vt});if(r)throw r;if(!t||!t.session||!t.user){const e=new ct;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){const t=await It(this.storage,`${this.storageKey}-code-verifier`),[r,n]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new pt;const{data:t,error:s}=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:Vt});if(await jt(this.storage,`${this.storageKey}-code-verifier`),s)throw s;if(!t||!t.session||!t.user){const e=new ct;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=n?n:null}),error:s})}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{const{options:t,provider:r,token:n,access_token:s,nonce:i}=e,o=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:Vt}),{data:a,error:l}=o;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a||!a.session||!a.user){const e=new ct;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:l})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,n,s,i;try{if("email"in e){const{email:n,options:s}=e;let i=null,o=null;"pkce"===this.flowType&&([i,o]=await Bt(this.storage,this.storageKey));const{error:a}=await Gt(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:n,data:null!==(t=null==s?void 0:s.data)&&void 0!==t?t:{},create_user:null===(r=null==s?void 0:s.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},code_challenge:i,code_challenge_method:o},redirectTo:null==s?void 0:s.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){const{phone:t,options:r}=e,{data:o,error:a}=await Gt(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(n=null==r?void 0:r.data)&&void 0!==n?n:{},create_user:null===(s=null==r?void 0:r.shouldCreateUser)||void 0===s||s,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(i=null==r?void 0:r.channel)&&void 0!==i?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a})}throw new ht("You must provide either an email or phone number.")}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let n,s;"options"in e&&(n=null===(t=e.options)||void 0===t?void 0:t.redirectTo,s=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:i,error:o}=await Gt(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:Vt});if(o)throw o;if(!i){throw new Error("An error occurred on token verification.")}const a=i.session,l=i.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,n,s,i;try{let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Bt(this.storage,this.storageKey));const l=await Gt(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(n=null==e?void 0:e.options)||void 0===n?void 0:n.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:a}),headers:this.headers,xform:Qt});return(null===(s=l.data)||void 0===s?void 0:s.url)&&Ot()&&!(null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new lt;const{error:n}=await Gt(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:n,options:s}=e,{error:i}=await Gt(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},redirectTo:null==s?void 0:s.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){const{phone:r,type:n,options:s}=e,{data:i,error:o}=await Gt(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:o})}throw new ht("You must provide either an email or phone number and a type")}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){await this.initializePromise;return await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await It(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=!!e.expires_at&&1e3*e.expires_at-Date.now()<Qe;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const t=await It(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=Ht()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,r,n)=>{if("__isInsecureUserWarningProxy"===r)return!0;if("symbol"==typeof r){const t=r.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,r,n)}return t.value||"string"!=typeof r||(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."),t.value=!0),Reflect.get(e,r,n)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await Gt(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Yt}):await this._useSession(async e=>{var t,r,n;const{data:s,error:i}=e;if(i)throw i;return(null===(t=s.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await Gt(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(n=null===(r=s.session)||void 0===r?void 0:r.access_token)&&void 0!==n?n:void 0,xform:Yt}):{data:{user:null},error:new lt}})}catch(e){if(st(e))return function(e){return st(e)&&"AuthSessionMissingError"===e.name}(e)&&(await this._removeSession(),await jt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:n,error:s}=r;if(s)throw s;if(!n.session)throw new lt;const i=n.session;let o=null,a=null;"pkce"===this.flowType&&null!=e.email&&([o,a]=await Bt(this.storage,this.storageKey));const{data:l,error:c}=await Gt(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:i.access_token,xform:Yt});if(c)throw c;return i.user=l.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new lt;const t=Date.now()/1e3;let r=t,n=!0,s=null;const{payload:i}=Nt(e.access_token);if(i.exp&&(r=i.exp,n=r<=t),n){const{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};s=t}else{const{data:n,error:i}=await this._getUser(e.access_token);if(i)throw i;s={access_token:e.access_token,refresh_token:e.refresh_token,user:n.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(e){if(st(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:n,error:s}=t;if(s)throw s;e=null!==(r=n.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new lt;const{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!Ot())throw new ut("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ut(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new dt("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new ut("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new dt("No code detected.");const{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;const n=new URL(window.location.href);return n.searchParams.delete("code"),window.history.replaceState(window.history.state,"",n.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:o,expires_at:a,token_type:l}=e;if(!(s&&o&&i&&l))throw new ut("No session defined in URL");const c=Math.round(Date.now()/1e3),h=parseInt(o);let u=c+h;a&&(u=parseInt(a));const d=u-c;1e3*d<=Ye&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${h}s`);const p=u-h;c-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,c):c-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,u,c);const{data:m,error:g}=await this._getUser(s);if(g)throw g;const f={provider_token:r,provider_refresh_token:n,access_token:s,expires_in:h,expires_at:u,refresh_token:i,token_type:l,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:f,redirectType:e.type},error:null})}catch(e){if(st(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await It(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:n,error:s}=t;if(s)return this._returnResult({error:s});const i=null===(r=n.session)||void 0===r?void 0:r.access_token;if(i){const{error:t}=await this.admin.signOut(i,e);if(t&&(!function(e){return st(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await jt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Symbol("auth-callback"),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,n;try{const{data:{session:n},error:s}=t;if(s)throw s;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(t){await(null===(n=this.stateChangeEmitters.get(e))||void 0===n?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,n=null;"pkce"===this.flowType&&([r,n]=await Bt(this.storage,this.storageKey,!0));try{return await Gt(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:n}=await this._useSession(async t=>{var r,n,s,i,o;const{data:a,error:l}=t;if(l)throw l;const c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(r=e.options)||void 0===r?void 0:r.redirectTo,scopes:null===(n=e.options)||void 0===n?void 0:n.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:!0});return await Gt(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(o=null===(i=a.session)||void 0===i?void 0:i.access_token)&&void 0!==o?o:void 0})});if(n)throw n;return Ot()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(st(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:n,data:{session:s}}=t;if(n)throw n;const{options:i,provider:o,token:a,access_token:l,nonce:c}=e,h=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(r=null==s?void 0:s.access_token)&&void 0!==r?r:void 0,body:{provider:o,id_token:a,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:Vt}),{data:u,error:d}=h;return d?this._returnResult({data:{user:null,session:null},error:d}):u&&u.session&&u.user?(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:d})):this._returnResult({data:{user:null,session:null},error:new ct})}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,n;const{data:s,error:i}=t;if(i)throw i;return await Gt(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(n=null===(r=s.session)||void 0===r?void 0:r.access_token)&&void 0!==n?n:void 0})})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const s=Date.now();return await(r=async r=>(r>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await Gt(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Vt})),n=(e,t)=>{const r=200*Math.pow(2,e);return t&>(t)&&Date.now()+r-s<Ye},new Promise((e,t)=>{(async()=>{for(let s=0;s<1/0;s++)try{const t=await r(s);if(!n(s,null,t))return void e(t)}catch(e){if(!n(s,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),st(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}var r,n}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),Ot()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const n=await It(this.storage,this.storageKey);if(n&&this.userStorage){let t=await It(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:n.user},await $t(this.userStorage,this.storageKey+"-user",t)),n.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:Ht()}else if(n&&!n.user&&!n.user){const e=await It(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(n.user=e.user,await jt(this.storage,this.storageKey+"-user"),await $t(this.storage,this.storageKey,n)):n.user=Ht()}if(this._debug(r,"session from storage",n),!this._isValidSession(n))return this._debug(r,"session is not valid"),void(null!==n&&await this._removeSession());const s=1e3*(null!==(t=n.expires_at)&&void 0!==t?t:1/0)-Date.now()<Qe;if(this._debug(r,`session has${s?"":" not"} expired with margin of 90000s`),s){if(this.autoRefreshToken&&n.refresh_token){const{error:e}=await this._callRefreshToken(n.refresh_token);e&&(console.error(e),gt(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(n.user&&!0===n.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(n.access_token);!t&&(null==e?void 0:e.user)?(n.user=e.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(e){return this._debug(r,"error",e),void console.error(e)}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new lt;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Pt;const{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new lt;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const n={data:t.session,error:null};return this.refreshingDeferred.resolve(n),n}catch(e){if(this._debug(n,"error",e),st(e)){const r={data:null,error:e};return gt(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,r=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const n=[],s=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){n.push(e)}});if(await Promise.all(s),n.length>0){for(let e=0;e<n.length;e+=1)console.error(n[e]);throw n[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await jt(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await $t(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const n=Ft(e);await $t(this.storage,this.storageKey,n)}else{const e=Ft(t);await $t(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await jt(this.storage,this.storageKey),await jt(this.storage,this.storageKey+"-code-verifier"),await jt(this.storage,this.storageKey+"-user"),this.userStorage&&await jt(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ot()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Ye);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);const t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const n=Math.floor((1e3*r.expires_at-e)/Ye);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),n<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof ir))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ot()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const n=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&n.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&n.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){const[e,t]=await Bt(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});n.push(r.toString())}if(null==r?void 0:r.queryParams){const e=new URLSearchParams(r.queryParams);n.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&n.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:n,error:s}=t;return s?this._returnResult({data:null,error:s}):await Gt(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token})})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,n;const{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:a,error:l}=await Gt(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===a.type&&(null===(n=null==a?void 0:a.totp)||void 0===n?void 0:n.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:n,error:s}=t;if(s)return this._returnResult({data:null,error:s});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?br(e.webauthn.credential_response):wr(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:a}=await Gt(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});return a?this._returnResult({data:null,error:a}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:a}))})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:n,error:s}=t;if(s)return this._returnResult({data:null,error:s});const i=await Gt(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});if(i.error)return i;const{data:o}=i;if("webauthn"!==o.type)return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:gr(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:fr(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){const{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;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const n={all:[],phone:[],totp:[],webauthn:[]};for(const r of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])n.all.push(r),"verified"===r.status&&n[r.factor_type].push(r);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:n}=await this.getSession();if(n)return this._returnResult({data:null,error:n});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:s}=Nt(r.access_token);let i=null;s.aal&&(i=s.aal);let o=i;(null!==(t=null===(e=r.user.factors)||void 0===e?void 0:e.filter(e=>"verified"===e.status))&&void 0!==t?t:[]).length>0&&(o="aal2");return{data:{currentLevel:i,nextLevel:o,currentAuthenticationMethods:s.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;return n?this._returnResult({data:null,error:n}):r?await Gt(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new lt})})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new lt});const i=await Gt(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&Ot()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new lt});const i=await Gt(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&Ot()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await Gt(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new lt})})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;return n?this._returnResult({data:null,error:n}):r?(await Gt(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 lt})})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;const n=Date.now();if(r=this.jwks.keys.find(t=>t.kid===e),r&&this.jwks_cached_at+6e5>n)return r;const{data:s,error:i}=await Gt(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return s.keys&&0!==s.keys.length?(this.jwks=s,this.jwks_cached_at=n,r=s.keys.find(t=>t.kid===e),r||null):null}async getClaims(e,t={}){try{let r=e;if(!r){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});r=e.session.access_token}const{header:n,payload:s,signature:i,raw:{header:o,payload:a}}=Nt(r);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(s.exp);const l=n.alg&&!n.alg.startsWith("HS")&&n.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(n.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!l){const{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:s,header:n,signature:i},error:null}}const c=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(n.alg),h=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!await crypto.subtle.verify(c,h,i,Et(`${o}.${a}`)))throw new bt("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}}Or.nextInstanceID={};const Rr=Or;let qr="";qr="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const Ar={headers:{"X-Client-Info":`supabase-js-${qr}/2.90.1`}},$r={schema:"public"},Ir={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},jr={};function Pr(e){return(Pr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function Nr(e){var t=function(e,t){if("object"!=Pr(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=Pr(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==Pr(t)?t:t+""}function Ur(e,t,r){return(t=Nr(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Lr(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function Br(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Lr(Object(r),!0).forEach(function(t){Ur(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Lr(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const Mr=(e,t,r)=>{const n=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),s=Headers;return async(r,i)=>{var o;const a=null!==(o=await t())&&void 0!==o?o:e;let l=new s(null==i?void 0:i.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${a}`),n(r,Br(Br({},i),{},{headers:l}))}};var zr=class extends Rr{constructor(e){super(e)}},Dr=class{constructor(e,t,r){var n,s;this.supabaseUrl=e,this.supabaseKey=t;const i=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((r=t).endsWith("/")?r:r+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var r}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,a=function(e,t){var r,n;const{db:s,auth:i,realtime:o,global:a}=e,{db:l,auth:c,realtime:h,global:u}=t,d={db:Br(Br({},l),s),auth:Br(Br({},c),i),realtime:Br(Br({},h),o),storage:{},global:Br(Br(Br({},u),a),{},{headers:Br(Br({},null!==(r=null==u?void 0:u.headers)&&void 0!==r?r:{}),null!==(n=null==a?void 0:a.headers)&&void 0!==n?n:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:$r,realtime:jr,auth:Br(Br({},Ir),{},{storageKey:o}),global:Ar});var l;(this.storageKey=null!==(n=a.auth.storageKey)&&void 0!==n?n:"",this.headers=null!==(s=a.global.headers)&&void 0!==s?s:{},a.accessToken)?(this.accessToken=a.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(l=a.auth)&&void 0!==l?l:{},this.headers,a.global.fetch);this.fetch=Mr(t,this._getAccessToken.bind(this),a.global.fetch),this.realtime=this._initRealtimeClient(Br({headers:this.headers,accessToken:this._getAccessToken.bind(this)},a.realtime)),this.accessToken&&this.accessToken().then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new g(new URL("rest/v1",i).href,{headers:this.headers,schema:a.db.schema,fetch:this.fetch}),this.storage=new Ve(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),a.accessToken||this._listenForAuthEvents()}get functions(){return new l(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t,r=this;if(r.accessToken)return await r.accessToken();const{data:n}=await r.auth.getSession();return null!==(e=null===(t=n.session)||void 0===t?void 0:t.access_token)&&void 0!==e?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:s,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},h,u){const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new zr({url:this.authUrl.href,headers:Br(Br({},d),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:s,flowType:o,lock:a,debug:l,throwOnError:c,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new X(this.realtimeUrl.href,Br(Br({},e),{},{params:Br(Br({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}};(function(){if("undefined"!=typeof window)return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(null==t)return!1;const r=t.match(/^v(\d+)\./);return!!r&&parseInt(r[1],10)<=18})()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Hr={mode:"widget",position:"bottom-right",defaultOpen:!1,theme:"dark",features:["prompts","timeline","deployments","elements","captures"],captureConsole:!0,captureNetwork:!0,hotkey:"ctrl+shift+o",apiUrl:"https://orquesta.live"};class Fr{constructor(){this.listeners=new Set,this.state=this.getInitialState()}getInitialState(){return{isConnected:!1,isConnecting:!1,connectionError:null,projectId:null,projectName:null,agentOnline:!1,isAuthenticated:!1,isAuthenticating:!1,user:null,authError:null,requireAuth:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,rightClickEnabled:!0,currentPrompt:null,promptHistory:[],isSubmitting:!1,promptQueue:[],outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1,includeHistory:!1,includeContext:!1}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}setConnected(e,t,r){this.setState({isConnected:!0,isConnecting:!1,connectionError:null,projectId:e,projectName:t,agentOnline:r})}setConnectionError(e){this.setState({isConnected:!1,isConnecting:!1,connectionError:e})}setOpen(e){this.setState({isOpen:e})}toggle(){this.setState({isOpen:!this.state.isOpen})}setActiveTab(e){this.setState({activeTab:e})}setCurrentPrompt(e){this.setState({currentPrompt:e}),e&&!this.state.promptHistory.find(t=>t.id===e.id)&&this.setState({promptHistory:[e,...this.state.promptHistory].slice(0,50)})}updatePrompt(e,t){this.state.currentPrompt?.id===e&&this.setState({currentPrompt:{...this.state.currentPrompt,...t}}),this.setState({promptHistory:this.state.promptHistory.map(r=>r.id===e?{...r,...t}:r)})}addOutputLine(e){const t={...e,id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`};this.setState({outputLines:[...this.state.outputLines,t]})}clearOutput(){this.setState({outputLines:[]})}storePromptOutput(e){this.state.outputLines.length>0&&this.setState({promptOutputs:{...this.state.promptOutputs,[e]:[...this.state.outputLines]}})}addToQueue(e){this.setState({promptQueue:[...this.state.promptQueue,e]})}getNextFromQueue(){if(0===this.state.promptQueue.length)return null;const[e,...t]=this.state.promptQueue;return this.setState({promptQueue:t}),e}clearQueue(){this.setState({promptQueue:[]})}getQueueLength(){return this.state.promptQueue.length}setSelectedElement(e){this.setState({selectedElement:e,isSelectingElement:!1})}startElementSelection(){this.setState({isSelectingElement:!0})}cancelElementSelection(){this.setState({isSelectingElement:!1,selectedElement:null})}setOverlayMode(e){this.setState({overlayMode:e}),"off"===e&&this.setState({highlightedPromptId:null})}setHighlightedPromptId(e){this.setState({highlightedPromptId:e})}setElementMarkers(e){this.setState({elementMarkers:e})}setCommentsForPrompt(e,t){this.setState({comments:{...this.state.comments,[e]:t}})}addComment(e,t){const r=this.state.comments[e]||[];this.setState({comments:{...this.state.comments,[e]:[...r,t]}}),this.setState({promptHistory:this.state.promptHistory.map(t=>t.id===e?{...t,comment_count:(t.comment_count||0)+1}:t)})}setExpandedPromptId(e){this.setState({expandedPromptId:e})}setLoadingComments(e){this.setState({isLoadingComments:e})}addConsoleLogs(e){this.setState({consoleLogs:[...this.state.consoleLogs,...e].slice(-100)})}addNetworkLogs(e){this.setState({networkLogs:[...this.state.networkLogs,...e].slice(-100)})}toggleIncludeConsole(){this.setState({includeConsole:!this.state.includeConsole})}toggleIncludeNetwork(){this.setState({includeNetwork:!this.state.includeNetwork})}toggleIncludeHistory(){this.setState({includeHistory:!this.state.includeHistory})}toggleIncludeContext(){this.setState({includeContext:!this.state.includeContext})}setAuth(e,t){this.setState({user:e,isAuthenticated:t,isAuthenticating:!1,authError:null})}setAuthenticating(e){this.setState({isAuthenticating:e})}setAuthError(e){this.setState({authError:e,isAuthenticating:!1})}setRequireAuth(e){this.setState({requireAuth:e})}reset(){this.state=this.getInitialState(),this.notify()}}class Wr{constructor(){this.buffer=[],this.maxSize=100,this.originalConsole=null,this.errorHandler=null,this.rejectionHandler=null,this.listeners=new Set}start(){if(this.originalConsole)return;this.originalConsole={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};const e=e=>(...t)=>{const r=this.createEntry(e,t);this.addEntry(r),this.originalConsole?.[e](...t)};console.log=e("log"),console.info=e("info"),console.warn=e("warn"),console.error=e("error"),this.errorHandler=e=>{const t=this.createEntry("error",[e.message],e.error?.stack);this.addEntry(t)},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{const t=e.reason instanceof Error?e.reason.message:String(e.reason),r=e.reason instanceof Error?e.reason.stack:void 0,n=this.createEntry("error",[`Unhandled Promise Rejection: ${t}`],r);this.addEntry(n)},window.addEventListener("unhandledrejection",this.rejectionHandler)}stop(){this.originalConsole&&(console.log=this.originalConsole.log,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error,this.originalConsole=null),this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null)}formatArg(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if(null===e)return"null";if(void 0===e)return"undefined";if("object"==typeof e)try{const t=JSON.stringify(e,null,2);if("{}"===t||"[]"===t){const t=Object.prototype.toString.call(e);if("[object Object]"!==t&&"[object Array]"!==t)return t}return t}catch{return Object.prototype.toString.call(e)}return String(e)}createEntry(e,t,r){const n=t.map(e=>this.formatArg(e)).join(" ");return{timestamp:Date.now(),level:e,message:n||"(empty)",args:t,stack:r}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>"error"===e.level||"warn"===e.level)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getRecent(20);return 0===t.length?"":t.map(e=>`${`[${new Date(e.timestamp).toISOString()}] [${e.level.toUpperCase()}]`} ${e.message}${e.stack?`\n${e.stack}`:""}`).join("\n")}}class Kr{constructor(){this.buffer=[],this.maxSize=100,this.originalFetch=null,this.originalXHROpen=null,this.originalXHRSend=null,this.listeners=new Set}start(){this.originalFetch||(this.patchFetch(),this.patchXHR())}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXHROpen&&this.originalXHRSend&&(XMLHttpRequest.prototype.open=this.originalXHROpen,XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHROpen=null,this.originalXHRSend=null)}patchFetch(){this.originalFetch=window.fetch.bind(window),window.fetch=async(e,t)=>{const r="string"==typeof e?e:e instanceof URL?e.href:e.url,n=t?.method||"GET",s=Date.now(),i={timestamp:s,method:n,url:r,requestBody:t?.body};try{const r=await this.originalFetch(e,t);if(i.status=r.status,i.duration=Date.now()-s,!r.ok)try{const e=r.clone();i.responseBody=await e.text()}catch{}return this.addEntry(i),r}catch(e){throw i.duration=Date.now()-s,i.error=e instanceof Error?e.message:String(e),this.addEntry(i),e}}}patchXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;const e=this,t=new WeakMap;XMLHttpRequest.prototype.open=function(r,n,...s){return t.set(this,{method:r,url:"string"==typeof n?n:n.href,startTime:0}),e.originalXHROpen.apply(this,[r,n,...s])},XMLHttpRequest.prototype.send=function(r){const n=t.get(this);return n&&(n.startTime=Date.now(),this.addEventListener("loadend",()=>{const t={timestamp:n.startTime,method:n.method,url:n.url,status:this.status,duration:Date.now()-n.startTime};if(this.status>=400||0===this.status){t.error=this.statusText||"Request failed";try{t.responseBody=this.responseText}catch{}}e.addEntry(t)})),e.originalXHRSend.call(this,r)}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>e.status&&e.status>=400||e.error)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getErrors();return 0===t.length?"":t.map(e=>{const t=new Date(e.timestamp).toISOString(),r=e.status?`[${e.status}]`:"[FAILED]";return`[${t}] ${e.method} ${e.url} ${r}${e.error?` - ${e.error}`:""}`}).join("\n")}}class Jr{constructor(){this.overlay=null,this.highlight=null,this.selectedHighlight=null,this.selectedElement=null,this.isActive=!1,this.onSelect=null,this.onCancel=null,this.globalRightClickHandler=null,this.globalRightClickCallback=null,this.globalRightClickWithPositionCallback=null,this.selectedElementScrollHandler=null,this.handleMouseMove=e=>{if(!this.isActive||!this.highlight)return;const t=document.elementFromPoint(e.clientX,e.clientY);if(!t||t.id?.startsWith("orquesta-"))return;this.selectedElement=t;const r=t.getBoundingClientRect();this.highlight.style.display="block",this.highlight.style.top=`${r.top}px`,this.highlight.style.left=`${r.left}px`,this.highlight.style.width=`${r.width}px`,this.highlight.style.height=`${r.height}px`;const n=this.highlight.querySelector("#orquesta-element-label");if(n){const e=t.tagName.toLowerCase(),r=t.id?`#${t.id}`:"",s=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";n.textContent=`<${e}${r}${s}>`}},this.handleClick=e=>{if(!this.isActive)return;const t=e.target;if(!t.id?.startsWith("orquesta-")&&(e.preventDefault(),e.stopPropagation(),this.selectedElement)){const e=this.getElementContext(this.selectedElement);this.deactivate(),this.onSelect?.(e)}},this.handleKeyDown=e=>{"Escape"===e.key&&this.isActive&&(this.deactivate(),this.onCancel?.())},this.promptHighlightScrollHandler=null}setupGlobalRightClick(e){return this.globalRightClickCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const r=this.getElementContext(t);this.globalRightClickCallback?.(r)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickCallback=null)}}setupGlobalRightClickWithPosition(e){return this.globalRightClickWithPositionCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const r=this.getElementContext(t),n={x:e.clientX,y:e.clientY};this.globalRightClickWithPositionCallback?.(r,n)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickWithPositionCallback=null)}}highlightSelectedElement(e){try{const t=this.safeQuerySelector(e);if(!t)return null;this.removeSelectedHighlight(),this.selectedHighlight=document.createElement("div"),this.selectedHighlight.id="orquesta-selected-element-highlight",this.selectedHighlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #3b82f6;\n background: rgba(59, 130, 246, 0.15);\n z-index: 2147483640;\n transition: all 0.15s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25), 0 0 20px rgba(59, 130, 246, 0.3);\n ",document.body.appendChild(this.selectedHighlight);const r=document.createElement("div");r.id="orquesta-selected-element-label",r.style.cssText='\n position: absolute;\n top: -28px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 8px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ';const n=t.tagName.toLowerCase(),s=t.id?`#${t.id}`:"",i=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";r.textContent=`Selected: <${n}${s}${i}>`,this.selectedHighlight.appendChild(r);const o=()=>{if(!this.selectedHighlight)return;const e=t.getBoundingClientRect();this.selectedHighlight.style.top=e.top-3+"px",this.selectedHighlight.style.left=e.left-3+"px",this.selectedHighlight.style.width=`${e.width+6}px`,this.selectedHighlight.style.height=`${e.height+6}px`};return o(),this.selectedElementScrollHandler=o,window.addEventListener("scroll",this.selectedElementScrollHandler,!0),window.addEventListener("resize",this.selectedElementScrollHandler),t}catch{return null}}removeSelectedHighlight(){this.selectedHighlight&&(this.selectedHighlight.remove(),this.selectedHighlight=null),this.selectedElementScrollHandler&&(window.removeEventListener("scroll",this.selectedElementScrollHandler,!0),window.removeEventListener("resize",this.selectedElementScrollHandler),this.selectedElementScrollHandler=null)}activate(e,t){this.isActive||(this.isActive=!0,this.onSelect=e,this.onCancel=t||null,this.createOverlay(),this.addListeners(),document.body.style.cursor="crosshair")}deactivate(){this.isActive&&(this.isActive=!1,this.removeListeners(),this.removeOverlay(),this.selectedElement=null,document.body.style.cursor="")}isSelecting(){return this.isActive}createOverlay(){this.overlay=document.createElement("div"),this.overlay.id="orquesta-element-selector-overlay",this.overlay.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2147483646;\n pointer-events: none;\n ",document.body.appendChild(this.overlay),this.highlight=document.createElement("div"),this.highlight.id="orquesta-element-highlight",this.highlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 2px solid #3b82f6;\n background: rgba(59, 130, 246, 0.1);\n z-index: 2147483646;\n transition: all 0.1s ease;\n display: none;\n ",document.body.appendChild(this.highlight);const e=document.createElement("div");e.id="orquesta-element-label",e.style.cssText="\n position: absolute;\n bottom: -24px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: monospace;\n padding: 2px 6px;\n border-radius: 2px;\n white-space: nowrap;\n ",this.highlight.appendChild(e)}removeOverlay(){this.overlay?.remove(),this.highlight?.remove(),this.overlay=null,this.highlight=null}addListeners(){document.addEventListener("mousemove",this.handleMouseMove,!0),document.addEventListener("click",this.handleClick,!0),document.addEventListener("keydown",this.handleKeyDown,!0)}removeListeners(){document.removeEventListener("mousemove",this.handleMouseMove,!0),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("keydown",this.handleKeyDown,!0)}highlightElement(e){try{const t=this.safeQuerySelector(e);if(!t)return null;this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null);let r=document.getElementById("orquesta-prompt-highlight");r||(r=document.createElement("div"),r.id="orquesta-prompt-highlight",r.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #8b5cf6;\n background: rgba(139, 92, 246, 0.15);\n z-index: 2147483640;\n transition: top 0.1s ease, left 0.1s ease, width 0.1s ease, height 0.1s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2), 0 0 20px rgba(139, 92, 246, 0.3);\n ",document.body.appendChild(r));let n=r.querySelector("#orquesta-prompt-highlight-label");n||(n=document.createElement("div"),n.id="orquesta-prompt-highlight-label",n.style.cssText='\n position: absolute;\n top: -30px;\n left: 0;\n background: #8b5cf6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 10px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ',r.appendChild(n));const s=t.tagName.toLowerCase(),i=t.id?`#${t.id}`:"",o=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";n.textContent=`Highlighted: <${s}${i}${o}>`;const a=()=>{const e=t.getBoundingClientRect();r.style.display="block",r.style.top=e.top-3+"px",r.style.left=e.left-3+"px",r.style.width=`${e.width+6}px`,r.style.height=`${e.height+6}px`};a(),this.promptHighlightScrollHandler=a,window.addEventListener("scroll",this.promptHighlightScrollHandler,!0),window.addEventListener("resize",this.promptHighlightScrollHandler);const l=t.getBoundingClientRect();return(l.top<0||l.bottom>window.innerHeight)&&t.scrollIntoView({behavior:"smooth",block:"center"}),t}catch{return null}}removeHighlight(){const e=document.getElementById("orquesta-prompt-highlight");e&&(e.style.display="none"),this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null)}safeQuerySelector(e){try{return document.querySelector(e)}catch{return null}}findElement(e,t){try{let r=this.safeQuerySelector(e);if(r)return r;if(t&&(r=document.getElementById(t),r))return r;const n=e.match(/^([a-z]+)\.([a-z0-9_-]+)/i);if(n){const[,e,t]=n;if(r=this.safeQuerySelector(`${e}.${t}`),r)return r}return null}catch{return null}}getElementContext(e){const t=e.getBoundingClientRect(),r={};for(const t of e.attributes)t.name.startsWith("data-")||"class"===t.name||"id"===t.name||(r[t.name]=t.value);return{selector:this.generateSelector(e),tag:e.tagName.toLowerCase(),id:e.id||void 0,className:"string"==typeof e.className?e.className:void 0,textContent:e.textContent?.trim().slice(0,200)||void 0,boundingRect:t,attributes:Object.keys(r).length>0?r:void 0}}isValidCssClass(e){return!/[@:/\[\]()!#]/.test(e)&&!!/^[a-zA-Z_-]/.test(e)}generateSelector(e){if(e.id&&this.isValidCssClass(e.id))return`#${e.id}`;const t=[];let r=e;for(;r&&r!==document.body;){let e=r.tagName.toLowerCase();if(r.id&&this.isValidCssClass(r.id)){e=`#${r.id}`,t.unshift(e);break}if(r.className&&"string"==typeof r.className){const t=r.className.trim().split(/\s+/).filter(e=>this.isValidCssClass(e)).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}const n=r.parentElement;if(n){const t=Array.from(n.children).filter(e=>e.tagName===r.tagName);if(t.length>1){e+=`:nth-child(${t.indexOf(r)+1})`}}t.unshift(e),r=r.parentElement}return t.join(" > ")}}class Gr{constructor(e,t){this.listeners=new Set,this.popupWindow=null,this.messageHandler=null,this.broadcastChannel=null,this.pollInterval=null,this.token=e,this.apiUrl=t,this.state=this.getInitialState()}getInitialState(){return{isAuthenticated:!1,isAuthenticating:!1,user:null,sessionToken:null,expiresAt:null,authError:null}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}getStorageKey(){return`orquesta_embed_session_${this.token.slice(-8)}`}saveSession(e){try{localStorage.setItem(this.getStorageKey(),JSON.stringify(e))}catch{}}loadSession(){try{const e=localStorage.getItem(this.getStorageKey());if(!e)return null;const t=JSON.parse(e);return t.expiresAt&&new Date(t.expiresAt)<new Date?(this.clearSession(),null):t}catch{return null}}clearSession(){try{localStorage.removeItem(this.getStorageKey())}catch{}}async checkSession(){const e=this.loadSession();if(!e)return!1;try{const t=await fetch(`${this.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:e.sessionToken})});if(!t.ok)return this.clearSession(),!1;const r=await t.json();return r.valid?(this.setState({isAuthenticated:!0,user:r.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null}),!0):(this.clearSession(),!1)}catch{return this.setState({isAuthenticated:!0,user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null}),!0}}login(){return new Promise((e,t)=>{this.setState({isAuthenticating:!0,authError:null});const r=Math.random().toString(36).slice(2),n=`eas_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,s=new URL(`${this.apiUrl}/embed/auth`);s.searchParams.set("token",this.token),s.searchParams.set("origin",window.location.origin),s.searchParams.set("state",r),s.searchParams.set("authSession",n);const i=window.screenX+(window.innerWidth-500)/2,o=window.screenY+(window.innerHeight-600)/2;if(this.popupWindow=window.open(s.toString(),"orquesta_auth",`width=500,height=600,left=${i},top=${o},popup=yes`),!this.popupWindow)return this.setState({isAuthenticating:!1,authError:"Popup blocked"}),void t(new Error("Popup blocked. Please allow popups for this site."));this.messageHandler=r=>{if(r.origin!==new URL(this.apiUrl).origin)return;const{type:n,payload:s}=r.data||{};"orquesta_auth_success"===n?(this.handleAuthSuccess(s),e(s),this.cleanup()):"orquesta_auth_error"===n?(this.handleAuthError(s),t(new Error(s.message||"Authentication failed")),this.cleanup()):"orquesta_auth_closed"===n&&(this.setState({isAuthenticating:!1}),t(new Error("Authentication cancelled")),this.cleanup())},window.addEventListener("message",this.messageHandler);const a=this.apiUrl.replace("://orquesta.live","://ws.orquesta.live").replace("://localhost:3113","://localhost:3200");this.pollInterval=setInterval(async()=>{try{const r=await fetch(`${a}/auth/result/${n}`);if(!r.ok)return;const s=await r.json();if(s.pending)return;const{type:i,payload:o}=s;"orquesta_auth_success"===i?(this.handleAuthSuccess(o),e(o),this.cleanup()):"orquesta_auth_error"===i&&(this.handleAuthError(o),t(new Error(o.message||"Authentication failed")),this.cleanup())}catch{}},1500);const l=setInterval(()=>{this.popupWindow?.closed&&(clearInterval(l),this.state.isAuthenticating&&(this.setState({isAuthenticating:!1}),t(new Error("Authentication cancelled")),this.cleanup()))},500)})}handleAuthSuccess(e){const t={user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt};this.saveSession(t),this.setState({isAuthenticated:!0,isAuthenticating:!1,user:t.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt,authError:null})}handleAuthError(e){this.setState({isAuthenticating:!1,authError:e.message})}cleanup(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.popupWindow&&!this.popupWindow.closed&&this.popupWindow.close(),this.popupWindow=null}async logout(){const e=this.loadSession();if(e?.sessionToken)try{await fetch(`${this.apiUrl}/api/embed/session`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:e.sessionToken})})}catch{}this.clearSession(),this.setState(this.getInitialState())}getUser(){return this.state.user}getSessionToken(){return this.state.sessionToken}destroy(){this.cleanup(),this.listeners.clear()}}const Vr=!1,Xr="prompts",Yr="dark";const Qr=new class{constructor(){this.projectId=null}setProjectId(e){this.projectId=e}getKey(e){const t=`orquesta_embed_${e}`;return this.projectId?`${t}_${this.projectId}`:t}get(e){try{const t=localStorage.getItem(this.getKey(e));return t?JSON.parse(t):null}catch{return null}}set(e,t){try{localStorage.setItem(this.getKey(e),JSON.stringify(t))}catch{}}remove(e){try{localStorage.removeItem(this.getKey(e))}catch{}}getState(){return{isOpen:this.get("isOpen")??Vr,position:this.get("position"),size:this.get("size"),activeTab:this.get("activeTab")??Xr,theme:this.get("theme")??Yr}}setState(e){Object.entries(e).forEach(([e,t])=>{void 0!==t&&this.set(e,t)})}clear(){["isOpen","position","size","activeTab","theme"].forEach(e=>this.remove(e))}};class Zr{constructor(e){this.supabase=null,this.channel=null,this.projectId=null,this.authManager=null,this.hotkeyHandler=null,this.config={...Hr,...e},this.state=new Fr,this.consoleCapture=new Wr,this.networkCapture=new Kr,this.elementSelector=new Jr,this.config.requireAuth&&(this.state.setRequireAuth(!0),this.authManager=new Gr(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(e=>{this.state.setState({isAuthenticated:e.isAuthenticated,isAuthenticating:e.isAuthenticating,user:e.user,authError:e.authError})}))}async connect(){if(!this.config.token)throw new Error("Embed token is required");this.state.setState({isConnecting:!0});try{const n=await fetch(`${this.config.apiUrl}/api/embed/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.token})});if(!n.ok){const e=await n.json();throw new Error(e.error||"Failed to validate token")}const s=await n.json();if(!s.valid)throw new Error("Invalid embed token");this.projectId=s.projectId,Qr.setProjectId(s.projectId);const i=s.requireAuth||this.config.requireAuth;i&&!this.authManager?(this.state.setRequireAuth(!0),this.authManager=new Gr(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(e=>{this.state.setState({isAuthenticated:e.isAuthenticated,isAuthenticating:e.isAuthenticating,user:e.user,authError:e.authError})}),await this.authManager.checkSession()):i&&this.state.setRequireAuth(!0),this.supabase=(e=s.supabaseUrl,t=s.supabaseAnonKey,new Dr(e,t,r)),this.channel=this.supabase.channel(s.channelName),this.channel.on("broadcast",{event:"output"},({payload:e})=>{this.handleOutput(e)}).on("broadcast",{event:"complete"},({payload:e})=>{this.handleComplete(e)}).on("broadcast",{event:"error"},({payload:e})=>{this.handleError(e)}).subscribe(e=>{if("SUBSCRIBED"===e){this.state.setConnected(s.projectId,s.project?.name||"Project",s.project?.agent_online||!1),this.config.captureConsole&&(this.consoleCapture.start(),this.consoleCapture.subscribe(e=>{this.state.addConsoleLogs([e])})),this.config.captureNetwork&&(this.networkCapture.start(),this.networkCapture.subscribe(e=>{this.state.addNetworkLogs([e])})),this.setupHotkey(),this.loadTimeline();const e=Qr.getState();this.state.setState({isOpen:this.config.defaultOpen??e.isOpen,activeTab:e.activeTab||"prompts"}),this.config.onReady?.()}else"CHANNEL_ERROR"!==e&&"TIMED_OUT"!==e||this.state.setConnectionError("Failed to connect to channel")})}catch(e){const t=e instanceof Error?e.message:"Connection failed";throw this.state.setConnectionError(t),this.config.onError?.(e instanceof Error?e:new Error(t)),e}var e,t,r}disconnect(){this.channel&&(this.supabase?.removeChannel(this.channel),this.channel=null),this.consoleCapture.stop(),this.networkCapture.stop(),this.elementSelector.deactivate(),this.removeHotkey(),this.authManager&&this.authManager.destroy(),this.state.reset(),this.supabase=null,this.projectId=null}setupHotkey(){if(!this.config.hotkey)return;const e=this.config.hotkey.toLowerCase().split("+"),t=e.pop(),r=new Set(e);this.hotkeyHandler=e=>{if(!e.key)return;const n=r.has("ctrl")===(e.ctrlKey||e.metaKey),s=r.has("shift")===e.shiftKey,i=r.has("alt")===e.altKey,o=e.key.toLowerCase()===t;n&&s&&i&&o&&(e.preventDefault(),this.toggle())},document.addEventListener("keydown",this.hotkeyHandler)}removeHotkey(){this.hotkeyHandler&&(document.removeEventListener("keydown",this.hotkeyHandler),this.hotkeyHandler=null)}handleOutput(e){if(!this.state.getState().currentPrompt)return;let t,r,n,s="stdout",i=e.data;"stderr"===e.type?s="stderr":e.data.includes("Tool:")||e.data.includes("tool_call")?s="tool":(e.data.includes("thinking")||e.data.includes("Thinking"))&&(s="thinking");try{const o=JSON.parse(e.data);if(o.type){switch(o.type){case"thinking":s="thinking",i=o.thinking?.content||e.data;break;case"tool_call":s="tool_call",r=o.tool_call?.name,i=`Using ${r||"tool"}`;break;case"tool_result":s="tool_result",r=o.tool_result?.name,n=o.tool_result?.success,i=n?o.tool_result?.output||"Success":o.tool_result?.error||"Failed";break;case"output":s="output",i=o.output?.content||e.data;break;case"error":s="error",i=o.error?.message||e.data;break;case"system":s="system",i=o.system?.message||o.system?.event||e.data;break;case"progress":s="progress";const t=void 0!==o.progress?.percentage?` (${o.progress.percentage}%)`:"";i=(o.progress?.message||"Processing")+t;break;default:i=o.content||o.message||e.data}t=o}}catch{}this.state.addOutputLine({timestamp:e.timestamp||Date.now(),type:s,content:i,details:t,toolName:r,toolSuccess:n})}handleComplete(e){const t=this.state.getState(),r=0===e.exitCode?"completed":"failed",n=t.currentPrompt?.id;if(t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:r,completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),n&&this.config.onPromptComplete&&this.config.onPromptComplete(n,r),this.config.reloadOnComplete&&"completed"===r){const e=this.config.reloadDelay??1500;return console.log(`[Orquesta Embed] Prompt completed. Reloading page in ${e}ms...`),void setTimeout(()=>{window.location.reload()},e)}this.processQueue()}async processQueue(){const e=this.state.getNextFromQueue();if(e){console.log(`[Orquesta Embed] Processing queued prompt. Remaining in queue: ${this.state.getQueueLength()}`);try{await this.submitPrompt(e.content,e.options)}catch(e){console.error("[Orquesta Embed] Failed to process queued prompt:",e),this.processQueue()}}}handleError(e){const t=this.state.getState();this.state.addOutputLine({timestamp:Date.now(),type:"stderr",content:`Error: ${e.error}`}),t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:"failed",completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),this.processQueue()}async submitPrompt(e,t){if(!this.projectId)throw new Error("Not connected");if(this.config.requireAuth&&!this.state.getState().isAuthenticated)throw new Error("Authentication required. Please log in first.");const r=this.state.getState();if(r.isSubmitting)return this.state.addToQueue({id:`queue-${Date.now()}`,content:e,options:t,queuedAt:Date.now()}),console.log(`[Orquesta Embed] Prompt queued. Queue length: ${this.state.getQueueLength()}`),`queued-${Date.now()}`;this.state.setState({isSubmitting:!0}),this.state.clearOutput();let n=e;const s=t?.elementContext||r.selectedElement;if(s&&(n+=`\n\n--- Element Context ---\nSelector: ${s.selector}\nTag: <${s.tag}>\n${s.id?`ID: ${s.id}`:""}\n${s.className?`Classes: ${s.className}`:""}\n${s.textContent?`Text: ${s.textContent}`:""}\n${s.attributes?`Attributes: ${JSON.stringify(s.attributes)}`:""}`),t?.includeConsole??r.includeConsole){const e=this.consoleCapture.formatForPrompt();e&&(n+=`\n\n--- Console Logs ---\n${e}`)}if(t?.includeNetwork??r.includeNetwork){const e=this.networkCapture.formatForPrompt();e&&(n+=`\n\n--- Network Errors ---\n${e}`)}if(t?.includeHistory??r.includeHistory){const e=r.promptHistory.filter(e=>"completed"===e.status).slice(0,5).reverse();e.length>0&&(n+="\n\n--- Previous Prompts Context ---",e.forEach((e,t)=>{n+=`\n\n[Prompt ${t+1}]: ${e.content}`;const s=r.promptOutputs[e.id];if(s&&s.length>0){const e=s.slice(-10).map(e=>e.content).join("\n");n+=`\n[Output ${t+1}]:\n${e}`}}))}try{const e={"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},t=this.authManager?.getSessionToken();t&&(e["X-Session-Token"]=t);const r=await fetch(`${this.config.apiUrl}/api/embed/prompts`,{method:"POST",headers:e,body:JSON.stringify({projectId:this.projectId,content:n,elementContext:s})});if(!r.ok){const e=await r.json();throw new Error(e.error||"Failed to submit prompt")}const i=(await r.json()).prompt;return this.state.setCurrentPrompt(i),this.state.setSelectedElement(null),this.config.onPromptSubmit?.(i.id),i.id}catch(e){throw this.state.setState({isSubmitting:!1}),e}}async loadTimeline(){if(this.projectId)try{const e=await fetch(`${this.config.apiUrl}/api/embed/prompts?projectId=${this.projectId}&limit=50`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(e.ok){const t=await e.json();this.state.setState({promptHistory:t.prompts||[]})}}catch{}}open(){this.state.setOpen(!0),Qr.set("isOpen",!0)}close(){this.state.setOpen(!1),Qr.set("isOpen",!1)}toggle(){const e=!this.state.getState().isOpen;this.state.setOpen(e),Qr.set("isOpen",e)}startElementSelection(){this.state.startElementSelection(),this.elementSelector.activate(e=>this.state.setSelectedElement(e),()=>this.state.cancelElementSelection())}getState(){return this.state.getState()}subscribe(e){return this.state.subscribe(e)}getConsoleCapture(){return this.consoleCapture}getNetworkCapture(){return this.networkCapture}getElementSelector(){return this.elementSelector}setActiveTab(e){this.state.setActiveTab(e)}async loadComments(e){if(this.projectId){this.state.setLoadingComments(!0);try{const t=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(t.ok){const r=await t.json();this.state.setCommentsForPrompt(e,r.comments||[])}}catch{}finally{this.state.setLoadingComments(!1)}}}async addComment(e,t){if(this.projectId)try{const r=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({content:t})});if(r.ok){const t=await r.json();t.comment&&this.state.addComment(e,t.comment)}}catch(e){throw console.error("Failed to add comment:",e),e}}setOverlayMode(e){if(this.state.setOverlayMode(e),"off"===e)this.elementSelector.removeHighlight(),this.state.setHighlightedPromptId(null);else if("all"===e){const e=this.state.getState().promptHistory.filter(e=>e.element_context?.selector).map(e=>({promptId:e.id,selector:e.element_context.selector,rect:null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}));this.state.setElementMarkers(e)}else this.state.setElementMarkers([])}highlightPromptElement(e){if(!e.element_context?.selector)return void console.warn("Prompt has no element context");this.elementSelector.highlightElement(e.element_context.selector)?(this.state.setHighlightedPromptId(e.id),this.state.setOverlayMode("single")):console.warn("Element not found for prompt:",e.id)}setupGlobalRightClick(e){return this.elementSelector.setupGlobalRightClick(e)}setupGlobalRightClickWithPosition(e){return this.elementSelector.setupGlobalRightClickWithPosition(e)}async login(){if(!this.authManager)throw new Error("Authentication is not enabled. Set requireAuth: true in config.");try{const e=await this.authManager.login();return this.config.onLogin?.(e.user),e.user}catch(e){throw e}}async logout(){if(!this.authManager)throw new Error("Authentication is not enabled.");await this.authManager.logout(),this.config.onLogout?.()}isAuthenticated(){return this.state.getState().isAuthenticated}getUser(){return this.state.getState().user}isAuthRequired(){return this.config.requireAuth||!1}}function en(e,t,r){const n=document.createElement(e);return t&&Object.entries(t).forEach(([e,t])=>{void 0!==t&&!1!==t&&("className"===e?n.className=t:e.startsWith("on")&&"string"==typeof t||(!0===t?n.setAttribute(e,""):n.setAttribute(e,t)))}),r&&r.forEach(e=>{"string"==typeof e?n.appendChild(document.createTextNode(e)):n.appendChild(e)}),n}function tn(e,t,r,n){return e.addEventListener(t,r,n),()=>e.removeEventListener(t,r,n)}function rn(e,t){Object.assign(e.style,t)}function nn(e){e?.parentNode?.removeChild(e)}class sn{constructor(e){this.state=null,this.elements={container:document.createElement("div"),panel:null,trigger:null,promptInput:null,logStream:null,statusBar:null,statusBarMinimized:null,contextMenu:null,elementMarkers:null},this.unsubscribe=null,this.cleanupFunctions=[],this.isMinimized=!1,this.showStatusBar=!0,this.statusBarMinimized=!1,this.lastCompletedPrompt=null,this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,this.builderTerminalCollapsed=!1,this.builderMessages=[],this.builderLastOutputCount=0,this.contextMenuState={isOpen:!1,position:{x:0,y:0},element:null},this.globalRightClickCleanup=null,this.config=e,this.currentMode=e.mode||"widget",this.client=new Zr(e),function(e,t){const r=document.getElementById(t);if(r)return r;const n=document.createElement("style");n.id=t,n.textContent=e,document.head.appendChild(n)}("\n/* Orquesta Embed SDK Styles - Auto-injected */\n/* These styles are scoped to orquesta-* classes to avoid conflicts */\n\n/* Reset for Orquesta elements */\n[class^=\"orquesta-\"],\n[class*=\" orquesta-\"] {\n box-sizing: border-box;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n/* Base colors */\n.orquesta-embed-panel {\n --orq-bg: #18181b;\n --orq-bg-secondary: #27272a;\n --orq-border: #3f3f46;\n --orq-text: #fafafa;\n --orq-text-muted: #a1a1aa;\n --orq-primary: #3b82f6;\n --orq-success: #22c55e;\n --orq-warning: #eab308;\n --orq-error: #ef4444;\n}\n\n/* Scrollbar styling */\n.orquesta-embed-panel ::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-track {\n background: transparent;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb {\n background: #3f3f46;\n border-radius: 3px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb:hover {\n background: #52525b;\n}\n\n/* Animations */\n@keyframes orquesta-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n@keyframes orquesta-pulse {\n 0%, 100% {\n opacity: 1;\n }\n 50% {\n opacity: 0.5;\n }\n}\n\n.orquesta-embed-panel .animate-spin {\n animation: orquesta-spin 1s linear infinite;\n}\n\n.orquesta-embed-panel .animate-pulse {\n animation: orquesta-pulse 2s ease-in-out infinite;\n}\n\n/* Utility classes */\n.orquesta-embed-panel .line-clamp-1 {\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n.orquesta-embed-panel .line-clamp-2 {\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n/* Focus visible */\n.orquesta-embed-panel button:focus-visible,\n.orquesta-embed-panel input:focus-visible,\n.orquesta-embed-panel textarea:focus-visible {\n outline: 2px solid var(--orq-primary);\n outline-offset: 2px;\n}\n\n/* Element selector highlight animation */\n#orquesta-element-highlight {\n animation: orquesta-highlight-pulse 1.5s ease-in-out infinite;\n}\n\n@keyframes orquesta-highlight-pulse {\n 0%, 100% {\n box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4);\n }\n 50% {\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2);\n }\n}\n\n/* Tooltip */\n.orquesta-tooltip {\n position: absolute;\n z-index: 2147483647;\n padding: 4px 8px;\n background: #18181b;\n border: 1px solid #3f3f46;\n border-radius: 4px;\n font-size: 12px;\n color: #fafafa;\n pointer-events: none;\n white-space: nowrap;\n}\n\n/* Transitions */\n.orquesta-embed-panel * {\n transition-property: color, background-color, border-color, opacity, transform;\n transition-duration: 150ms;\n transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);\n}\n\n/* Panel entrance animation */\n.orquesta-embed-panel {\n animation: orquesta-panel-enter 0.2s ease-out;\n}\n\n@keyframes orquesta-panel-enter {\n from {\n opacity: 0;\n transform: scale(0.95) translateY(10px);\n }\n to {\n opacity: 1;\n transform: scale(1) translateY(0);\n }\n}\n\n/* Trigger button */\n.orquesta-embed-trigger {\n animation: orquesta-trigger-enter 0.3s ease-out;\n}\n\n@keyframes orquesta-trigger-enter {\n from {\n opacity: 0;\n transform: scale(0.8);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n}\n\n/* Log stream */\n.orquesta-log-stream {\n background: #0a0a0a;\n border: 1px solid #27272a;\n border-radius: 6px;\n padding: 8px;\n}\n\n/* Timeline item hover */\n.orquesta-timeline button:hover {\n transform: translateX(2px);\n}\n\n/* ============================================ */\n/* Tailwind class overrides - CRITICAL STYLES */\n/* These ensure styles work even when purged */\n/* ============================================ */\n\n/* Explicit background colors */\n.orquesta-embed-panel {\n background-color: #18181b !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel .bg-zinc-950 { background-color: #09090b !important; }\n.orquesta-embed-panel .bg-zinc-900 { background-color: #18181b !important; }\n.orquesta-embed-panel .bg-zinc-800 { background-color: #27272a !important; }\n.orquesta-embed-panel .bg-zinc-700 { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .bg-zinc-600 { background-color: #52525b !important; }\n\n/* Text colors */\n.orquesta-embed-panel .text-white { color: #fafafa !important; }\n.orquesta-embed-panel .text-zinc-100 { color: #f4f4f5 !important; }\n.orquesta-embed-panel .text-zinc-200 { color: #e4e4e7 !important; }\n.orquesta-embed-panel .text-zinc-300 { color: #d4d4d8 !important; }\n.orquesta-embed-panel .text-zinc-400 { color: #a1a1aa !important; }\n.orquesta-embed-panel .text-zinc-500 { color: #71717a !important; }\n.orquesta-embed-panel .text-red-400 { color: #f87171 !important; }\n.orquesta-embed-panel .text-red-300 { color: #fca5a5 !important; }\n.orquesta-embed-panel .text-green-400 { color: #4ade80 !important; }\n.orquesta-embed-panel .text-green-500 { color: #22c55e !important; }\n.orquesta-embed-panel .text-blue-400 { color: #60a5fa !important; }\n.orquesta-embed-panel .text-blue-500 { color: #3b82f6 !important; }\n.orquesta-embed-panel .text-yellow-400 { color: #facc15 !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .text-orange-400 { color: #fb923c !important; }\n.orquesta-embed-panel .text-gray-800 { color: #1f2937 !important; }\n\n/* Border colors */\n.orquesta-embed-panel .border-zinc-700 { border-color: #3f3f46 !important; }\n.orquesta-embed-panel .border-zinc-800 { border-color: #27272a !important; }\n.orquesta-embed-panel .border-red-800 { border-color: #991b1b !important; }\n\n/* Background colors for buttons and UI */\n.orquesta-embed-panel .bg-blue-500 { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .bg-blue-600 { background-color: #2563eb !important; }\n.orquesta-embed-panel .bg-green-400 { background-color: #4ade80 !important; }\n.orquesta-embed-panel .bg-green-500 { background-color: #22c55e !important; }\n.orquesta-embed-panel .bg-green-600 { background-color: #16a34a !important; }\n.orquesta-embed-panel .bg-red-500 { background-color: #ef4444 !important; }\n.orquesta-embed-panel .bg-red-600 { background-color: #dc2626 !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-red-900\\/30 { background-color: rgba(127, 29, 29, 0.3) !important; }\n.orquesta-embed-panel .bg-white { background-color: #ffffff !important; }\n\n/* Hover states */\n.orquesta-embed-panel .hover\\:bg-zinc-700:hover { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .hover\\:bg-zinc-800:hover { background-color: #27272a !important; }\n.orquesta-embed-panel .hover\\:bg-blue-500:hover { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .hover\\:bg-blue-700:hover { background-color: #1d4ed8 !important; }\n.orquesta-embed-panel .hover\\:bg-gray-100:hover { background-color: #f3f4f6 !important; }\n.orquesta-embed-panel .hover\\:text-white:hover { color: #fafafa !important; }\n.orquesta-embed-panel .hover\\:text-zinc-300:hover { color: #d4d4d8 !important; }\n\n/* Form inputs */\n.orquesta-embed-panel input,\n.orquesta-embed-panel textarea {\n background-color: #27272a !important;\n border-color: #3f3f46 !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel input::placeholder,\n.orquesta-embed-panel textarea::placeholder {\n color: #71717a !important;\n}\n\n/* Buttons base */\n.orquesta-embed-panel button {\n background-color: transparent;\n}\n\n.orquesta-embed-panel button:hover {\n background-color: #3f3f46;\n}\n\n/* Rounded borders */\n.orquesta-embed-panel .rounded { border-radius: 0.25rem !important; }\n.orquesta-embed-panel .rounded-md { border-radius: 0.375rem !important; }\n.orquesta-embed-panel .rounded-lg { border-radius: 0.5rem !important; }\n.orquesta-embed-panel .rounded-xl { border-radius: 0.75rem !important; }\n.orquesta-embed-panel .rounded-full { border-radius: 9999px !important; }\n\n/* Border widths */\n.orquesta-embed-panel .border { border-width: 1px !important; }\n.orquesta-embed-panel .border-b { border-bottom-width: 1px !important; }\n.orquesta-embed-panel .border-t { border-top-width: 1px !important; }\n\n/* Padding */\n.orquesta-embed-panel .p-1 { padding: 0.25rem !important; }\n.orquesta-embed-panel .p-2 { padding: 0.5rem !important; }\n.orquesta-embed-panel .p-3 { padding: 0.75rem !important; }\n.orquesta-embed-panel .p-4 { padding: 1rem !important; }\n.orquesta-embed-panel .px-2 { padding-left: 0.5rem !important; padding-right: 0.5rem !important; }\n.orquesta-embed-panel .px-3 { padding-left: 0.75rem !important; padding-right: 0.75rem !important; }\n.orquesta-embed-panel .px-4 { padding-left: 1rem !important; padding-right: 1rem !important; }\n.orquesta-embed-panel .py-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; }\n.orquesta-embed-panel .py-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .py-3 { padding-top: 0.75rem !important; padding-bottom: 0.75rem !important; }\n\n/* Margin */\n.orquesta-embed-panel .m-1 { margin: 0.25rem !important; }\n.orquesta-embed-panel .m-2 { margin: 0.5rem !important; }\n.orquesta-embed-panel .mb-1 { margin-bottom: 0.25rem !important; }\n.orquesta-embed-panel .mb-2 { margin-bottom: 0.5rem !important; }\n.orquesta-embed-panel .mb-4 { margin-bottom: 1rem !important; }\n.orquesta-embed-panel .mt-1 { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .mt-2 { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .mt-3 { margin-top: 0.75rem !important; }\n.orquesta-embed-panel .mt-4 { margin-top: 1rem !important; }\n.orquesta-embed-panel .mr-1 { margin-right: 0.25rem !important; }\n.orquesta-embed-panel .mr-2 { margin-right: 0.5rem !important; }\n.orquesta-embed-panel .mx-1 { margin-left: 0.25rem !important; margin-right: 0.25rem !important; }\n\n/* Gap */\n.orquesta-embed-panel .gap-0\\.5 { gap: 0.125rem !important; }\n.orquesta-embed-panel .gap-1 { gap: 0.25rem !important; }\n.orquesta-embed-panel .gap-1\\.5 { gap: 0.375rem !important; }\n.orquesta-embed-panel .gap-2 { gap: 0.5rem !important; }\n.orquesta-embed-panel .gap-3 { gap: 0.75rem !important; }\n.orquesta-embed-panel .gap-4 { gap: 1rem !important; }\n\n/* Flex */\n.orquesta-embed-panel .flex { display: flex !important; }\n.orquesta-embed-panel .flex-col { flex-direction: column !important; }\n.orquesta-embed-panel .flex-1 { flex: 1 1 0% !important; }\n.orquesta-embed-panel .flex-shrink-0 { flex-shrink: 0 !important; }\n.orquesta-embed-panel .items-center { align-items: center !important; }\n.orquesta-embed-panel .items-start { align-items: flex-start !important; }\n.orquesta-embed-panel .justify-center { justify-content: center !important; }\n.orquesta-embed-panel .justify-between { justify-content: space-between !important; }\n\n/* Width/Height */\n.orquesta-embed-panel .w-full { width: 100% !important; }\n.orquesta-embed-panel .w-2 { width: 0.5rem !important; }\n.orquesta-embed-panel .w-3 { width: 0.75rem !important; }\n.orquesta-embed-panel .w-3\\.5 { width: 0.875rem !important; }\n.orquesta-embed-panel .w-4 { width: 1rem !important; }\n.orquesta-embed-panel .w-5 { width: 1.25rem !important; }\n.orquesta-embed-panel .w-6 { width: 1.5rem !important; }\n.orquesta-embed-panel .w-8 { width: 2rem !important; }\n.orquesta-embed-panel .w-16 { width: 4rem !important; }\n.orquesta-embed-panel .h-2 { height: 0.5rem !important; }\n.orquesta-embed-panel .h-3 { height: 0.75rem !important; }\n.orquesta-embed-panel .h-3\\.5 { height: 0.875rem !important; }\n.orquesta-embed-panel .h-4 { height: 1rem !important; }\n.orquesta-embed-panel .h-5 { height: 1.25rem !important; }\n.orquesta-embed-panel .h-6 { height: 1.5rem !important; }\n.orquesta-embed-panel .h-8 { height: 2rem !important; }\n.orquesta-embed-panel .h-16 { height: 4rem !important; }\n.orquesta-embed-panel .h-full { height: 100% !important; }\n.orquesta-embed-panel .max-w-20 { max-width: 5rem !important; }\n\n/* Font */\n.orquesta-embed-panel .text-xs { font-size: 0.75rem !important; line-height: 1rem !important; }\n.orquesta-embed-panel .text-sm { font-size: 0.875rem !important; line-height: 1.25rem !important; }\n.orquesta-embed-panel .text-lg { font-size: 1.125rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-xl { font-size: 1.25rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-2xl { font-size: 1.5rem !important; line-height: 2rem !important; }\n.orquesta-embed-panel .text-4xl { font-size: 2.25rem !important; line-height: 2.5rem !important; }\n.orquesta-embed-panel .font-medium { font-weight: 500 !important; }\n.orquesta-embed-panel .font-semibold { font-weight: 600 !important; }\n.orquesta-embed-panel .font-bold { font-weight: 700 !important; }\n.orquesta-embed-panel .text-center { text-align: center !important; }\n.orquesta-embed-panel .truncate { overflow: hidden !important; text-overflow: ellipsis !important; white-space: nowrap !important; }\n\n/* Opacity */\n.orquesta-embed-panel .opacity-25 { opacity: 0.25 !important; }\n.orquesta-embed-panel .opacity-50 { opacity: 0.5 !important; }\n.orquesta-embed-panel .opacity-75 { opacity: 0.75 !important; }\n\n/* Overflow */\n.orquesta-embed-panel .overflow-hidden { overflow: hidden !important; }\n.orquesta-embed-panel .overflow-y-auto { overflow-y: auto !important; }\n\n/* Shadow */\n.orquesta-embed-panel .shadow-xl { box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04) !important; }\n.orquesta-embed-panel .shadow-2xl { box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important; }\n.orquesta-embed-panel .shadow-lg { box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05) !important; }\n\n/* Position */\n.orquesta-embed-panel .fixed { position: fixed !important; }\n.orquesta-embed-panel .absolute { position: absolute !important; }\n.orquesta-embed-panel .relative { position: relative !important; }\n.orquesta-embed-panel .top-1 { top: 0.25rem !important; }\n.orquesta-embed-panel .right-1 { right: 0.25rem !important; }\n.orquesta-embed-panel .bottom-0 { bottom: 0 !important; }\n.orquesta-embed-panel .right-0 { right: 0 !important; }\n\n/* Z-index */\n.orquesta-embed-panel .z-\\[2147483647\\] { z-index: 2147483647 !important; }\n\n/* Cursor */\n.orquesta-embed-panel .cursor-move { cursor: move !important; }\n.orquesta-embed-panel .cursor-se-resize { cursor: se-resize !important; }\n.orquesta-embed-panel .cursor-not-allowed { cursor: not-allowed !important; }\n\n/* Select */\n.orquesta-embed-panel .select-none { user-select: none !important; }\n\n/* Disabled states */\n.orquesta-embed-panel .disabled\\:opacity-50:disabled { opacity: 0.5 !important; }\n.orquesta-embed-panel .disabled\\:cursor-not-allowed:disabled { cursor: not-allowed !important; }\n.orquesta-embed-panel .disabled\\:bg-blue-800:disabled { background-color: #1e40af !important; }\n.orquesta-embed-panel .disabled\\:bg-gray-300:disabled { background-color: #d1d5db !important; }\n\n/* Transition */\n.orquesta-embed-panel .transition-colors { transition-property: color, background-color, border-color !important; transition-duration: 150ms !important; }\n.orquesta-embed-panel .transition-all { transition-property: all !important; transition-duration: 150ms !important; }\n\n/* ============================================ */\n/* Action buttons & Comments - Timeline styles */\n/* ============================================ */\n\n/* Purple colors for \"Show on page\" button */\n.orquesta-embed-panel .text-purple-300 { color: #d8b4fe !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-purple-600\\/20 { background-color: rgba(147, 51, 234, 0.2) !important; }\n.orquesta-embed-panel .bg-purple-600\\/30 { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .border-purple-500\\/40 { border-color: rgba(168, 85, 247, 0.4) !important; }\n.orquesta-embed-panel .border-purple-500\\/60 { border-color: rgba(168, 85, 247, 0.6) !important; }\n.orquesta-embed-panel .hover\\:bg-purple-600\\/30:hover { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .hover\\:border-purple-500\\/60:hover { border-color: rgba(168, 85, 247, 0.6) !important; }\n\n/* Zinc with opacity for \"View output\" button */\n.orquesta-embed-panel .bg-zinc-700\\/50 { background-color: rgba(63, 63, 70, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600\\/50 { border-color: rgba(82, 82, 91, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600 { border-color: #52525b !important; }\n.orquesta-embed-panel .border-zinc-500 { border-color: #71717a !important; }\n.orquesta-embed-panel .hover\\:border-zinc-500:hover { border-color: #71717a !important; }\n\n/* Blue with opacity */\n.orquesta-embed-panel .bg-blue-500\\/20 { background-color: rgba(59, 130, 246, 0.2) !important; }\n.orquesta-embed-panel .border-blue-500\\/30 { border-color: rgba(59, 130, 246, 0.3) !important; }\n.orquesta-embed-panel .text-blue-300 { color: #93c5fd !important; }\n.orquesta-embed-panel .text-blue-300\\/70 { color: rgba(147, 197, 253, 0.7) !important; }\n\n/* Additional padding */\n.orquesta-embed-panel .py-1\\.5 { padding-top: 0.375rem !important; padding-bottom: 0.375rem !important; }\n.orquesta-embed-panel .py-0\\.5 { padding-top: 0.125rem !important; padding-bottom: 0.125rem !important; }\n.orquesta-embed-panel .px-1\\.5 { padding-left: 0.375rem !important; padding-right: 0.375rem !important; }\n.orquesta-embed-panel .px-2\\.5 { padding-left: 0.625rem !important; padding-right: 0.625rem !important; }\n.orquesta-embed-panel .pb-2 { padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .pb-3 { padding-bottom: 0.75rem !important; }\n.orquesta-embed-panel .pt-1 { padding-top: 0.25rem !important; }\n\n/* Space utilities */\n.orquesta-embed-panel .space-y-0\\.5 > * + * { margin-top: 0.125rem !important; }\n.orquesta-embed-panel .space-y-1 > * + * { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .space-y-2 > * + * { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .space-y-3 > * + * { margin-top: 0.75rem !important; }\n\n/* Focus states */\n.orquesta-embed-panel .focus\\:outline-none:focus { outline: none !important; }\n.orquesta-embed-panel .focus\\:ring-1:focus { box-shadow: 0 0 0 1px var(--orq-primary, #3b82f6) !important; }\n.orquesta-embed-panel .focus\\:ring-blue-500:focus { --tw-ring-color: #3b82f6 !important; }\n\n/* Placeholder colors */\n.orquesta-embed-panel .placeholder\\:text-zinc-500::placeholder { color: #71717a !important; }\n\n/* Text utilities */\n.orquesta-embed-panel .break-words { word-wrap: break-word !important; overflow-wrap: break-word !important; }\n.orquesta-embed-panel .italic { font-style: italic !important; }\n\n/* Negative margins */\n.orquesta-embed-panel .-mt-1 { margin-top: -0.25rem !important; }\n\n/* Max height */\n.orquesta-embed-panel .max-h-\\[400px\\] { max-height: 400px !important; }\n.orquesta-embed-panel .max-h-\\[150px\\] { max-height: 150px !important; }\n\n/* Font mono */\n.orquesta-embed-panel .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important; }\n\n/* Text sizes */\n.orquesta-embed-panel .text-\\[10px\\] { font-size: 10px !important; line-height: 1.4 !important; }\n.orquesta-embed-panel .text-\\[11px\\] { font-size: 11px !important; line-height: 1.4 !important; }\n\n/* Flex wrap */\n.orquesta-embed-panel .flex-wrap { flex-wrap: wrap !important; }\n\n/* Min width */\n.orquesta-embed-panel .min-w-0 { min-width: 0 !important; }\n\n/* ml-auto for comment button alignment */\n.orquesta-embed-panel .ml-auto { margin-left: auto !important; }\n\n/* Hidden utility */\n.orquesta-embed-panel .hidden { display: none !important; }\n\n/* SVG icon sizing */\n.orquesta-embed-panel svg { flex-shrink: 0; }\n\n/* Mobile responsive */\n@media (max-width: 480px) {\n .orquesta-embed-panel {\n position: fixed !important;\n left: 8px !important;\n right: 8px !important;\n bottom: 8px !important;\n top: auto !important;\n width: auto !important;\n max-height: 70vh !important;\n }\n}\n\n/* Builder Mode */\n.orquesta-builder{display:flex;flex-direction:column;width:100%;height:100vh;background:#0a0a0a;color:#fafafa;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;overflow:hidden}\n.orquesta-builder-header{display:flex;align-items:center;justify-content:space-between;height:48px;padding:0 16px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-header-left{display:flex;align-items:center;gap:12px}\n.orquesta-builder-header-right{display:flex;align-items:center;gap:8px}\n.orquesta-builder-logo{font-weight:700;font-size:14px;color:#fafafa;letter-spacing:-0.02em}\n.orquesta-builder-project{font-size:13px;color:#a1a1aa}\n.orquesta-builder-status{display:flex;align-items:center;gap:6px;font-size:12px;color:#a1a1aa}\n.orquesta-builder-status-dot{width:8px;height:8px;border-radius:50%}\n.orquesta-builder-main{display:flex;flex:1;min-height:0}\n.orquesta-builder-chat{display:flex;flex-direction:column;width:380px;min-width:300px;max-width:50%;border-right:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}\n.orquesta-builder-chat-input{padding:12px 16px;border-top:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-input textarea{width:100%;min-height:60px;max-height:200px;padding:10px 12px;background:#27272a;border:1px solid #3f3f46;border-radius:8px;color:#fafafa;font-size:13px;resize:vertical;outline:none;font-family:inherit}\n.orquesta-builder-chat-input textarea:focus{border-color:#3b82f6}\n.orquesta-builder-chat-input-actions{display:flex;justify-content:space-between;align-items:center;margin-top:8px}\n.orquesta-builder-preview{flex:1;display:flex;flex-direction:column;min-width:0}\n.orquesta-builder-preview-bar{display:flex;align-items:center;height:36px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;gap:8px;flex-shrink:0}\n.orquesta-builder-preview-url{flex:1;padding:4px 10px;background:#27272a;border:1px solid #3f3f46;border-radius:6px;color:#a1a1aa;font-size:12px;font-family:'SF Mono','Fira Code',monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.orquesta-builder-preview-iframe{flex:1;width:100%;border:none;background:#fff}\n.orquesta-builder-terminal{height:200px;min-height:100px;max-height:50vh;border-top:1px solid #27272a;background:#0a0a0a;display:flex;flex-direction:column;flex-shrink:0}\n.orquesta-builder-terminal-header{display:flex;align-items:center;justify-content:space-between;height:32px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-terminal-title{font-size:12px;font-weight:600;color:#a1a1aa;text-transform:uppercase;letter-spacing:0.05em}\n.orquesta-builder-terminal-output{flex:1;overflow-y:auto;padding:8px 12px;font-family:'SF Mono','Fira Code','Cascadia Code',monospace;font-size:12px;line-height:1.5}\n.orquesta-builder-terminal.collapsed{height:32px;min-height:32px}\n.orquesta-builder-terminal.collapsed .orquesta-builder-terminal-output{display:none}\n.orquesta-builder-msg{max-width:90%;padding:10px 14px;border-radius:12px;font-size:13px;line-height:1.5;word-break:break-word}\n.orquesta-builder-msg-user{align-self:flex-end;background:#3b82f6;color:#fff;border-bottom-right-radius:4px}\n.orquesta-builder-msg-system{align-self:flex-start;background:#27272a;color:#fafafa;border-bottom-left-radius:4px}\n.orquesta-builder-msg-status{align-self:center;background:transparent;color:#71717a;font-size:12px;padding:4px 0}\n.orquesta-builder-resizer-h{width:4px;cursor:col-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-h:hover{background:#3b82f6}\n.orquesta-builder-resizer-v{height:4px;cursor:row-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-v:hover{background:#3b82f6}\n.orquesta-builder button{background:transparent;border:none;color:#a1a1aa;cursor:pointer;padding:4px 8px;border-radius:4px;font-size:12px}\n.orquesta-builder button:hover{background:#27272a;color:#fafafa}\n.orquesta-builder-btn-primary{background:#3b82f6!important;color:#fff!important;font-weight:500;padding:6px 16px!important;border-radius:6px!important}\n.orquesta-builder-btn-primary:hover{background:#2563eb!important}\n.orquesta-builder-btn-primary:disabled{opacity:0.5;cursor:not-allowed}\n@media(max-width:768px){.orquesta-builder-main{flex-direction:column}.orquesta-builder-chat{width:100%;max-width:100%;height:50%;border-right:none;border-bottom:1px solid #27272a}.orquesta-builder-resizer-h{display:none}}\n","orquesta-embed-styles"),this.elements.container.id="orquesta-widget-container",document.body.appendChild(this.elements.container),!1!==e.enableGlobalRightClick&&this.setupGlobalRightClick()}setupGlobalRightClick(){this.globalRightClickCleanup=this.client.setupGlobalRightClickWithPosition((e,t)=>{this.client.getElementSelector().deactivate(),this.client.getElementSelector().highlightSelectedElement(e.selector),this.contextMenuState={isOpen:!0,position:t,element:e},this.render()})}async init(){console.log("[Orquesta Embed] v0.1.37"),this.unsubscribe=this.client.subscribe(e=>{this.state=e,this.render()});try{await this.client.connect()}catch(e){throw this.renderError(e instanceof Error?e.message:"Connection failed"),e}}render(){this.state&&("builder"!==this.currentMode?(this.elements.container.innerHTML="",this.cleanupFunctions.forEach(e=>e()),this.cleanupFunctions=[],"completed"!==this.state.currentPrompt?.status&&"failed"!==this.state.currentPrompt?.status||(this.lastCompletedPrompt=this.state.currentPrompt),this.showStatusBar&&this.renderStatusBar(),this.state.isOpen&&!this.isMinimized||this.renderTrigger(),this.state.isOpen&&!this.isMinimized&&this.renderPanel(),this.state.isSelectingElement&&this.renderElementInspector(),this.contextMenuState.isOpen&&this.renderContextMenu(),"all"===this.state.overlayMode&&this.state.elementMarkers.length>0&&this.renderElementMarkers()):this.renderBuilder())}renderTrigger(){const e=this.config.position||"bottom-right",[t,r]=e.split("-"),n=en("button",{className:"orquesta-embed-trigger"},["⬡"]);if(rn(n,{position:"fixed",zIndex:"2147483647",padding:"12px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"50%",boxShadow:"0 10px 25px rgba(0,0,0,0.3)",cursor:"pointer",fontSize:"20px",["top"===t?"top":"bottom"]:"20px",["left"===r?"left":"right"]:"20px"}),this.state?.agentOnline){const e=en("span");rn(e,{position:"absolute",top:"4px",right:"4px",width:"8px",height:"8px",background:"#22c55e",borderRadius:"50%"}),n.appendChild(e)}const s=tn(n,"click",()=>{this.isMinimized=!1,this.client.open()});this.cleanupFunctions.push(s),this.elements.container.appendChild(n),this.elements.trigger=n}renderPanel(){if(!this.state)return;const e=en("div",{className:"orquesta-embed-panel"});rn(e,{position:"fixed",zIndex:"2147483647",width:"400px",height:"500px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"8px",boxShadow:"0 25px 50px rgba(0,0,0,0.5)",display:"flex",flexDirection:"column",overflow:"hidden",right:"20px",bottom:"20px"});const t=this.createHeader();e.appendChild(t);const r=this.createTabs();if(e.appendChild(r),this.state?.connectionError){const t=en("div");rn(t,{margin:"8px 12px",padding:"8px 12px",background:"rgba(127, 29, 29, 0.3)",border:"1px solid rgba(239, 68, 68, 0.3)",borderRadius:"8px",display:"flex",alignItems:"center",gap:"8px"});const r=en("span",{},["⚠️"]);rn(r,{fontSize:"12px"});const n=en("span",{},[this.state.connectionError]);rn(n,{fontSize:"11px",color:"#fca5a5"}),t.appendChild(r),t.appendChild(n),e.appendChild(t)}if(!this.state?.isConnected&&!this.state?.connectionError){const t=en("div");rn(t,{margin:"8px 12px",padding:"8px 12px",background:"rgba(113, 63, 18, 0.3)",border:"1px solid rgba(234, 179, 8, 0.3)",borderRadius:"8px",display:"flex",alignItems:"center",gap:"8px"});const r=en("span",{},["ℹ️"]);rn(r,{fontSize:"12px"});const n=en("span",{},["Reconnecting to Orquesta..."]);rn(n,{fontSize:"11px",color:"#fcd34d"}),t.appendChild(r),t.appendChild(n),e.appendChild(t)}const n=en("div");if(rn(n,{flex:"1",overflowY:"auto",padding:"12px"}),this.state?.requireAuth&&!this.state?.isAuthenticated){const e=this.createAuthOverlay();n.appendChild(e)}else{const e=this.createContent();n.appendChild(e)}e.appendChild(n),this.elements.container.appendChild(e),this.elements.panel=e}createAuthOverlay(){const e=en("div");rn(e,{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",textAlign:"center",padding:"16px"});const t=en("div");rn(t,{width:"64px",height:"64px",borderRadius:"50%",background:"#27272a",display:"flex",alignItems:"center",justifyContent:"center",marginBottom:"16px"});const r=en("span",{},["🔒"]);rn(r,{fontSize:"28px"}),t.appendChild(r),e.appendChild(t);const n=en("h3",{},["Sign in to continue"]);rn(n,{color:"white",fontWeight:"600",margin:"0 0 8px 0",fontSize:"16px"}),e.appendChild(n);const s=en("p",{},["You need to sign in to submit prompts to this project."]);if(rn(s,{color:"#a1a1aa",fontSize:"13px",margin:"0 0 16px 0"}),e.appendChild(s),this.state?.authError){const t=en("div",{},[this.state.authError]);rn(t,{marginBottom:"16px",padding:"8px 12px",background:"rgba(127, 29, 29, 0.3)",border:"1px solid #7f1d1d",borderRadius:"6px",color:"#fca5a5",fontSize:"12px"}),e.appendChild(t)}const i=en("button");if(rn(i,{display:"flex",alignItems:"center",gap:"8px",padding:"10px 20px",background:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"500",fontSize:"14px",color:"#374151"}),this.state?.isAuthenticating){const e=en("span",{},["⏳"]),t=en("span",{},["Signing in..."]);i.appendChild(e),i.appendChild(t),i.style.opacity="0.7"}else{const e=en("span",{},["G"]);rn(e,{fontWeight:"bold",color:"#4285f4"});const t=en("span",{},["Continue with Google"]);i.appendChild(e),i.appendChild(t)}const o=tn(i,"click",()=>{this.state?.isAuthenticating||this.client.login()});this.cleanupFunctions.push(o),e.appendChild(i);const a=en("p",{},["You must be a member of this project's organization."]);return rn(a,{color:"#71717a",fontSize:"11px",marginTop:"16px"}),e.appendChild(a),e}createHeader(){const e=en("div");rn(e,{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",background:"#27272a",borderBottom:"1px solid #3f3f46",cursor:"move"});const t=en("div");rn(t,{display:"flex",alignItems:"center",gap:"8px"});const r=en("span",{},["⬡"]);rn(r,{fontSize:"16px"});const n=en("span",{},["Orquesta"]);if(rn(n,{fontWeight:"600",color:"white",fontSize:"14px"}),t.appendChild(r),t.appendChild(n),this.state?.projectName){const e=en("span",{},[`• ${this.state.projectName}`]);rn(e,{fontSize:"12px",color:"#a1a1aa"}),t.appendChild(e)}const s=en("div");if(rn(s,{display:"flex",alignItems:"center",gap:"4px"}),this.state?.requireAuth)if(this.state.isAuthenticated&&this.state.user){const e=en("div");if(rn(e,{display:"flex",alignItems:"center",gap:"6px",marginRight:"8px"}),this.state.user.avatar_url){const t=en("img",{src:this.state.user.avatar_url});rn(t,{width:"20px",height:"20px",borderRadius:"50%"}),e.appendChild(t)}else{const t=en("div",{},[this.state.user.full_name?.[0]?.toUpperCase()||"?"]);rn(t,{width:"20px",height:"20px",borderRadius:"50%",background:"#52525b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",color:"white"}),e.appendChild(t)}const t=en("span",{},[this.state.user.full_name||"User"]);rn(t,{fontSize:"12px",color:"#d4d4d8",maxWidth:"80px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),e.appendChild(t);const r=en("button",{},["↪"]);rn(r,{padding:"4px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",fontSize:"12px"});const n=tn(r,"click",()=>this.client.logout());this.cleanupFunctions.push(n),e.appendChild(r),s.appendChild(e)}else{const e=en("button",{},[this.state?.isAuthenticating?"...":"Sign in"]);rn(e,{padding:"4px 8px",marginRight:"8px",background:"#2563eb",border:"none",borderRadius:"4px",color:"white",cursor:"pointer",fontSize:"11px"});const t=tn(e,"click",()=>this.client.login());this.cleanupFunctions.push(t),s.appendChild(e)}const i=en("span");rn(i,{width:"8px",height:"8px",borderRadius:"50%",marginRight:"4px",background:this.state?.isConnected?this.state?.agentOnline?"#22c55e":"#71717a":"#ef4444"}),i.title=this.state?.isConnected?this.state?.agentOnline?"Agent online":"Agent offline":"Not connected",s.appendChild(i);const o=en("button",{},["🎯"]);rn(o,{padding:"4px",background:this.state?.rightClickEnabled?"#16a34a":"#3f3f46",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"12px"}),o.title=this.state?.rightClickEnabled?"Right-click enabled":"Right-click disabled";const a=tn(o,"click",()=>{if(this.state){const e=!this.state.rightClickEnabled;this.state.rightClickEnabled=e,e?this.globalRightClickCleanup||this.setupGlobalRightClick():this.globalRightClickCleanup&&(this.globalRightClickCleanup(),this.globalRightClickCleanup=null),this.render()}});this.cleanupFunctions.push(a),s.appendChild(o);const l=en("div");rn(l,{display:"flex",gap:"2px",margin:"0 4px",padding:"2px",background:"#27272a",borderRadius:"4px"});[{mode:"off",icon:"👁️🗨️",title:"Overlay off"},{mode:"single",icon:"👁️",title:"Show selected prompt"},{mode:"all",icon:"📍",title:"Show all prompts"}].forEach(({mode:e,icon:t,title:r})=>{const n=en("button",{},[t]),s=this.state?.overlayMode===e;rn(n,{padding:"4px",background:s?"off"===e?"#3f3f46":"single"===e?"#2563eb":"#7c3aed":"transparent",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"10px",opacity:s?"1":"0.5"}),n.title=r;const i=tn(n,"click",()=>{this.state&&(this.state.overlayMode=e,"all"===e?this.state.elementMarkers=this.state.promptHistory.filter(e=>e.element_context?.selector).map(e=>{let t=null;try{t=document.querySelector(e.element_context.selector)}catch{}return{promptId:e.id,selector:e.element_context.selector,rect:t?.getBoundingClientRect()||null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}}):"off"===e&&(this.state.elementMarkers=[],this.state.highlightedPromptId=null,this.client.getElementSelector().removeHighlight()),this.render())});this.cleanupFunctions.push(i),l.appendChild(n)}),s.appendChild(l);const c=this.createIconButton("⛶",()=>{this.switchMode("builder")});c.title="Expand to builder mode",s.appendChild(c);const h=this.createIconButton("−",()=>{this.isMinimized=!0,this.render()});s.appendChild(h);const u=this.createIconButton("×",()=>{this.client.close()});return s.appendChild(u),e.appendChild(t),e.appendChild(s),e}createIconButton(e,t){const r=en("button",{},[e]);rn(r,{padding:"4px 8px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",borderRadius:"4px",fontSize:"16px"});const n=tn(r,"click",t);this.cleanupFunctions.push(n);const s=tn(r,"mouseenter",()=>{rn(r,{background:"#3f3f46",color:"white"})}),i=tn(r,"mouseleave",()=>{rn(r,{background:"transparent",color:"#a1a1aa"})});return this.cleanupFunctions.push(s,i),r}createTabs(){const e=en("div");rn(e,{padding:"8px 12px",borderBottom:"1px solid #27272a"});const t=en("div");rn(t,{display:"flex",gap:"4px",padding:"4px",background:"#27272a",borderRadius:"8px"});return["prompts","timeline","logs"].forEach(e=>{const r=this.state?.activeTab===e,n=en("button",{},[e.charAt(0).toUpperCase()+e.slice(1)]);rn(n,{flex:"1",padding:"6px 12px",background:r?"#3f3f46":"transparent",border:"none",borderRadius:"6px",color:r?"white":"#a1a1aa",cursor:"pointer",fontSize:"13px",fontWeight:"500"});const s=tn(n,"click",()=>{this.state&&(this.state.activeTab=e,this.render())});this.cleanupFunctions.push(s),t.appendChild(n)}),e.appendChild(t),e}createContent(){const e=en("div");switch(this.state?.activeTab){case"prompts":e.appendChild(this.createPromptsTab());break;case"timeline":e.appendChild(this.createTimelineTab());break;case"logs":e.appendChild(this.createLogsTab())}return e}createPromptsTab(){const e=en("div"),t=async()=>{const e=this.elements.promptInput?.value.trim();if(e&&this.state?.agentOnline&&!this.state?.isSubmitting)try{const t=this.state?.selectedElement?{elementContext:this.state.selectedElement}:void 0;await this.client.submitPrompt(e,t),this.elements.promptInput&&(this.elements.promptInput.value=""),this.state&&(this.state.selectedElement=null,this.render())}catch(e){console.error("Failed to submit prompt:",e)}},r=en("textarea",{placeholder:this.state?.agentOnline?"What would you like to do?":"Agent is offline..."});rn(r,{width:"100%",minHeight:"80px",padding:"8px 12px",background:"#27272a",border:"1px solid #3f3f46",borderRadius:"6px",color:"white",fontSize:"14px",resize:"none",outline:"none"}),r.disabled=!this.state?.agentOnline||this.state?.isSubmitting,this.elements.promptInput=r,e.appendChild(r);const n=tn(r,"keydown",e=>{const r=e;"Enter"===r.key&&(r.metaKey||r.ctrlKey)&&(r.preventDefault(),t())});this.cleanupFunctions.push(n);const s=en("div");if(rn(s,{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"}),this.state?.selectedElement){const e=this.createContextBadge("🎯",`<${this.state.selectedElement.tag}>${this.state.selectedElement.textContent?": "+this.state.selectedElement.textContent.slice(0,20)+(this.state.selectedElement.textContent.length>20?"...":""):""}`,"#1e3a5f","#3b82f6","#93c5fd",()=>{this.state&&(this.state.selectedElement=null,this.render())});s.appendChild(e)}if(this.state?.includeConsole){const e=this.createContextBadge("📋","Console logs","#422006","#eab308","#fcd34d",()=>{this.state&&(this.state.includeConsole=!1,this.render())});s.appendChild(e)}if(this.state?.includeNetwork){const e=this.createContextBadge("🌐","Network errors","#450a0a","#ef4444","#fca5a5",()=>{this.state&&(this.state.includeNetwork=!1,this.render())});s.appendChild(e)}if(this.state?.includeContext){const e=this.createContextBadge("🔗","Session outputs","#3b0764","#a855f7","#d8b4fe",()=>{this.state&&(this.state.includeContext=!1,this.render())});s.appendChild(e)}s.childNodes.length>0&&e.appendChild(s);const i=en("div");rn(i,{display:"flex",gap:"8px",marginTop:"8px"});const o=this.createContextButton(this.state?.selectedElement?"🎯 Element ✓":"🎯 Element",()=>{this.client.startElementSelection()},!!this.state?.selectedElement),a=this.createContextButton("📋 Logs",()=>{this.state&&(this.state.includeConsole=!this.state.includeConsole,this.render())},this.state?.includeConsole),l=this.createContextButton("🌐 Network",()=>{this.state&&(this.state.includeNetwork=!this.state.includeNetwork,this.render())},this.state?.includeNetwork),c=this.createContextButton("🔗 Context",()=>{this.state&&(this.state.includeContext=!this.state.includeContext,this.render())},this.state?.includeContext);i.appendChild(o),i.appendChild(a),i.appendChild(l),i.appendChild(c),e.appendChild(i);const h=en("div");rn(h,{display:"flex",justifyContent:"flex-end",marginTop:"12px"});const u=en("button",{},[this.state?.isSubmitting?"Running...":"Submit (⌘↵)"]);rn(u,{padding:"8px 16px",background:"#3b82f6",border:"none",borderRadius:"6px",color:"white",cursor:"pointer",fontWeight:"500",opacity:!this.state?.agentOnline||this.state?.isSubmitting?"0.5":"1"});const d=tn(u,"click",t);if(this.cleanupFunctions.push(d),h.appendChild(u),e.appendChild(h),this.state?.outputLines.length||this.state?.isSubmitting){const t=en("div");rn(t,{marginTop:"16px",paddingTop:"16px",borderTop:"1px solid #27272a"});const r=this.createLogStream(this.state?.outputLines||[]);t.appendChild(r),e.appendChild(t)}return e}createContextButton(e,t,r){const n=en("button",{},[e]);rn(n,{padding:"4px 8px",background:r?"#3f3f46":"transparent",border:"none",borderRadius:"4px",color:r?"white":"#a1a1aa",cursor:"pointer",fontSize:"12px"});const s=tn(n,"click",t);return this.cleanupFunctions.push(s),n}createContextBadge(e,t,r,n,s,i){const o=en("div");rn(o,{display:"flex",alignItems:"center",gap:"6px",padding:"4px 8px",background:r,border:`1px solid ${n}`,borderRadius:"6px",fontSize:"11px",color:s});const a=en("span",{},[e]),l=en("span",{},[t]),c=en("button",{},["×"]);rn(c,{marginLeft:"4px",background:"none",border:"none",color:s,cursor:"pointer",fontSize:"14px",padding:"0",lineHeight:"1"});const h=tn(c,"click",i);return this.cleanupFunctions.push(h),o.appendChild(a),o.appendChild(l),o.appendChild(c),o}createLogStream(e){const t=en("div",{className:"orquesta-log-stream"});if(rn(t,{maxHeight:"200px",overflowY:"auto",background:"#0a0a0a",border:"1px solid #27272a",borderRadius:"6px",padding:"8px",fontFamily:"monospace",fontSize:"11px"}),this.state?.isSubmitting){const e=en("div");rn(e,{color:"#3b82f6",padding:"4px 0",marginBottom:"4px"}),e.textContent="● Running...",t.appendChild(e)}return[...e].reverse().forEach(e=>{const r=en("div");rn(r,{display:"flex",gap:"8px",padding:"2px 0",color:"stderr"===e.type?"#ef4444":"tool"===e.type?"#3b82f6":"#d4d4d8"});const n=en("span",{},["stderr"===e.type?"✕":"tool"===e.type?"🔧":"›"]);rn(n,{opacity:"0.5",width:"16px",textAlign:"center"});const s=en("span",{},[e.content]);rn(s,{flex:"1",wordBreak:"break-all",whiteSpace:"pre-wrap"}),r.appendChild(n),r.appendChild(s),t.appendChild(r)}),this.elements.logStream=t,t}createTimelineTab(){const e=en("div");if(rn(e,{maxHeight:"400px",overflowY:"auto"}),!this.state?.promptHistory.length){const t=en("div",{},["No prompts yet. Right-click any element to start!"]);return rn(t,{textAlign:"center",padding:"32px",color:"#71717a",fontSize:"14px"}),e.appendChild(t),e}return this.state.promptHistory.forEach(t=>{const r=t.id===this.state?.currentPrompt?.id,n=t.id===this.state?.expandedPromptId,s=en("div");rn(s,{marginBottom:"8px",background:r?"#27272a":"#18181b",border:"1px solid "+(r?"#3b82f6":"#3f3f46"),borderRadius:"8px",transition:"border-color 0.2s"});const i=en("div");rn(i,{display:"flex",alignItems:"flex-start",gap:"10px",padding:"12px",cursor:"pointer"});const o=en("div"),a=t.author?.full_name||"Unknown",l=a[0]?.toUpperCase()||"?";if(t.author?.avatar_url){const e=en("img",{src:t.author.avatar_url});rn(e,{width:"28px",height:"28px",borderRadius:"50%"}),o.appendChild(e)}else rn(o,{width:"28px",height:"28px",borderRadius:"50%",background:"#52525b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:"600",color:"white"}),o.textContent=l;const c=en("div");rn(c,{flex:"1",minWidth:"0"});const h=en("div");rn(h,{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"});const u=en("span",{},[a]);rn(u,{fontSize:"12px",fontWeight:"500",color:"#d4d4d8"});const d=en("span",{},[this.formatDate(t.created_at)]);rn(d,{fontSize:"10px",color:"#71717a"}),h.appendChild(u),h.appendChild(d);const p=en("p",{},[t.content.slice(0,100)+(t.content.length>100?"...":"")]);rn(p,{color:"#e4e4e7",fontSize:"13px",margin:"0 0 8px 0",lineHeight:"1.4"});const m=en("div");if(rn(m,{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"}),t.git_commit_sha){const e=en("span",{},[`🔗 ${t.git_commit_sha.slice(0,7)}`]);rn(e,{padding:"2px 6px",background:"#1e3a5f",border:"1px solid #3b82f6",borderRadius:"4px",fontSize:"10px",color:"#93c5fd",fontFamily:"monospace"}),m.appendChild(e)}if(t.element_context){const e=en("span",{},[`🎯 <${t.element_context.tag}>`]);rn(e,{padding:"2px 6px",background:"rgba(59, 130, 246, 0.2)",border:"1px solid rgba(59, 130, 246, 0.3)",borderRadius:"4px",fontSize:"10px",color:"#60a5fa"}),m.appendChild(e)}if((t.comment_count||0)>0){const e=en("span",{},[`💬 ${t.comment_count}`]);rn(e,{padding:"2px 6px",background:"#27272a",borderRadius:"4px",fontSize:"10px",color:"#a1a1aa"}),m.appendChild(e)}c.appendChild(h),c.appendChild(p),c.appendChild(m);const g=en("div");rn(g,{display:"flex",alignItems:"center",gap:"6px",flexShrink:"0"});const f=en("span");rn(f,{width:"8px",height:"8px",borderRadius:"50%",background:"completed"===t.status?"#22c55e":"failed"===t.status?"#ef4444":"running"===t.status?"#3b82f6":"#71717a"});const b=en("span",{},[t.status]);rn(b,{padding:"2px 8px",background:"completed"===t.status?"#14532d":"failed"===t.status?"#7f1d1d":"running"===t.status?"#1e3a5f":"#27272a",color:"completed"===t.status?"#4ade80":"failed"===t.status?"#f87171":"running"===t.status?"#60a5fa":"#a1a1aa",borderRadius:"9999px",fontSize:"10px",fontWeight:"500"}),g.appendChild(f),g.appendChild(b),i.appendChild(o),i.appendChild(c),i.appendChild(g),s.appendChild(i);const w="completed"===t.status||"failed"===t.status||t.element_context,y=en("div");if(rn(y,{display:w?"flex":"none",alignItems:"center",gap:"8px",padding:"0 12px 10px 50px"}),t.element_context){const e=en("button",{},["👁 Show on page"]);rn(e,{padding:"4px 10px",background:"rgba(124, 58, 237, 0.2)",border:"1px solid rgba(124, 58, 237, 0.4)",borderRadius:"6px",color:"#c4b5fd",fontSize:"11px",cursor:"pointer"});const r=tn(e,"click",e=>{if(e.stopPropagation(),t.element_context){this.client.getElementSelector().highlightSelectedElement(t.element_context.selector);try{const e=document.querySelector(t.element_context.selector);e?.scrollIntoView({behavior:"smooth",block:"center"})}catch{}}});this.cleanupFunctions.push(r),y.appendChild(e)}if("completed"===t.status||"failed"===t.status){const e=en("button",{},[n?"📄 Hide output":"📄 View output"]);rn(e,{padding:"4px 10px",background:n?"#3f3f46":"rgba(63, 63, 70, 0.5)",border:"1px solid rgba(63, 63, 70, 0.5)",borderRadius:"6px",color:n?"white":"#d4d4d8",fontSize:"11px",cursor:"pointer"});const r=tn(e,"click",e=>{e.stopPropagation(),this.state&&(this.state.expandedPromptId=n?null:t.id,this.render())});this.cleanupFunctions.push(r),y.appendChild(e)}if(s.appendChild(y),n){const e=en("div");rn(e,{padding:"0 12px 12px 12px",borderTop:"1px solid #27272a",marginTop:"4px"});const r=en("div");rn(r,{marginTop:"8px",background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"150px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"});const n=this.state?.promptOutputs?.[t.id]||[];if(n.length>0)n.slice(-20).forEach(e=>{const t=en("div",{},[e.content]);rn(t,{color:"stderr"===e.type?"#ef4444":"tool"===e.type?"#3b82f6":"thinking"===e.type?"#71717a":"#d4d4d8",padding:"1px 0",fontStyle:"thinking"===e.type?"italic":"normal"}),r.appendChild(t)});else{const e=en("div",{},["No output recorded for this prompt"]);rn(e,{color:"#71717a",textAlign:"center",padding:"8px"}),r.appendChild(e)}e.appendChild(r),s.appendChild(e)}const v=tn(s,"mouseenter",()=>{r||rn(s,{borderColor:"#52525b"})}),x=tn(s,"mouseleave",()=>{r||rn(s,{borderColor:"#3f3f46"})});this.cleanupFunctions.push(v,x);const _=tn(i,"click",()=>{this.state&&t.element_context&&this.client.getElementSelector().highlightSelectedElement(t.element_context.selector)});this.cleanupFunctions.push(_),e.appendChild(s)}),e}createLogsTab(){const e=en("div"),t=en("div");rn(t,{marginBottom:"16px"});const r=en("div");rn(r,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const n=en("h3",{},["Agent Output"]);if(rn(n,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"}),this.state?.isSubmitting){const e=en("span",{},["Running..."]);rn(e,{fontSize:"11px",color:"#4ade80"}),r.appendChild(n),r.appendChild(e)}else r.appendChild(n);t.appendChild(r);const s=en("div");if(rn(s,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"150px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.outputLines.length)this.state.outputLines.slice(-30).forEach(e=>{const t=en("div",{},[e.content]);rn(t,{color:"stderr"===e.type?"#ef4444":"tool"===e.type?"#3b82f6":"#d4d4d8",padding:"1px 0",wordBreak:"break-all"}),s.appendChild(t)});else{const e=en("div",{},["No agent output yet"]);rn(e,{color:"#71717a",textAlign:"center",padding:"8px"}),s.appendChild(e)}t.appendChild(s),e.appendChild(t);const i=en("div");rn(i,{marginBottom:"16px"});const o=en("div");rn(o,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const a=en("h3",{},["Console Logs"]);rn(a,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"});const l=en("span",{},[`${this.state?.consoleLogs.length||0} entries`]);rn(l,{fontSize:"11px",color:"#71717a"}),o.appendChild(a),o.appendChild(l),i.appendChild(o);const c=en("div");if(rn(c,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"120px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.consoleLogs.length)this.state.consoleLogs.slice(-20).forEach(e=>{const t=en("div");rn(t,{color:"error"===e.level?"#ef4444":"warn"===e.level?"#eab308":"#d4d4d8",padding:"1px 0"}),t.textContent=`[${e.level}] ${e.message}`,c.appendChild(t)});else{const e=en("div",{},["No console logs captured"]);rn(e,{color:"#71717a",textAlign:"center",padding:"8px"}),c.appendChild(e)}i.appendChild(c),e.appendChild(i);const h=en("div"),u=en("div");rn(u,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const d=en("h3",{},["Network Requests"]);rn(d,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"});const p=en("span",{},[`${this.state?.networkLogs.length||0} requests`]);rn(p,{fontSize:"11px",color:"#71717a"}),u.appendChild(d),u.appendChild(p),h.appendChild(u);const m=en("div");if(rn(m,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"120px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.networkLogs.length)this.state.networkLogs.slice(-15).forEach(e=>{const t=en("div");rn(t,{display:"flex",gap:"8px",padding:"2px 0"});const r=en("span",{},[String(e.status||"...")]);rn(r,{color:e.status&&e.status>=400?"#ef4444":e.status&&e.status>=300?"#eab308":"#4ade80"});const n=en("span",{},[e.method]);rn(n,{color:"#a1a1aa"});const s=en("span",{},[e.url]);if(rn(s,{color:"#d4d4d8",flex:"1",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),t.appendChild(r),t.appendChild(n),t.appendChild(s),e.duration){const r=en("span",{},[`${e.duration}ms`]);rn(r,{color:"#71717a"}),t.appendChild(r)}m.appendChild(t)});else{const e=en("div",{},["No network requests captured"]);rn(e,{color:"#71717a",textAlign:"center",padding:"8px"}),m.appendChild(e)}return h.appendChild(m),e.appendChild(h),e}renderElementInspector(){const e=en("div",{className:"orquesta-element-inspector"});rn(e,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"});const t=en("div");rn(t,{position:"absolute",top:"16px",left:"50%",transform:"translateX(-50%)",pointerEvents:"auto",display:"flex",alignItems:"center",gap:"12px",padding:"8px 16px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"8px",boxShadow:"0 10px 25px rgba(0,0,0,0.3)"});const r=en("span",{},["Click on any element to select it, or right-click for options"]);rn(r,{fontSize:"13px",color:"#d4d4d8"});const n=en("button",{},["Cancel (Esc)"]);rn(n,{padding:"4px 12px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",fontSize:"13px"});const s=tn(n,"click",()=>{this.client.getElementSelector().deactivate()});this.cleanupFunctions.push(s),t.appendChild(r),t.appendChild(n),e.appendChild(t),this.elements.container.appendChild(e)}renderStatusBar(){if(!this.state)return;let e="idle";this.state.isConnected?this.state.agentOnline?this.state.isSubmitting||"running"===this.state.currentPrompt?.status?e="running":"completed"===this.state.currentPrompt?.status?e="completed":"failed"===this.state.currentPrompt?.status&&(e="failed"):e="offline":e="connecting";const t=(()=>{switch(e){case"connecting":return{bg:"#27272a",border:"#3f3f46",icon:"⟳",iconBg:"#3f3f46",text:"Connecting to Orquesta...",pulse:!0};case"offline":return{bg:"#27272a",border:"#ef4444",icon:"○",iconBg:"#7f1d1d",text:"Agent offline",pulse:!1};case"running":return{bg:"#172554",border:"#3b82f6",icon:"⟳",iconBg:"#1d4ed8",text:`Running: ${this.state?.currentPrompt?.content.slice(0,50)}${(this.state?.currentPrompt?.content.length||0)>50?"...":""}`,pulse:!0};case"completed":return{bg:"#14532d",border:"#22c55e",icon:"✓",iconBg:"#15803d",text:"Completed"+(this.state?.currentPrompt?.git_commit_sha?` • Commit ${this.state.currentPrompt.git_commit_sha.slice(0,7)}`:""),pulse:!1};case"failed":return{bg:"#450a0a",border:"#ef4444",icon:"✕",iconBg:"#b91c1c",text:"Prompt failed",pulse:!1};default:return{bg:"#18181b",border:"#3f3f46",icon:"⬡",iconBg:"#27272a",text:this.state?.projectName?`${this.state.projectName} • Ready`:"Orquesta Ready",pulse:!1}}})();if(this.statusBarMinimized){const r=en("div",{id:"orquesta-status-bar-minimized"});rn(r,{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483646",display:"flex",alignItems:"center",gap:"6px",padding:"6px 12px",backgroundColor:t.bg,border:`1px solid ${t.border}`,borderRadius:"20px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",cursor:"pointer",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const n=en("span");rn(n,{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"completed"===e?"#22c55e":"failed"===e?"#ef4444":"running"===e?"#3b82f6":"#71717a"});const s=en("span",{},["Orquesta"]);rn(s,{fontSize:"11px",color:"#d4d4d8",fontWeight:"500"}),r.appendChild(n),r.appendChild(s);const i=tn(r,"click",()=>{this.statusBarMinimized=!1,this.render()});return this.cleanupFunctions.push(i),this.elements.container.appendChild(r),void(this.elements.statusBarMinimized=r)}const r=en("div",{id:"orquesta-status-bar"});rn(r,{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483646",display:"flex",alignItems:"center",gap:"10px",padding:"8px 12px 8px 10px",backgroundColor:t.bg,border:`1px solid ${t.border}`,borderRadius:"10px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',maxWidth:"calc(100vw - 40px)"});const n=en("div");rn(n,{width:"28px",height:"28px",borderRadius:"6px",backgroundColor:t.iconBg,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:"0"});const s=en("span",{},[t.icon]);rn(s,{fontSize:"14px",color:"#ffffff"}),n.appendChild(s);const i=en("div");rn(i,{flex:"1",minWidth:"0"});const o=en("div",{},[t.text]);if(rn(o,{fontSize:"12px",fontWeight:"500",color:"#ffffff",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"400px"}),i.appendChild(o),"running"===e){const e=en("div");rn(e,{marginTop:"4px",height:"3px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"2px",overflow:"hidden"});const t=en("div");rn(t,{height:"100%",backgroundColor:"#3b82f6",borderRadius:"2px",width:"30%",animation:"orquesta-progress 2s ease-in-out infinite"}),e.appendChild(t),i.appendChild(e)}const a=en("button",{},["−"]);rn(a,{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",fontSize:"16px",flexShrink:"0"});const l=tn(a,"click",()=>{this.statusBarMinimized=!0,this.render()});this.cleanupFunctions.push(l);const c=en("button",{},["×"]);rn(c,{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",fontSize:"16px",flexShrink:"0"});const h=tn(c,"click",()=>{this.showStatusBar=!1,this.render()});this.cleanupFunctions.push(h),r.appendChild(n),r.appendChild(i),r.appendChild(a),r.appendChild(c);const u=en("style");u.textContent="\n @keyframes orquesta-progress {\n 0% { width: 0%; margin-left: 0%; }\n 50% { width: 40%; margin-left: 30%; }\n 100% { width: 0%; margin-left: 100%; }\n }\n ",r.appendChild(u),this.elements.container.appendChild(r),this.elements.statusBar=r,"completed"!==e&&"failed"!==e||setTimeout(()=>{this.showStatusBar&&!this.statusBarMinimized&&(this.statusBarMinimized=!0,this.render())},5e3)}renderContextMenu(){if(!this.contextMenuState.isOpen||!this.contextMenuState.element)return;const e=en("div",{className:"orquesta-context-menu"});rn(e,{position:"fixed",zIndex:"2147483648",left:`${this.contextMenuState.position.x}px`,top:`${this.contextMenuState.position.y}px`,width:"320px",backgroundColor:"#18181b",border:"1px solid #3f3f46",borderRadius:"12px",boxShadow:"0 25px 50px rgba(0, 0, 0, 0.5)",overflow:"hidden",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const t=en("div");rn(t,{padding:"12px",borderBottom:"1px solid #27272a",backgroundColor:"#27272a"});const r=en("div");rn(r,{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"});const n=en("span",{},["🎯"]),s=en("span",{},["Prompt about element"]);rn(s,{fontWeight:"600",color:"white",fontSize:"14px"}),r.appendChild(n),r.appendChild(s);const i=en("div");rn(i,{display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#3f3f46",borderRadius:"4px",fontSize:"11px",fontFamily:"ui-monospace, monospace",color:"#a1a1aa"});const o=en("span",{},[`<${this.contextMenuState.element.tag}>`]);if(rn(o,{color:"#60a5fa"}),i.appendChild(o),this.contextMenuState.element.className){const e=en("span",{},[`.${this.contextMenuState.element.className.split(" ")[0]}`]);rn(e,{color:"#4ade80"}),i.appendChild(e)}t.appendChild(r),t.appendChild(i);const a=en("div");rn(a,{padding:"12px"});const l=en("textarea",{placeholder:"What would you like to do with this element?"});rn(l,{width:"100%",minHeight:"80px",padding:"10px 12px",backgroundColor:"#27272a",border:"1px solid #3f3f46",borderRadius:"8px",color:"white",fontSize:"14px",resize:"none",outline:"none",marginBottom:"12px"});const c=en("div");rn(c,{display:"flex",gap:"8px",marginBottom:"12px"});const h=(e,t,r)=>{const n=en("button",{},[e]);rn(n,{flex:"1",padding:"6px 10px",backgroundColor:t?"#3f3f46":"transparent",border:"1px solid #3f3f46",borderRadius:"6px",color:t?"white":"#a1a1aa",fontSize:"12px",cursor:"pointer"});const s=tn(n,"click",r);return this.cleanupFunctions.push(s),n},u=h("📋 Logs "+(this.state?.includeConsole?"✓":""),this.state?.includeConsole||!1,()=>{this.state&&(this.state.includeConsole=!this.state.includeConsole,this.render())}),d=h("🌐 Network "+(this.state?.includeNetwork?"✓":""),this.state?.includeNetwork||!1,()=>{this.state&&(this.state.includeNetwork=!this.state.includeNetwork,this.render())});c.appendChild(u),c.appendChild(d);const p=en("div");rn(p,{display:"flex",gap:"8px"});const m=en("button",{},["Open Panel"]);rn(m,{flex:"1",padding:"8px 12px",backgroundColor:"#27272a",border:"1px solid #3f3f46",borderRadius:"6px",color:"#d4d4d8",fontSize:"13px",fontWeight:"500",cursor:"pointer"});const g=tn(m,"click",()=>{this.state&&this.contextMenuState.element&&(this.state.selectedElement=this.contextMenuState.element,this.state.isOpen=!0,this.state.activeTab="prompts"),this.closeContextMenu(),this.isMinimized=!1,this.client.open()});this.cleanupFunctions.push(g);const f=en("button",{},["Submit"]);rn(f,{flex:"1",padding:"8px 12px",backgroundColor:this.state?.agentOnline?"#3b82f6":"#3f3f46",border:"none",borderRadius:"6px",color:"white",fontSize:"13px",fontWeight:"500",cursor:this.state?.agentOnline?"pointer":"not-allowed",opacity:this.state?.agentOnline?"1":"0.5"});const b=tn(f,"click",async()=>{const e=l.value.trim();if(e&&this.state?.agentOnline&&this.contextMenuState.element)try{await this.client.submitPrompt(e,{elementContext:this.contextMenuState.element}),this.closeContextMenu(),this.isMinimized=!1,this.client.open()}catch(e){console.error("Failed to submit:",e)}});this.cleanupFunctions.push(b),p.appendChild(m),p.appendChild(f),a.appendChild(l),a.appendChild(c),a.appendChild(p),e.appendChild(t),e.appendChild(a);const w=tn(document,"click",t=>{e&&!e.contains(t.target)&&this.closeContextMenu()});this.cleanupFunctions.push(w);const y=tn(document,"keydown",e=>{"Escape"===e.key&&this.closeContextMenu()});this.cleanupFunctions.push(y),this.elements.container.appendChild(e),this.elements.contextMenu=e,setTimeout(()=>l.focus(),50)}closeContextMenu(){this.contextMenuState={isOpen:!1,position:{x:0,y:0},element:null},this.client.getElementSelector().removeSelectedHighlight(),this.render()}renderElementMarkers(){if(!this.state||"all"!==this.state.overlayMode)return;const e=en("div",{className:"orquesta-element-markers"});rn(e,{position:"fixed",inset:"0",zIndex:"2147483644",pointerEvents:"none"}),this.state.elementMarkers.forEach(t=>{if(!t.rect)return;const r=en("div");rn(r,{position:"fixed",left:`${t.rect.left}px`,top:`${t.rect.top}px`,width:`${t.rect.width}px`,height:`${t.rect.height}px`,border:"2px solid #7c3aed",borderRadius:"4px",backgroundColor:"rgba(124, 58, 237, 0.1)",pointerEvents:"auto",cursor:"pointer"});const n=en("div");rn(n,{position:"absolute",top:"-8px",right:"-8px",width:"20px",height:"20px",borderRadius:"50%",backgroundColor:"#7c3aed",color:"white",fontSize:"11px",fontWeight:"600",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'}),n.textContent="1",r.appendChild(n);const s=tn(r,"click",()=>{this.state&&(this.state.activeTab="timeline",this.state.expandedPromptId=t.promptId,this.client.open()),this.render()});this.cleanupFunctions.push(s);const i=en("div");rn(i,{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"8px",padding:"8px 12px",backgroundColor:"#18181b",border:"1px solid #3f3f46",borderRadius:"6px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",maxWidth:"250px",display:"none",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const o=en("div",{},[t.content.slice(0,80)+(t.content.length>80?"...":"")]);if(rn(o,{fontSize:"12px",color:"#d4d4d8"}),i.appendChild(o),t.author){const e=en("div",{},[`by ${t.author.full_name}`]);rn(e,{fontSize:"11px",color:"#71717a",marginTop:"4px"}),i.appendChild(e)}r.appendChild(i);const a=tn(r,"mouseenter",()=>{rn(i,{display:"block"})}),l=tn(r,"mouseleave",()=>{rn(i,{display:"none"})});this.cleanupFunctions.push(a,l),e.appendChild(r)}),this.elements.container.appendChild(e),this.elements.elementMarkers=e}renderError(e){const t=en("div",{className:"orquesta-embed-error"});rn(t,{position:"fixed",bottom:"16px",right:"16px",zIndex:"2147483647",padding:"16px",background:"#7f1d1d",border:"1px solid #991b1b",borderRadius:"8px",maxWidth:"300px"});const r=en("div",{},["Orquesta Error"]);rn(r,{fontWeight:"600",color:"white",marginBottom:"4px"});const n=en("div",{},[e]);rn(n,{color:"#fecaca",fontSize:"13px"}),t.appendChild(r),t.appendChild(n),this.elements.container.appendChild(t)}formatDate(e){const t=new Date(e),r=(new Date).getTime()-t.getTime(),n=Math.floor(r/6e4);return n<1?"Just now":n<60?`${n}m ago`:n<1440?`${Math.floor(n/60)}h ago`:`${Math.floor(n/1440)}d ago`}open(){this.isMinimized=!1,this.client.open()}close(){this.client.close()}toggle(){this.client.toggle()}startElementSelection(){this.client.startElementSelection()}async submitPrompt(e,t){return this.client.submitPrompt(e,t)}renderBuilder(){if(!this.state)return;this.builderRoot||this.createBuilderDOM();const e=this.builderRoot?.querySelector(".orquesta-builder-status-dot");e&&(e.style.background=this.state.agentOnline?"#22c55e":"#ef4444");const t=this.builderRoot?.querySelector(".orquesta-builder-status-text");if(t&&(t.textContent=this.state.agentOnline?"Agent online":"Agent offline"),this.state.currentPrompt){const e=this.state.currentPrompt;"running"!==e.status||this.builderMessages.some(t=>t.content===`Running: ${e.content.slice(0,80)}`)||this.builderMessages.push({role:"status",content:`Running: ${e.content.slice(0,80)}${e.content.length>80?"...":""}`}),"completed"!==e.status||this.builderMessages.some(e=>e.content.startsWith("Completed"))||(this.builderMessages.push({role:"status",content:"Completed successfully"}),this.builderPreviewFrame&&(this.builderPreviewFrame.src=this.builderPreviewFrame.src)),"failed"!==e.status||this.builderMessages.some(e=>e.content.startsWith("Failed"))||this.builderMessages.push({role:"status",content:"Failed — check terminal for details"})}this.updateBuilderMessages(),this.updateBuilderTerminal();const r=this.builderRoot?.querySelector(".orquesta-builder-submit");r&&(r.disabled=this.state.isSubmitting||!this.state.agentOnline)}createBuilderDOM(){this.config.container&&("string"==typeof this.config.container?document.querySelector(this.config.container)||document.body:this.config.container);const e=this.config.previewUrl||window.location.href,t=this.state?.projectName||"Project",r=en("div",{className:"orquesta-builder orquesta-embed-panel"}),n=en("div",{className:"orquesta-builder-header"}),s=en("div",{className:"orquesta-builder-header-left"});s.innerHTML=`\n <span class="orquesta-builder-logo">⬡ Orquesta</span>\n <span class="orquesta-builder-project">${this.escapeHtml(t)}</span>\n `;const i=en("div",{className:"orquesta-builder-header-right"});i.innerHTML=`\n <div class="orquesta-builder-status">\n <span class="orquesta-builder-status-dot" style="background:${this.state?.agentOnline?"#22c55e":"#ef4444"}"></span>\n <span class="orquesta-builder-status-text">${this.state?.agentOnline?"Agent online":"Agent offline"}</span>\n </div>\n `;const o=en("button");o.textContent="⊡",o.title="Collapse to widget mode",rn(o,{padding:"4px 8px",background:"transparent",border:"1px solid #3f3f46",borderRadius:"4px",color:"#a1a1aa",cursor:"pointer",fontSize:"14px",marginLeft:"8px"}),this.cleanupFunctions.push(tn(o,"click",()=>{this.switchMode("widget")})),this.cleanupFunctions.push(tn(o,"mouseenter",()=>{rn(o,{background:"#3f3f46",color:"white"})})),this.cleanupFunctions.push(tn(o,"mouseleave",()=>{rn(o,{background:"transparent",color:"#a1a1aa"})})),i.appendChild(o),n.appendChild(s),n.appendChild(i),r.appendChild(n);const a=en("div",{className:"orquesta-builder-main"}),l=en("div",{className:"orquesta-builder-chat"}),c=en("div",{className:"orquesta-builder-chat-messages"});c.innerHTML='\n <div class="orquesta-builder-msg orquesta-builder-msg-system">\n What would you like to build? Describe the feature or change and I\'ll implement it.\n </div>\n ',this.builderMsgContainer=c,l.appendChild(c);const h=en("div",{className:"orquesta-builder-chat-input"}),u=en("textarea",{placeholder:"Describe what you want to build..."});u.setAttribute("rows","3");const d=en("div",{className:"orquesta-builder-chat-input-actions"}),p=en("span");rn(p,{fontSize:"11px",color:"#71717a"}),p.textContent="Enter to send, Shift+Enter for newline";const m=en("button",{className:"orquesta-builder-btn-primary orquesta-builder-submit"});m.textContent="Send",m.disabled=!this.state?.agentOnline,d.appendChild(p),d.appendChild(m),h.appendChild(u),h.appendChild(d),l.appendChild(h);const g=()=>{const e=u.value.trim();e&&!this.state?.isSubmitting&&(u.value="",this.builderMessages.push({role:"user",content:e}),this.updateBuilderMessages(),this.client.submitPrompt(e).catch(e=>{this.builderMessages.push({role:"status",content:`Error: ${e.message}`}),this.updateBuilderMessages()}))};this.cleanupFunctions.push(tn(m,"click",g)),this.cleanupFunctions.push(tn(u,"keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),g())})),a.appendChild(l);const f=en("div",{className:"orquesta-builder-resizer-h"});let b=!1;this.cleanupFunctions.push(tn(f,"mousedown",()=>{b=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none"})),this.cleanupFunctions.push(tn(document,"mousemove",e=>{if(!b)return;const t=Math.max(300,Math.min(e.clientX,.5*window.innerWidth));l.style.width=`${t}px`})),this.cleanupFunctions.push(tn(document,"mouseup",()=>{b&&(b=!1,document.body.style.cursor="",document.body.style.userSelect="")})),a.appendChild(f);const w=en("div",{className:"orquesta-builder-preview"}),y=en("div",{className:"orquesta-builder-preview-bar"}),v=en("div");rn(v,{display:"flex",gap:"6px"}),v.innerHTML='\n <span style="width:12px;height:12px;border-radius:50%;background:#ef4444"></span>\n <span style="width:12px;height:12px;border-radius:50%;background:#eab308"></span>\n <span style="width:12px;height:12px;border-radius:50%;background:#22c55e"></span>\n ',y.appendChild(v);const x=en("div",{className:"orquesta-builder-preview-url"});x.textContent=e,y.appendChild(x);const _=en("button");_.textContent="↻",_.title="Refresh preview",this.cleanupFunctions.push(tn(_,"click",()=>{this.builderPreviewFrame&&(this.builderPreviewFrame.src=this.builderPreviewFrame.src)})),y.appendChild(_),w.appendChild(y);const k=en("iframe",{className:"orquesta-builder-preview-iframe"});k.src=e,k.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),this.builderPreviewFrame=k,w.appendChild(k),a.appendChild(w),r.appendChild(a);const S=en("div",{className:"orquesta-builder-resizer-v"});let C=!1;const E=en("div",{className:"orquesta-builder-terminal"+(this.builderTerminalCollapsed?" collapsed":"")});this.cleanupFunctions.push(tn(S,"mousedown",()=>{C=!0,document.body.style.cursor="row-resize",document.body.style.userSelect="none"})),this.cleanupFunctions.push(tn(document,"mousemove",e=>{if(!C)return;const t=Math.max(100,Math.min(window.innerHeight-e.clientY,.5*window.innerHeight));E.style.height=`${t}px`,this.builderTerminalCollapsed=!1,E.classList.remove("collapsed")})),this.cleanupFunctions.push(tn(document,"mouseup",()=>{C&&(C=!1,document.body.style.cursor="",document.body.style.userSelect="")})),r.appendChild(S);const T=en("div",{className:"orquesta-builder-terminal-header"}),O=en("span",{className:"orquesta-builder-terminal-title"});O.textContent="Terminal";const R=en("button");R.textContent=this.builderTerminalCollapsed?"▲":"▼",R.title="Toggle terminal",this.cleanupFunctions.push(tn(R,"click",()=>{this.builderTerminalCollapsed=!this.builderTerminalCollapsed,E.classList.toggle("collapsed",this.builderTerminalCollapsed),R.textContent=this.builderTerminalCollapsed?"▲":"▼"})),T.appendChild(O),T.appendChild(R),E.appendChild(T);const q=en("div",{className:"orquesta-builder-terminal-output"});this.builderTerminalOutput=q,E.appendChild(q),r.appendChild(E),this.elements.container.innerHTML="",this.elements.container.appendChild(r),this.builderRoot=r,rn(this.elements.container,{position:"fixed",top:"0",left:"0",right:"0",bottom:"0",zIndex:"2147483647"}),u.focus()}updateBuilderMessages(){if(!this.builderMsgContainer)return;const e=this.builderMsgContainer.querySelector(".orquesta-builder-msg-system");this.builderMsgContainer.innerHTML="",e&&this.builderMsgContainer.appendChild(e);for(const e of this.builderMessages){const t=en("div",{className:`orquesta-builder-msg orquesta-builder-msg-${e.role}`});t.textContent=e.content,this.builderMsgContainer.appendChild(t)}this.builderMsgContainer.scrollTop=this.builderMsgContainer.scrollHeight}updateBuilderTerminal(){if(!this.builderTerminalOutput||!this.state)return;const e=this.state.outputLines;if(e.length!==this.builderLastOutputCount){for(let t=this.builderLastOutputCount;t<e.length;t++){const r=e[t],n=en("div");rn(n,{color:this.getTerminalColor(r.type),whiteSpace:"pre-wrap",wordBreak:"break-all"}),n.textContent=r.content,this.builderTerminalOutput.appendChild(n)}this.builderLastOutputCount=e.length,this.builderTerminalOutput.scrollTop=this.builderTerminalOutput.scrollHeight}}getTerminalColor(e){switch(e){case"stderr":case"error":return"#ef4444";case"tool":case"tool_call":return"#3b82f6";case"tool_result":return"#22c55e";case"thinking":return"#71717a";case"system":return"#eab308";case"progress":return"#a78bfa";default:return"#d4d4d8"}}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}switchMode(e){this.currentMode!==e&&(this.currentMode=e,this.elements.container.innerHTML="",this.cleanupFunctions.forEach(e=>e()),this.cleanupFunctions=[],"widget"===e&&(this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,rn(this.elements.container,{position:"",top:"",left:"",right:"",bottom:""}),this.isMinimized=!1,this.client.open()),this.render())}setMode(e){this.switchMode(e)}destroy(){this.unsubscribe?.(),this.cleanupFunctions.forEach(e=>e()),this.globalRightClickCleanup&&(this.globalRightClickCleanup(),this.globalRightClickCleanup=null),this.client.disconnect(),this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,nn(this.elements.container),nn(function(e,t=document){return t.querySelector(e)}("#orquesta-embed-styles"))}showStatus(){this.showStatusBar=!0,this.statusBarMinimized=!1,this.render()}hideStatus(){this.showStatusBar=!1,this.render()}}const on={init(e){const t=new sn(e);return t.init().catch(console.error),t},OrquestaWidget:sn};return"undefined"!=typeof window&&(window.Orquesta=on),e.ConsoleCapture=Wr,e.ElementSelector=Jr,e.NetworkCapture=Kr,e.OrquestaEmbedClient=Zr,e.OrquestaWidget=sn,e.default=on,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
|
|
1
|
+
var Orquesta=function(e){"use strict";function t(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(r[n[s]]=e[n[s]])}return r}function r(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}l((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class n extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class s extends n{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class i extends n{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class o extends n{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var a;!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(a||(a={}));class l{constructor(e,{headers:t={},customFetch:r,region:n=a.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return r(this,arguments,void 0,function*(e,t={}){var r;let n,a;try{const{headers:l,method:c,body:h,signal:u,timeout:d}=t;let p={},{region:m}=t;m||(m=this.region);const g=new URL(`${this.url}/${e}`);let f;m&&"any"!==m&&(p["x-region"]=m,g.searchParams.set("forceFunctionRegion",m)),h&&(l&&!Object.prototype.hasOwnProperty.call(l,"Content-Type")||!l)?"undefined"!=typeof Blob&&h instanceof Blob||h instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",f=h):"string"==typeof h?(p["Content-Type"]="text/plain",f=h):"undefined"!=typeof FormData&&h instanceof FormData?f=h:(p["Content-Type"]="application/json",f=JSON.stringify(h)):f=!h||"string"==typeof h||"undefined"!=typeof Blob&&h instanceof Blob||h instanceof ArrayBuffer||"undefined"!=typeof FormData&&h instanceof FormData?h:JSON.stringify(h);let b=u;d&&(a=new AbortController,n=setTimeout(()=>a.abort(),d),u?(b=a.signal,u.addEventListener("abort",()=>a.abort())):b=a.signal);const w=yield this.fetch(g.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),l),body:f,signal:b}).catch(e=>{throw new s(e)}),y=w.headers.get("x-relay-error");if(y&&"true"===y)throw new i(w);if(!w.ok)throw new o(w);let v,x=(null!==(r=w.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return v="application/json"===x?yield w.json():"application/octet-stream"===x||"application/pdf"===x?yield w.blob():"text/event-stream"===x?w:"multipart/form-data"===x?yield w.formData():yield w.text(),{data:v,error:null,response:w}}catch(e){return{data:null,error:e,response:e instanceof o||e instanceof i?e.context:void 0}}finally{n&&clearTimeout(n)}})}}var c=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},h=class{constructor(e){var t,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var r=this;void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let n=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,n=null,s=null,i=e.status,o=e.statusText;if(e.ok){var a,l;if("HEAD"!==r.method){var h;const t=await e.text();""===t||(n="text/csv"===r.headers.get("Accept")||r.headers.get("Accept")&&(null===(h=r.headers.get("Accept"))||void 0===h?void 0:h.includes("application/vnd.pgrst.plan+text"))?t:JSON.parse(t))}const c=null===(a=r.headers.get("Prefer"))||void 0===a?void 0:a.match(/count=(exact|planned|estimated)/),u=null===(l=e.headers.get("content-range"))||void 0===l?void 0:l.split("/");c&&u&&u.length>1&&(s=parseInt(u[1])),r.isMaybeSingle&&"GET"===r.method&&Array.isArray(n)&&(n.length>1?(t={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,s=null,i=406,o="Not Acceptable"):n=1===n.length?n[0]:null)}else{var u;const s=await e.text();try{t=JSON.parse(s),Array.isArray(t)&&404===e.status&&(n=[],t=null,i=200,o="OK")}catch(r){404===e.status&&""===s?(i=204,o="No Content"):t={message:s}}if(t&&r.isMaybeSingle&&(null==t||null===(u=t.details)||void 0===u?void 0:u.includes("0 rows"))&&(t=null,i=200,o="OK"),t&&r.shouldThrowOnError)throw new c(t)}return{error:t,data:n,count:s,status:i,statusText:o}});return this.shouldThrowOnError||(n=n.catch(e=>{var t;let r="";const n=null==e?void 0:e.cause;if(n){var s,i,o,a;const t=null!==(s=null==n?void 0:n.message)&&void 0!==s?s:"",l=null!==(i=null==n?void 0:n.code)&&void 0!==i?i:"";r=`${null!==(o=null==e?void 0:e.name)&&void 0!==o?o:"FetchError"}: ${null==e?void 0:e.message}`,r+=`\n\nCaused by: ${null!==(a=null==n?void 0:n.name)&&void 0!==a?a:"Error"}: ${t}`,l&&(r+=` (${l})`),(null==n?void 0:n.stack)&&(r+=`\n${n.stack}`)}else{var l;r=null!==(l=null==e?void 0:e.stack)&&void 0!==l?l:""}return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:r,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),n.then(e,t)}returns(){return this}overrideTypes(){return this}},u=class extends h{select(e){let t=!1;const r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:n,referencedTable:s=n}={}){const i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const n=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:n=r}={}){const s=void 0===n?"offset":`${n}.offset`,i=void 0===n?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:n=!1,wal:s=!1,format:i="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,r?"settings":null,n?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=null!==(o=this.headers.get("Accept"))&&void 0!==o?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const d=new RegExp("[,()]");var p=class extends u{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&d.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&d.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:n}={}){let s="";"plain"===n?s="pl":"phrase"===n?s="ph":"websearch"===n&&(s="w");const i=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${s}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},m=class{constructor(e,{headers:t={},schema:r,fetch:n}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:r=!1,count:n}=null!=t?t:{},s=r?"HEAD":"GET";let i=!1;const o=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new p({method:s,url:a,headers:l,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){var n;const{url:s,headers:i}=this.cloneRequestState();if(t&&i.append("Prefer",`count=${t}`),r||i.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);s.searchParams.set("columns",e.join(","))}}return new p({method:"POST",url:s,headers:i,schema:this.schema,body:e,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:n,defaultToNull:s=!0}={}){var i;const{url:o,headers:a}=this.cloneRequestState();if(a.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&o.searchParams.set("on_conflict",t),n&&a.append("Prefer",`count=${n}`),s||a.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);o.searchParams.set("columns",e.join(","))}}return new p({method:"POST",url:o,headers:a,schema:this.schema,body:e,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}update(e,{count:t}={}){var r;const{url:n,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new p({method:"PATCH",url:n,headers:s,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:e}={}){var t;const{url:r,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new p({method:"DELETE",url:r,headers:n,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch})}},g=class e{constructor(e,{headers:t={},schema:r,fetch:n}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=n}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");return new m(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:n=!1,count:s}={}){var i;let o;const a=new URL(`${this.url}/rpc/${e}`);let l;const c=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(c)),h=r&&Object.values(t).some(c);h?(o="POST",l=t):r||n?(o=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{a.searchParams.append(e,t)})):(o="POST",l=t);const u=new Headers(this.headers);return h?u.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&u.set("Prefer",`count=${s}`),new p({method:o,url:a,headers:u,schema:this.schemaName,body:l,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}};class f{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const t=globalThis.process;if(t){const e=t.versions;if(e&&e.node){const t=e.node,r=parseInt(t.replace(/^v/,"").split(".")[0]);return r>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const b="1.0.0",w=b,y=1e4;var v,x,_,k,S,C;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(v||(v={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(x||(x={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(_||(_={})),function(e){e.websocket="websocket"}(k||(k={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(S||(S={}));class E{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const n=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var t,r;const n=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:{},s=(new TextEncoder).encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,s)}_encodeUserBroadcastPush(e,t,r){var n,s;const i=e.topic,o=null!==(n=e.ref)&&void 0!==n?n:"",a=null!==(s=e.join_ref)&&void 0!==s?s:"",l=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=0===Object.keys(c).length?"":JSON.stringify(c);if(a.length>255)throw new Error(`joinRef length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const u=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+o.length+i.length+l.length+h.length,d=new ArrayBuffer(this.HEADER_LENGTH+u);let p=new DataView(d),m=0;p.setUint8(m++,this.KINDS.userBroadcastPush),p.setUint8(m++,a.length),p.setUint8(m++,o.length),p.setUint8(m++,i.length),p.setUint8(m++,l.length),p.setUint8(m++,h.length),p.setUint8(m++,t),Array.from(a,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(o,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(i,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(l,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(h,e=>p.setUint8(m++,e.charCodeAt(0)));var g=new Uint8Array(d.byteLength+r.byteLength);return g.set(new Uint8Array(d),0),g.set(new Uint8Array(r),d.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e)){return t(this._binaryDecode(e))}if("string"==typeof e){const r=JSON.parse(e),[n,s,i,o,a]=r;return t({join_ref:n,ref:s,topic:i,event:o,payload:a})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),n=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,n)}_decodeUserBroadcast(e,t,r){const n=t.getUint8(1),s=t.getUint8(2),i=t.getUint8(3),o=t.getUint8(4);let a=this.HEADER_LENGTH+4;const l=r.decode(e.slice(a,a+n));a+=n;const c=r.decode(e.slice(a,a+s));a+=s;const h=r.decode(e.slice(a,a+i));a+=i;const u=e.slice(a,e.byteLength),d=o===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:c,payload:d};return i>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}class T{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(C||(C={}));const O=(e,t,r={})=>{var n;const s=null!==(n=r.skipTypes)&&void 0!==n?n:[];return t?Object.keys(t).reduce((r,n)=>(r[n]=R(n,e,t,s),r),{}):{}},R=(e,t,r,n)=>{const s=t.find(t=>t.name===e),i=null==s?void 0:s.type,o=r[e];return i&&!n.includes(i)?q(i,o):A(o)},q=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return P(t,r)}switch(e){case C.bool:return $(t);case C.float4:case C.float8:case C.int2:case C.int4:case C.int8:case C.numeric:case C.oid:return I(t);case C.json:case C.jsonb:return j(t);case C.timestamp:return N(t);case C.abstime:case C.date:case C.daterange:case C.int4range:case C.int8range:case C.money:case C.reltime:case C.text:case C.time:case C.timestamptz:case C.timetz:case C.tsrange:case C.tstzrange:default:return A(t)}},A=e=>e,$=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},I=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},j=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}return e},P=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,n=e[r];if("{"===e[0]&&"}"===n){let n;const s=e.slice(1,r);try{n=JSON.parse("["+s+"]")}catch(e){n=s?s.split(","):[]}return n.map(e=>q(t,e))}return e},N=e=>"string"==typeof e?e.replace(" ","T"):e,U=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class L{constructor(e,t,r={},n=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null===(r=this.receivedResp)||void 0===r?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var B,M,z,D;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(B||(B={}));class H{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{const{onJoin:t,onLeave:r,onSync:n}=this.caller;this.joinRef=this.channel._joinRef(),this.state=H.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=H.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],n()}),this.channel._on(r.diff,{},e=>{const{onJoin:t,onLeave:r,onSync:n}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=H.syncDiff(this.state,e,t,r),n())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,n){const s=this.cloneDeep(e),i=this.transformState(t),o={},a={};return this.map(s,(e,t)=>{i[e]||(a[e]=t)}),this.map(i,(e,t)=>{const r=s[e];if(r){const n=t.map(e=>e.presence_ref),s=r.map(e=>e.presence_ref),i=t.filter(e=>s.indexOf(e.presence_ref)<0),l=r.filter(e=>n.indexOf(e.presence_ref)<0);i.length>0&&(o[e]=i),l.length>0&&(a[e]=l)}else o[e]=t}),this.syncDiff(s,{joins:o,leaves:a},r,n)}static syncDiff(e,t,r,n){const{joins:s,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),n||(n=()=>{}),this.map(s,(t,n)=>{var s;const i=null!==(s=e[t])&&void 0!==s?s:[];if(e[t]=this.cloneDeep(n),i.length>0){const r=e[t].map(e=>e.presence_ref),n=i.filter(e=>r.indexOf(e.presence_ref)<0);e[t].unshift(...n)}r(t,i,n)}),this.map(i,(t,r)=>{let s=e[t];if(!s)return;const i=r.map(e=>e.presence_ref);s=s.filter(e=>i.indexOf(e.presence_ref)<0),e[t]=s,n(t,s,r),0===s.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const n=e[r];return t[r]="metas"in n?n.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):n,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(M||(M={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(z||(z={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(D||(D={}));class F{constructor(e,t={config:{}},r){var n,s;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=x.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new L(this,_.join,this.params,this.timeout),this.rejoinTimer=new T(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=x.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=x.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this._on(_.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new H(this),this.broadcastEndpointURL=U(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(s=null===(n=this.params.config)||void 0===n?void 0:n.broadcast)||void 0===s?void 0:s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,n,s;if(this.socket.isConnected()||this.socket.connect(),this.state==x.closed){const{config:{broadcast:i,presence:o,private:a}}=this.params,l=null!==(n=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==n?n:[],c=!!this.bindings[z.PRESENCE]&&this.bindings[z.PRESENCE].length>0||!0===(null===(s=this.params.config.presence)||void 0===s?void 0:s.enabled),h={},u={broadcast:i,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:l,private:a};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(D.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(D.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var r;if(this.socket._isManualToken()||this.socket.setAuth(),void 0!==t){const n=this.bindings.postgres_changes,s=null!==(r=null==n?void 0:n.length)&&void 0!==r?r:0,i=[];for(let r=0;r<s;r++){const s=n[r],{filter:{event:o,schema:a,table:l,filter:c}}=s,h=t&&t[r];if(!(h&&h.event===o&&F.isFilterValueEqual(h.schema,a)&&F.isFilterValueEqual(h.table,l)&&F.isFilterValueEqual(h.filter,c)))return this.unsubscribe(),this.state=x.errored,void(null==e||e(D.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));i.push(Object.assign(Object.assign({},s),{id:h.id}))}return this.bindings.postgres_changes=i,void(e&&e(D.SUBSCRIBED))}null==e||e(D.SUBSCRIBED)}).receive("error",t=>{this.state=x.errored,null==e||e(D.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(D.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===x.joined&&e===z.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var n;if(null==t)return Promise.reject("Payload is required for httpSend()");const s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);const i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!==(n=r.timeout)&&void 0!==n?n:this.timeout);if(202===o.status)return{success:!0};let a=o.statusText;try{const e=await o.json();a=e.error||e.message||a}catch(e){}return Promise.reject(new Error(a))}async send(e,t={}){var r,n;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var n,s,i;const o=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(i=null===(s=null===(n=this.params)||void 0===n?void 0:n.config)||void 0===s?void 0:s.broadcast)||void 0===i?void 0:i.ack)||r("ok"),o.receive("ok",()=>r("ok")),o.receive("error",()=>r("error")),o.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:s,payload:i}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:i,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);return await(null===(n=e.body)||void 0===n?void 0:n.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=x.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(_.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(n=>{r=new L(this,_.leave,{},e),r.receive("ok",()=>{t(),n("ok")}).receive("timeout",()=>{t(),n("timed out")}).receive("error",()=>{n("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{null==r||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=x.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const n=new AbortController,s=setTimeout(()=>n.abort(),r),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(s),i}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new L(this,e,t,r);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var n,s;const i=e.toLocaleLowerCase(),{close:o,error:a,leave:l,join:c}=_;if(r&&[o,a,l,c].indexOf(i)>=0&&r!==this._joinRef())return;let h=this._onMessage(i,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?null===(n=this.bindings.postgres_changes)||void 0===n||n.filter(e=>{var t,r,n;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(n=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===n?void 0:n.toLocaleLowerCase())===i}).map(e=>e.callback(h,r)):null===(s=this.bindings[i])||void 0===s||s.filter(e=>{var r,n,s,o,a,l,c,h;if(["broadcast","presence","postgres_changes"].includes(i)){if("id"in e){const i=e.id,l=null===(r=e.filter)||void 0===r?void 0:r.event;return i&&(null===(n=t.ids)||void 0===n?void 0:n.includes(i))&&("*"===l||(null==l?void 0:l.toLocaleLowerCase())===(null===(s=t.data)||void 0===s?void 0:s.type.toLocaleLowerCase()))&&(!(null===(o=e.filter)||void 0===o?void 0:o.table)||e.filter.table===(null===(a=t.data)||void 0===a?void 0:a.table))}{const r=null===(c=null===(l=null==e?void 0:e.filter)||void 0===l?void 0:l.event)||void 0===c?void 0:c.toLocaleLowerCase();return"*"===r||r===(null===(h=null==t?void 0:t.event)||void 0===h?void 0:h.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===i}).map(e=>{if("object"==typeof h&&"ids"in h){const e=h.data,{schema:t,table:r,commit_timestamp:n,type:s,errors:i}=e,o={schema:t,table:r,commit_timestamp:n,eventType:s,new:{},old:{},errors:i};h=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===x.closed}_isJoined(){return this.state===x.joined}_isJoining(){return this.state===x.joining}_isLeaving(){return this.state===x.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const n=e.toLocaleLowerCase(),s={type:n,filter:t,callback:r};return this.bindings[n]?this.bindings[n].push(s):this.bindings[n]=[s],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(e=>{var n;return!((null===(n=e.type)||void 0===n?void 0:n.toLocaleLowerCase())===r&&F.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(_.close,{},e)}_onError(e){this._on(_.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=x.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=O(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=O(e.columns,e.old_record)),t}}const W=()=>{},K=25e3,J=10,G=100,V=[1e3,2e3,5e3,1e4];class X{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=y,this.transport=null,this.heartbeatIntervalMs=K,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=W,this.ref=0,this.reconnectTimer=null,this.vsn=w,this.logger=W,this.conn=null,this.sendBuffer=[],this.serializer=new E,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${k.websocket}`,this.httpEndpoint=U(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=f.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case v.connecting:return S.Connecting;case v.open:return S.Open;case v.closing:return S.Closing;default:return S.Closed}}isConnected(){return this.connectionState()===S.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const r=`realtime:${e}`,n=this.getChannels().find(e=>e.topic===r);if(n)return n;{const r=new F(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){const{topic:t,event:r,payload:n,ref:s}=e,i=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${r} (${s})`,n),this.isConnected()?i():this.sendBuffer.push(i)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},G)}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event&&e.ref&&e.ref===this.pendingHeartbeatRef){const t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error",t)}catch(e){this.log("error","error in heartbeat callback",e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:t,event:r,payload:n,ref:s}=e,i=s?`(${s})`:"",o=n.status||"";this.log("receive",`${o} ${t} ${r} ${i}`.trim(),n),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,n,s)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===v.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===v.open||this.conn.readyState===v.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`);(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(_.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const r={access_token:t,version:"realtime-js/2.90.1"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push(_.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new T(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},J)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,n,s,i,o,a,l,c,h,u,d;switch(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(r=null==e?void 0:e.timeout)&&void 0!==r?r:y,this.heartbeatIntervalMs=null!==(n=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==n?n:K,this.worker=null!==(s=null==e?void 0:e.worker)&&void 0!==s&&s,this.accessToken=null!==(i=null==e?void 0:e.accessToken)&&void 0!==i?i:null,this.heartbeatCallback=null!==(o=null==e?void 0:e.heartbeatCallback)&&void 0!==o?o:W,this.vsn=null!==(a=null==e?void 0:e.vsn)&&void 0!==a?a:w,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(l=null==e?void 0:e.reconnectAfterMs)&&void 0!==l?l:e=>V[e-1]||1e4,this.vsn){case b:this.encode=null!==(c=null==e?void 0:e.encode)&&void 0!==c?c:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(h=null==e?void 0:e.decode)&&void 0!==h?h:(e,t)=>t(JSON.parse(e));break;case"2.0.0":this.encode=null!==(u=null==e?void 0:e.encode)&&void 0!==u?u:this.serializer.encode.bind(this.serializer),this.decode=null!==(d=null==e?void 0:e.decode)&&void 0!==d?d:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}var Y=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function Q(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:s,body:i,headers:o}){const a=function(e,t,r){const n=new URL(t,e);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&n.searchParams.set(e,t);return n.toString()}(e.baseUrl,n,s),l=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),c=await t(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),h=await c.text(),u=(c.headers.get("content-type")||"").includes("application/json"),d=u&&h?JSON.parse(h):h;if(!c.ok){const e=u?d:void 0,t=e?.error;throw new Y(t?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:c.status,headers:c.headers,data:d}}}}function Z(e){return e.join("")}var ee=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:Z(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){const r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Z(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Z(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Z(e.namespace)}`}),!0}catch(e){if(e instanceof Y&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof Y&&409===e.status)return;throw e}}};function te(e){return e.join("")}var re=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const r={};this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${te(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof Y&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof Y&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},ne=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Q({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new ee(this.client,t),this.tableOps=new re(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},se=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function ie(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var oe=class extends se{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},ae=class extends se{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};const le=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),ce=e=>{if(Array.isArray(e))return e.map(e=>ce(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,r])=>{const n=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[n]=ce(r)}),t};function he(e){return(he="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ue(e){var t=function(e,t){if("object"!=he(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=he(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==he(t)?t:t+""}function de(e,t,r){return(t=ue(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function pe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function me(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?pe(Object(r),!0).forEach(function(t){de(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):pe(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const ge=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null===(t=e.error)||void 0===t?void 0:t.message)||JSON.stringify(e)},fe=async(e,t,r)=>{e instanceof await Response&&!(null==r?void 0:r.noResolveJson)?e.json().then(r=>{const n=e.status||500,s=(null==r?void 0:r.statusCode)||n+"";t(new oe(ge(r),n,s))}).catch(e=>{t(new ae(ge(e),e))}):t(new ae(ge(e),e))},be=(e,t,r,n)=>{const s={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&n?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(n)?(s.headers=me({"Content-Type":"application/json"},null==t?void 0:t.headers),s.body=JSON.stringify(n)):s.body=n,(null==t?void 0:t.duplex)&&(s.duplex=t.duplex),me(me({},s),r)):s};async function we(e,t,r,n,s,i){return new Promise((o,a)=>{e(r,be(t,n,s,i)).then(e=>{if(!e.ok)throw e;return(null==n?void 0:n.noResolveJson)?e:e.json()}).then(e=>o(e)).catch(e=>fe(e,a,n))})}async function ye(e,t,r,n){return we(e,"GET",t,r,n)}async function ve(e,t,r,n,s){return we(e,"POST",t,n,s,r)}async function xe(e,t,r,n,s){return we(e,"PUT",t,n,s,r)}async function _e(e,t,r,n,s){return we(e,"DELETE",t,n,s,r)}var ke=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}};let Se;Se=Symbol.toStringTag;var Ce=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Se]="BlobDownloadBuilder",this.promise=null}asStream(){return new ke(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await(await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}};const Ee={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Te={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Oe=class{constructor(e,t={},r,n){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=le(n)}throwOnError(){return this.shouldThrowOnError=!0,this}async uploadOrUpdate(e,t,r,n){var s=this;try{let i;const o=me(me({},Te),n);let a=me(me({},s.headers),"POST"===e&&{"x-upsert":String(o.upsert)});const l=o.metadata;"undefined"!=typeof Blob&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=s.toBase64(s.encodeMetadata(l))),("undefined"!=typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!o.duplex&&(o.duplex="half")),(null==n?void 0:n.headers)&&(a=me(me({},a),n.headers));const c=s._removeEmptyFolders(t),h=s._getFinalPath(c),u=await("PUT"==e?xe:ve)(s.fetch,`${s.url}/object/${h}`,i,me({headers:a},(null==o?void 0:o.duplex)?{duplex:o.duplex}:{}));return{data:{path:c,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,n){var s=this;const i=s._removeEmptyFolders(e),o=s._getFinalPath(i),a=new URL(s.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let e;const t=me({upsert:Te.upsert},n),o=me(me({},s.headers),{"x-upsert":String(t.upsert)});return"undefined"!=typeof Blob&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r,e.append("cacheControl",t.cacheControl)):(e=r,o["cache-control"]=`max-age=${t.cacheControl}`,o["content-type"]=t.contentType),{data:{path:i,fullPath:(await xe(s.fetch,a.toString(),e,{headers:o})).Key},error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createSignedUploadUrl(e,t){var r=this;try{let n=r._getFinalPath(e);const s=me({},r.headers);(null==t?void 0:t.upsert)&&(s["x-upsert"]="true");const i=await ve(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:s}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new se("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var n=this;try{return{data:await ve(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:n.headers}),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async copy(e,t,r){var n=this;try{return{data:{path:(await ve(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:n.headers})).Key},error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createSignedUrl(e,t,r){var n=this;try{let s=n._getFinalPath(e),i=await ve(n.fetch,`${n.url}/object/sign/${s}`,me({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:n.headers});const o=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return i={signedUrl:encodeURI(`${n.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createSignedUrls(e,t,r){var n=this;try{const s=await ve(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:t,paths:e},{headers:n.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:s.map(e=>me(me({},e),{},{signedUrl:e.signedURL?encodeURI(`${n.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}download(e,t){const r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",n=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),s=n?`?${n}`:"",i=this._getFinalPath(e);return new Ce(()=>ye(this.fetch,`${this.url}/${r}/${i}${s}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}async info(e){var t=this;const r=t._getFinalPath(e);try{return{data:ce(await ye(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async exists(e){var t=this;const r=t._getFinalPath(e);try{return await async function(e,t,r,n){return we(e,"HEAD",t,me(me({},r),{},{noResolveJson:!0}),n)}(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e)&&e instanceof ae){const t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){const r=this._getFinalPath(e),n=[],s=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==s&&n.push(s);const i=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&n.push(o);let a=n.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${a}`)}}}async remove(e){var t=this;try{return{data:await _e(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async list(e,t,r){var n=this;try{const s=me(me(me({},Ee),t),{},{prefix:e||""});return{data:await ve(n.fetch,`${n.url}/object/list/${n.bucketId}`,s,{headers:n.headers},r),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async listV2(e,t){var r=this;try{const n=me({},e);return{data:await ve(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},t),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};const Re="2.90.1",qe={"X-Client-Info":`storage-js/${Re}`};var Ae=class{constructor(e,t={},r,n){this.shouldThrowOnError=!1;const s=new URL(e);(null==n?void 0:n.useNewHostname)&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase.")),this.url=s.href.replace(/\/$/,""),this.headers=me(me({},qe),t),this.fetch=le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async listBuckets(e){var t=this;try{const r=t.listBucketOptionsToQueryString(e);return{data:await ye(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await ye(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createBucket(e,t={public:!1}){var r=this;try{return{data:await ve(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async updateBucket(e,t){var r=this;try{return{data:await xe(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async emptyBucket(e){var t=this;try{return{data:await ve(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await _e(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},$e=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=me(me({},qe),t),this.fetch=le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await ve(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async listBuckets(e){var t=this;try{const r=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&r.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);const n=r.toString(),s=n?`${t.url}/bucket?${n}`:`${t.url}/bucket`;return{data:await ye(t.fetch,s,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await _e(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}from(e){var t=this;if(!(e=>!(!e||"string"!=typeof e)&&!(0===e.length||e.length>100)&&e.trim()===e&&!e.includes("/")&&!e.includes("\\")&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e))(e))throw new se("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new ne({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(e,t){const r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(n)throw e;return{data:null,error:e}}}}})}};const Ie={"X-Client-Info":`storage-js/${Re}`,"Content-Type":"application/json"};var je=class extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}};function Pe(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}var Ne=class extends je{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Ue=class extends je{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}};const Le=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Be=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Me=(e,t,r,n)=>{const s={method:e,headers:(null==t?void 0:t.headers)||{}};return n?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(n)?(s.headers=me({"Content-Type":"application/json"},null==t?void 0:t.headers),s.body=JSON.stringify(n)):s.body=n,me(me({},s),r)):s};async function ze(e,t,r,n,s,i){return new Promise((o,a)=>{e(r,Me(t,n,s,i)).then(e=>{if(!e.ok)throw e;if(null==n?void 0:n.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>o(e)).catch(e=>(async(e,t,r)=>{if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==r?void 0:r.noResolveJson)){const r=e.status||500,n=e;if("function"==typeof n.json)n.json().then(e=>{const n=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new Ne(Be(e),r,n))}).catch(()=>{const e=r+"";t(new Ne(n.statusText||`HTTP ${r} error`,r,e))});else{const e=r+"";t(new Ne(n.statusText||`HTTP ${r} error`,r,e))}}else t(new Ue(Be(e),e))})(e,a,n))})}async function De(e,t,r,n,s){return ze(e,"POST",t,n,s,r)}var He=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=me(me({},Ie),t),this.fetch=Le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createIndex(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async getIndex(e,t){var r=this;try{return{data:await De(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async listIndexes(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async deleteIndex(e,t){var r=this;try{return{data:await De(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}},Fe=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=me(me({},Ie),t),this.fetch=Le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async putVectors(e){var t=this;try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:await De(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async getVectors(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async listVectors(e){var t=this;try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:await De(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async queryVectors(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async deleteVectors(e){var t=this;try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:await De(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}},We=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=me(me({},Ie),t),this.fetch=Le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async listBuckets(e={}){var t=this;try{return{data:await De(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await De(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}},Ke=class extends We{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Je(this.url,this.headers,e,this.fetch)}async createBucket(e){return(()=>super.createBucket)().call(this,e)}async getBucket(e){return(()=>super.getBucket)().call(this,e)}async listBuckets(e={}){return(()=>super.listBuckets)().call(this,e)}async deleteBucket(e){return(()=>super.deleteBucket)().call(this,e)}},Je=class extends He{constructor(e,t,r,n){super(e,t,n),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,me(me({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,me(me({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return(()=>super.getIndex)().call(this,this.vectorBucketName,e)}async deleteIndex(e){return(()=>super.deleteIndex)().call(this,this.vectorBucketName,e)}index(e){return new Ge(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Ge=class extends Fe{constructor(e,t,r,n,s){super(e,t,s),this.vectorBucketName=r,this.indexName=n}async putVectors(e){var t=this;return(()=>super.putVectors)().call(t,me(me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,me(me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,me(me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,me(me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,me(me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},Ve=class extends Ae{constructor(e,t={},r,n){super(e,t,r,n)}from(e){return new Oe(this.url,this.headers,e,this.fetch)}get vectors(){return new Ke(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new $e(this.url+"/iceberg",this.headers,this.fetch)}};const Xe="2.90.1",Ye=3e4,Qe=9e4,Ze={"X-Client-Info":`gotrue-js/${Xe}`},et="X-Supabase-Api-Version",tt={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},rt=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class nt extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function st(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class it extends nt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class ot extends nt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class at extends nt{constructor(e,t,r,n){super(e,r,n),this.name=t,this.status=r}}class lt extends at{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class ct extends at{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ht extends at{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ut extends at{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class dt extends at{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class pt extends at{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class mt extends at{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function gt(e){return st(e)&&"AuthRetryableFetchError"===e.name}class ft extends at{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class bt extends at{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),yt=" \t\n\r=".split(""),vt=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<yt.length;t+=1)e[yt[t].charCodeAt(0)]=-2;for(let t=0;t<wt.length;t+=1)e[wt[t].charCodeAt(0)]=t;return e})();function xt(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(wt[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(wt[e]),t.queuedBits-=6}}function _t(e,t,r){const n=vt[e];if(!(n>-1)){if(-2===n)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|n,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function kt(e){const t=[],r=e=>{t.push(String.fromCodePoint(e))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return void r(e);for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,n,r)};for(let t=0;t<e.length;t+=1)_t(e.charCodeAt(t),s,i);return t.join("")}function St(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function Ct(e){const t=[],r={queue:0,queuedBits:0},n=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)_t(e.charCodeAt(t),r,n);return new Uint8Array(t)}function Et(e){const t=[];return function(e,t){for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>55295&&n<=56319){const t=1024*(n-55296)&65535;n=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}St(n,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function Tt(e){const t=[],r={queue:0,queuedBits:0},n=e=>{t.push(e)};return e.forEach(e=>xt(e,r,n)),xt(null,r,n),t.join("")}const Ot=()=>"undefined"!=typeof window&&"undefined"!=typeof document,Rt={tested:!1,writable:!1},qt=()=>{if(!Ot())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(Rt.tested)return Rt.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Rt.tested=!0,Rt.writable=!0}catch(e){Rt.tested=!0,Rt.writable=!1}return Rt.writable};const At=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),$t=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},It=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},jt=async(e,t)=>{await e.removeItem(t)};class Pt{constructor(){this.promise=new Pt.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function Nt(e){const t=e.split(".");if(3!==t.length)throw new bt("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!rt.test(t[e]))throw new bt("JWT not in base64url format");return{header:JSON.parse(kt(t[0])),payload:JSON.parse(kt(t[1])),signature:Ct(t[2]),raw:{header:t[0],payload:t[1]}}}function Ut(e){return("0"+e.toString(16)).substr(-2)}async function Lt(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(r);return Array.from(n).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Bt(e,t,r=!1){const n=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let n=0;n<56;n++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,Ut).join("")}();let s=n;r&&(s+="/PASSWORD_RECOVERY"),await $t(e,`${t}-code-verifier`,s);const i=await Lt(n);return[i,n===i?"plain":"s256"]}Pt.promiseConstructor=Promise;const Mt=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const zt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Dt(e){if(!zt.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ht(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)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 Ft(e){return JSON.parse(JSON.stringify(e))}const Wt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Kt=[502,503,504];async function Jt(e){var t,r;if(!("object"==typeof(r=e)&&null!==r&&"status"in r&&"ok"in r&&"json"in r&&"function"==typeof r.json))throw new mt(Wt(e),0);if(Kt.includes(e.status))throw new mt(Wt(e),e.status);let n,s;try{n=await e.json()}catch(e){throw new ot(Wt(e),e)}const i=function(e){const t=e.headers.get(et);if(!t)return null;if(!t.match(Mt))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=tt.timestamp&&"object"==typeof n&&n&&"string"==typeof n.code?s=n.code:"object"==typeof n&&n&&"string"==typeof n.error_code&&(s=n.error_code),s){if("weak_password"===s)throw new ft(Wt(n),e.status,(null===(t=n.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===s)throw new lt}else if("object"==typeof n&&n&&"object"==typeof n.weak_password&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new ft(Wt(n),e.status,n.weak_password.reasons);throw new it(Wt(n),e.status||500,s)}async function Gt(e,t,r,n){var s;const i=Object.assign({},null==n?void 0:n.headers);i[et]||(i[et]=tt.name),(null==n?void 0:n.jwt)&&(i.Authorization=`Bearer ${n.jwt}`);const o=null!==(s=null==n?void 0:n.query)&&void 0!==s?s:{};(null==n?void 0:n.redirectTo)&&(o.redirect_to=n.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await async function(e,t,r,n,s,i){const o=((e,t,r,n)=>{const s={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),r))})(t,n,s,i);let a;try{a=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new mt(Wt(e),0)}a.ok||await Jt(a);if(null==n?void 0:n.noResolveJson)return a;try{return await a.json()}catch(e){await Jt(e)}}(e,t,r+a,{headers:i,noResolveJson:null==n?void 0:n.noResolveJson},{},null==n?void 0:n.body);return(null==n?void 0:n.xform)?null==n?void 0:n.xform(l):{data:Object.assign({},l),error:null}}function Vt(e){var t;let r=null;var n;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=(n=e.expires_in,Math.round(Date.now()/1e3)+n)));return{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function Xt(e){const t=Vt(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function Yt(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function Qt(e){return{data:e,error:null}}function Zt(e){const{action_link:r,email_otp:n,hashed_token:s,redirect_to:i,verification_type:o}=e,a=t(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:r,email_otp:n,hashed_token:s,redirect_to:i,verification_type:o},user:Object.assign({},a)},error:null}}function er(e){return e}const tr=["global","local","others"];class rr{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=At(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=tr[0]){if(tr.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${tr.join(", ")}`);try{return await Gt(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(st(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await Gt(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Yt})}catch(e){if(st(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:r}=e,n=t(e,["options"]),s=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(s.new_email=null==n?void 0:n.newEmail,delete s.newEmail),await Gt(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Zt,redirectTo:null==r?void 0:r.redirectTo})}catch(e){if(st(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await Gt(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Yt})}catch(e){if(st(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,n,s,i,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await Gt(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(s=null===(n=null==e?void 0:e.perPage)||void 0===n?void 0:n.toString())&&void 0!==s?s:""},xform:er});if(c.error)throw c.error;const h=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(st(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Dt(e);try{return await Gt(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Yt})}catch(e){if(st(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Dt(e);try{return await Gt(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Yt})}catch(e){if(st(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Dt(e);try{return await Gt(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Yt})}catch(e){if(st(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Dt(e.userId);try{const{data:t,error:r}=await Gt(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(st(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Dt(e.userId),Dt(e.id);try{return{data:await Gt(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(st(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,n,s,i,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await Gt(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(s=null===(n=null==e?void 0:e.perPage)||void 0===n?void 0:n.toString())&&void 0!==s?s:""},xform:er});if(c.error)throw c.error;const h=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(st(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await Gt(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(st(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await Gt(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(st(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await Gt(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(st(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await Gt(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(st(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await Gt(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(st(e))return{data:null,error:e};throw e}}}function nr(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}const sr=!!(globalThis&&qt()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class ir extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class or extends ir{}async function ar(e,t,r){sr&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const n=new globalThis.AbortController;return t>0&&setTimeout(()=>{n.abort(),sr&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async n=>{if(!n){if(0===t)throw sr&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new or(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(sr)try{const e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}sr&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,n.name);try{return await r()}finally{sr&&console.log("@supabase/gotrue-js: navigatorLock: released",e,n.name)}}))}function lr(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function cr(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class hr extends Error{constructor({message:e,code:t,cause:r,name:n}){var s;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!==(s=null!=n?n:r instanceof Error?r.name:void 0)&&void 0!==s?s:"Unknown Error",this.code=t}}class ur extends hr{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function dr({error:e,options:t}){var r,n,s;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new hr({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(r=i.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey))return new hr({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(n=i.authenticatorSelection)||void 0===n?void 0:n.userVerification))return new hr({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(s=i.authenticatorSelection)||void 0===s?void 0:s.userVerification))return new hr({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new hr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new hr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===i.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new hr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new hr({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!yr(t))return new hr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(i.rp.id!==t)return new hr({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new hr({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new hr({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new hr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function pr({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new hr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new hr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!yr(t))return new hr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new hr({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new hr({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new hr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const mr=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function gr(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:r,user:n,excludeCredentials:s}=e,i=t(e,["challenge","user","excludeCredentials"]),o=Ct(r).buffer,a=Object.assign(Object.assign({},n),{id:Ct(n.id).buffer}),l=Object.assign(Object.assign({},i),{challenge:o,user:a});if(s&&s.length>0){l.excludeCredentials=new Array(s.length);for(let e=0;e<s.length;e++){const t=s[e];l.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:Ct(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return l}function fr(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:r,allowCredentials:n}=e,s=t(e,["challenge","allowCredentials"]),i=Ct(r).buffer,o=Object.assign(Object.assign({},s),{challenge:i});if(n&&n.length>0){o.allowCredentials=new Array(n.length);for(let e=0;e<n.length;e++){const t=n[e];o.allowCredentials[e]=Object.assign(Object.assign({},t),{id:Ct(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function br(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e;return{id:e.id,rawId:e.id,response:{attestationObject:Tt(new Uint8Array(e.response.attestationObject)),clientDataJSON:Tt(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function wr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e,n=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Tt(new Uint8Array(s.authenticatorData)),clientDataJSON:Tt(new Uint8Array(s.clientDataJSON)),signature:Tt(new Uint8Array(s.signature)),userHandle:s.userHandle?Tt(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function yr(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function vr(){var e,t;return!!(Ot()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const xr={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},_r={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function kr(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),n={};for(const s of e)if(s)for(const e in s){const i=s[e];if(void 0!==i)if(Array.isArray(i))n[e]=i;else if(r(i))n[e]=i;else if(t(i)){const r=n[e];t(r)?n[e]=kr(r,i):n[e]=kr(i)}else n[e]=i}return n}class Sr{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:n},s){try{const{data:i,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!i)return{data:null,error:o};const a=null!=n?n:mr.createNewAbortSignal();if("create"===i.webauthn.type){const{user:e}=i.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${r}`),e.displayName||(e.displayName=e.name)}switch(i.webauthn.type){case"create":{const t=function(e,t){return kr(xr,e,t||{})}(i.webauthn.credential_options.publicKey,null==s?void 0:s.create),{data:r,error:n}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new ur("Browser returned unexpected credential type",t)}:{data:null,error:new ur("Empty credential response",t)}}catch(t){return{data:null,error:dr({error:t,options:e})}}}({publicKey:t,signal:a});return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:n}}case"request":{const t=function(e,t){return kr(_r,e,t||{})}(i.webauthn.credential_options.publicKey,null==s?void 0:s.request),{data:r,error:n}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new ur("Browser returned unexpected credential type",t)}:{data:null,error:new ur("Empty credential response",t)}}catch(t){return{data:null,error:pr({error:t,options:e})}}}(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:t,signal:a}));return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:n}}}}catch(e){return st(e)?{data:null,error:e}:{data:null,error:new ot("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:n}={}},s){if(!t)return{data:null,error:new nt("rpId is required for WebAuthn authentication")};try{if(!vr())return{data:null,error:new ot("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:n},{request:s});if(!i)return{data:null,error:o};const{webauthn:a}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:a.type,rpId:t,rpOrigins:r,credential_response:a.credential_response}})}catch(e){return st(e)?{data:null,error:e}:{data:null,error:new ot("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:n}={}},s){if(!t)return{data:null,error:new nt("rpId is required for WebAuthn registration")};try{if(!vr())return{data:null,error:new ot("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(t=>{var r;return null===(r=t.data)||void 0===r?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:o};const{data:a,error:l}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:n},{create:s});return a?this._verify({factorId:i.id,challengeId:a.challengeId,webauthn:{rpId:t,rpOrigins:r,type:a.webauthn.type,credential_response:a.webauthn.credential_response}}):{data:null,error:l}}catch(e){return st(e)?{data:null,error:e}:{data:null,error:new ot("Unexpected error in register",e)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const Cr={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ze,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function Er(e,t,r){return await r()}const Tr={};class Or{get jwks(){var e,t;return null!==(t=null===(e=Tr[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){Tr[this.storageKey]=Object.assign(Object.assign({},Tr[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=Tr[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Tr[this.storageKey]=Object.assign(Object.assign({},Tr[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const s=Object.assign(Object.assign({},Cr),e);if(this.storageKey=s.storageKey,this.instanceID=null!==(t=Or.nextInstanceID[this.storageKey])&&void 0!==t?t:0,Or.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,"function"==typeof s.debug&&(this.logger=s.debug),this.instanceID>0&&Ot()){const e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new rr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=At(s.fetch),this.lock=s.lock||Er,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&Ot()&&(null===(r=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===r?void 0:r.locks)?this.lock=ar:this.lock=Er,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new Sr(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(s.storage?this.storage=s.storage:qt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=nr(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=nr(this.memoryStorage)),Ot()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(n=this.broadcastChannel)||void 0===n||n.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Xe}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(Ot()&&(t=function(e){const t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),Ot()&&this.detectSessionInUrl&&"none"!==r){const{data:n,error:s}=await this._getSessionFromURL(t,r);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),function(e){return st(e)&&"AuthImplicitGrantRedirectError"===e.name}(s)){const t=null===(e=s.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:s}}return{error:s}}const{session:i,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",o),await this._saveSession(i),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return st(e)?this._returnResult({error:e}):this._returnResult({error:new ot("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,n;try{const s=await Gt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==r?r:{},gotrue_meta_security:{captcha_token:null===(n=null==e?void 0:e.options)||void 0===n?void 0:n.captchaToken}},xform:Vt}),{data:i,error:o}=s;if(o||!i)return this._returnResult({data:{user:null,session:null},error:o});const a=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,n;try{let s;if("email"in e){const{email:r,password:n,options:i}=e;let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Bt(this.storage,this.storageKey)),s=await Gt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==i?void 0:i.emailRedirectTo,body:{email:r,password:n,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:o,code_challenge_method:a},xform:Vt})}else{if(!("phone"in e))throw new ht("You must provide either an email or phone number and a password");{const{phone:t,password:i,options:o}=e;s=await Gt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:i,data:null!==(r=null==o?void 0:o.data)&&void 0!==r?r:{},channel:null!==(n=null==o?void 0:o.channel)&&void 0!==n?n:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:Vt})}}const{data:i,error:o}=s;if(o||!i)return await jt(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const a=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:r,password:n,options:s}=e;t=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},xform:Xt})}else{if(!("phone"in e))throw new ht("You must provide either an email or phone number and a password");{const{phone:r,password:n,options:s}=e;t=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},xform:Xt})}}const{data:r,error:n}=t;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!r||!r.session||!r.user){const e=new ct;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:n})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(n=e.options)||void 0===n?void 0:n.queryParams,skipBrowserRedirect:null===(s=e.options)||void 0===s?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{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,n,s,i,o,a,l,c,h,u;let d,p;if("message"in e)d=e.message,p=e.signature;else{const{chain:h,wallet:u,statement:m,options:g}=e;let f;if(Ot())if("object"==typeof u)f=u;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)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.");f=e.ethereum}else{if("object"!=typeof u||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");f=u}const b=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href),w=await f.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!w||0===w.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const y=lr(w[0]);let v=null===(r=null==g?void 0:g.signInWithEthereum)||void 0===r?void 0:r.chainId;if(!v){const e=await f.request({method:"eth_chainId"});v=parseInt(e,16)}d=function(e){var t;const{chainId:r,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:h,uri:u,version:d}=e;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)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(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const p=`${h?`${h}://${n}`:n} wants you to sign in with your Ethereum account:\n${lr(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let m=`URI: ${u}\nVersion: ${d}\nChain ID: ${r}${o?`\nNonce: ${o}`:""}\nIssued At: ${i.toISOString()}`;if(s&&(m+=`\nExpiration Time: ${s.toISOString()}`),a&&(m+=`\nNot Before: ${a.toISOString()}`),l&&(m+=`\nRequest ID: ${l}`),c){let e="\nResources:";for(const t of c){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}m+=e}return`${p}\n${m}`}({domain:b.host,address:y,statement:m,uri:b.href,version:"1",chainId:v,nonce:null===(n=null==g?void 0:g.signInWithEthereum)||void 0===n?void 0:n.nonce,issuedAt:null!==(i=null===(s=null==g?void 0:g.signInWithEthereum)||void 0===s?void 0:s.issuedAt)&&void 0!==i?i:new Date,expirationTime:null===(o=null==g?void 0:g.signInWithEthereum)||void 0===o?void 0:o.expirationTime,notBefore:null===(a=null==g?void 0:g.signInWithEthereum)||void 0===a?void 0:a.notBefore,requestId:null===(l=null==g?void 0:g.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(c=null==g?void 0:g.signInWithEthereum)||void 0===c?void 0:c.resources}),p=await f.request({method:"personal_sign",params:[cr(d),y]})}try{const{data:t,error:r}=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:p},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(u=e.options)||void 0===u?void 0:u.captchaToken}}:null),xform:Vt});if(r)throw r;if(!t||!t.session||!t.user){const e=new ct;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,n,s,i,o,a,l,c,h,u,d;let p,m;if("message"in e)p=e.message,m=e.signature;else{const{chain:u,wallet:d,statement:g,options:f}=e;let b;if(Ot())if("object"==typeof d)b=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))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.");b=e.solana}else{if("object"!=typeof d||!(null==f?void 0:f.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=d}const w=new URL(null!==(t=null==f?void 0:f.url)&&void 0!==t?t:window.location.href);if("signIn"in b&&b.signIn){const e=await b.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==f?void 0:f.signInWithSolana),{version:"1",domain:w.host,uri:w.href}),g?{statement:g}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");p="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),m=t.signature}else{if(!("signMessage"in b&&"function"==typeof b.signMessage&&"publicKey"in b&&"object"==typeof b&&b.publicKey&&"toBase58"in b.publicKey&&"function"==typeof b.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${w.host} wants you to sign in with your Solana account:`,b.publicKey.toBase58(),...g?["",g,""]:[""],"Version: 1",`URI: ${w.href}`,`Issued At: ${null!==(n=null===(r=null==f?void 0:f.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==n?n:(new Date).toISOString()}`,...(null===(s=null==f?void 0:f.signInWithSolana)||void 0===s?void 0:s.notBefore)?[`Not Before: ${f.signInWithSolana.notBefore}`]:[],...(null===(i=null==f?void 0:f.signInWithSolana)||void 0===i?void 0:i.expirationTime)?[`Expiration Time: ${f.signInWithSolana.expirationTime}`]:[],...(null===(o=null==f?void 0:f.signInWithSolana)||void 0===o?void 0:o.chainId)?[`Chain ID: ${f.signInWithSolana.chainId}`]:[],...(null===(a=null==f?void 0:f.signInWithSolana)||void 0===a?void 0:a.nonce)?[`Nonce: ${f.signInWithSolana.nonce}`]:[],...(null===(l=null==f?void 0:f.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${f.signInWithSolana.requestId}`]:[],...(null===(h=null===(c=null==f?void 0:f.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===h?void 0:h.length)?["Resources",...f.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await b.signMessage((new TextEncoder).encode(p),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=e}}try{const{data:t,error:r}=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:Tt(m)},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:Vt});if(r)throw r;if(!t||!t.session||!t.user){const e=new ct;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){const t=await It(this.storage,`${this.storageKey}-code-verifier`),[r,n]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new pt;const{data:t,error:s}=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:Vt});if(await jt(this.storage,`${this.storageKey}-code-verifier`),s)throw s;if(!t||!t.session||!t.user){const e=new ct;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=n?n:null}),error:s})}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{const{options:t,provider:r,token:n,access_token:s,nonce:i}=e,o=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:Vt}),{data:a,error:l}=o;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a||!a.session||!a.user){const e=new ct;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:l})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,n,s,i;try{if("email"in e){const{email:n,options:s}=e;let i=null,o=null;"pkce"===this.flowType&&([i,o]=await Bt(this.storage,this.storageKey));const{error:a}=await Gt(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:n,data:null!==(t=null==s?void 0:s.data)&&void 0!==t?t:{},create_user:null===(r=null==s?void 0:s.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},code_challenge:i,code_challenge_method:o},redirectTo:null==s?void 0:s.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){const{phone:t,options:r}=e,{data:o,error:a}=await Gt(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(n=null==r?void 0:r.data)&&void 0!==n?n:{},create_user:null===(s=null==r?void 0:r.shouldCreateUser)||void 0===s||s,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(i=null==r?void 0:r.channel)&&void 0!==i?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a})}throw new ht("You must provide either an email or phone number.")}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let n,s;"options"in e&&(n=null===(t=e.options)||void 0===t?void 0:t.redirectTo,s=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:i,error:o}=await Gt(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:Vt});if(o)throw o;if(!i){throw new Error("An error occurred on token verification.")}const a=i.session,l=i.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,n,s,i;try{let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Bt(this.storage,this.storageKey));const l=await Gt(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(n=null==e?void 0:e.options)||void 0===n?void 0:n.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:a}),headers:this.headers,xform:Qt});return(null===(s=l.data)||void 0===s?void 0:s.url)&&Ot()&&!(null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new lt;const{error:n}=await Gt(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:n,options:s}=e,{error:i}=await Gt(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},redirectTo:null==s?void 0:s.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){const{phone:r,type:n,options:s}=e,{data:i,error:o}=await Gt(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:o})}throw new ht("You must provide either an email or phone number and a type")}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){await this.initializePromise;return await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await It(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=!!e.expires_at&&1e3*e.expires_at-Date.now()<Qe;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const t=await It(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=Ht()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,r,n)=>{if("__isInsecureUserWarningProxy"===r)return!0;if("symbol"==typeof r){const t=r.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,r,n)}return t.value||"string"!=typeof r||(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."),t.value=!0),Reflect.get(e,r,n)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await Gt(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Yt}):await this._useSession(async e=>{var t,r,n;const{data:s,error:i}=e;if(i)throw i;return(null===(t=s.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await Gt(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(n=null===(r=s.session)||void 0===r?void 0:r.access_token)&&void 0!==n?n:void 0,xform:Yt}):{data:{user:null},error:new lt}})}catch(e){if(st(e))return function(e){return st(e)&&"AuthSessionMissingError"===e.name}(e)&&(await this._removeSession(),await jt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:n,error:s}=r;if(s)throw s;if(!n.session)throw new lt;const i=n.session;let o=null,a=null;"pkce"===this.flowType&&null!=e.email&&([o,a]=await Bt(this.storage,this.storageKey));const{data:l,error:c}=await Gt(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:i.access_token,xform:Yt});if(c)throw c;return i.user=l.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new lt;const t=Date.now()/1e3;let r=t,n=!0,s=null;const{payload:i}=Nt(e.access_token);if(i.exp&&(r=i.exp,n=r<=t),n){const{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};s=t}else{const{data:n,error:i}=await this._getUser(e.access_token);if(i)throw i;s={access_token:e.access_token,refresh_token:e.refresh_token,user:n.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(e){if(st(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:n,error:s}=t;if(s)throw s;e=null!==(r=n.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new lt;const{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!Ot())throw new ut("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ut(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new dt("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new ut("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new dt("No code detected.");const{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;const n=new URL(window.location.href);return n.searchParams.delete("code"),window.history.replaceState(window.history.state,"",n.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:o,expires_at:a,token_type:l}=e;if(!(s&&o&&i&&l))throw new ut("No session defined in URL");const c=Math.round(Date.now()/1e3),h=parseInt(o);let u=c+h;a&&(u=parseInt(a));const d=u-c;1e3*d<=Ye&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${h}s`);const p=u-h;c-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,c):c-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,u,c);const{data:m,error:g}=await this._getUser(s);if(g)throw g;const f={provider_token:r,provider_refresh_token:n,access_token:s,expires_in:h,expires_at:u,refresh_token:i,token_type:l,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:f,redirectType:e.type},error:null})}catch(e){if(st(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await It(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:n,error:s}=t;if(s)return this._returnResult({error:s});const i=null===(r=n.session)||void 0===r?void 0:r.access_token;if(i){const{error:t}=await this.admin.signOut(i,e);if(t&&(!function(e){return st(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await jt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Symbol("auth-callback"),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,n;try{const{data:{session:n},error:s}=t;if(s)throw s;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(t){await(null===(n=this.stateChangeEmitters.get(e))||void 0===n?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,n=null;"pkce"===this.flowType&&([r,n]=await Bt(this.storage,this.storageKey,!0));try{return await Gt(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:n}=await this._useSession(async t=>{var r,n,s,i,o;const{data:a,error:l}=t;if(l)throw l;const c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(r=e.options)||void 0===r?void 0:r.redirectTo,scopes:null===(n=e.options)||void 0===n?void 0:n.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:!0});return await Gt(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(o=null===(i=a.session)||void 0===i?void 0:i.access_token)&&void 0!==o?o:void 0})});if(n)throw n;return Ot()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(st(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:n,data:{session:s}}=t;if(n)throw n;const{options:i,provider:o,token:a,access_token:l,nonce:c}=e,h=await Gt(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(r=null==s?void 0:s.access_token)&&void 0!==r?r:void 0,body:{provider:o,id_token:a,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:Vt}),{data:u,error:d}=h;return d?this._returnResult({data:{user:null,session:null},error:d}):u&&u.session&&u.user?(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:d})):this._returnResult({data:{user:null,session:null},error:new ct})}catch(e){if(await jt(this.storage,`${this.storageKey}-code-verifier`),st(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,n;const{data:s,error:i}=t;if(i)throw i;return await Gt(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(n=null===(r=s.session)||void 0===r?void 0:r.access_token)&&void 0!==n?n:void 0})})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const s=Date.now();return await(r=async r=>(r>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await Gt(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Vt})),n=(e,t)=>{const r=200*Math.pow(2,e);return t&>(t)&&Date.now()+r-s<Ye},new Promise((e,t)=>{(async()=>{for(let s=0;s<1/0;s++)try{const t=await r(s);if(!n(s,null,t))return void e(t)}catch(e){if(!n(s,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),st(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}var r,n}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),Ot()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const n=await It(this.storage,this.storageKey);if(n&&this.userStorage){let t=await It(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:n.user},await $t(this.userStorage,this.storageKey+"-user",t)),n.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:Ht()}else if(n&&!n.user&&!n.user){const e=await It(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(n.user=e.user,await jt(this.storage,this.storageKey+"-user"),await $t(this.storage,this.storageKey,n)):n.user=Ht()}if(this._debug(r,"session from storage",n),!this._isValidSession(n))return this._debug(r,"session is not valid"),void(null!==n&&await this._removeSession());const s=1e3*(null!==(t=n.expires_at)&&void 0!==t?t:1/0)-Date.now()<Qe;if(this._debug(r,`session has${s?"":" not"} expired with margin of 90000s`),s){if(this.autoRefreshToken&&n.refresh_token){const{error:e}=await this._callRefreshToken(n.refresh_token);e&&(console.error(e),gt(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(n.user&&!0===n.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(n.access_token);!t&&(null==e?void 0:e.user)?(n.user=e.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(e){return this._debug(r,"error",e),void console.error(e)}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new lt;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Pt;const{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new lt;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const n={data:t.session,error:null};return this.refreshingDeferred.resolve(n),n}catch(e){if(this._debug(n,"error",e),st(e)){const r={data:null,error:e};return gt(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,r=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const n=[],s=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){n.push(e)}});if(await Promise.all(s),n.length>0){for(let e=0;e<n.length;e+=1)console.error(n[e]);throw n[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await jt(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await $t(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const n=Ft(e);await $t(this.storage,this.storageKey,n)}else{const e=Ft(t);await $t(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await jt(this.storage,this.storageKey),await jt(this.storage,this.storageKey+"-code-verifier"),await jt(this.storage,this.storageKey+"-user"),this.userStorage&&await jt(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ot()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Ye);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);const t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const n=Math.floor((1e3*r.expires_at-e)/Ye);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),n<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof ir))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ot()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const n=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&n.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&n.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){const[e,t]=await Bt(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});n.push(r.toString())}if(null==r?void 0:r.queryParams){const e=new URLSearchParams(r.queryParams);n.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&n.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:n,error:s}=t;return s?this._returnResult({data:null,error:s}):await Gt(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token})})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,n;const{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:a,error:l}=await Gt(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===a.type&&(null===(n=null==a?void 0:a.totp)||void 0===n?void 0:n.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:n,error:s}=t;if(s)return this._returnResult({data:null,error:s});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?br(e.webauthn.credential_response):wr(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:a}=await Gt(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});return a?this._returnResult({data:null,error:a}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:a}))})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:n,error:s}=t;if(s)return this._returnResult({data:null,error:s});const i=await Gt(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});if(i.error)return i;const{data:o}=i;if("webauthn"!==o.type)return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:gr(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:fr(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){const{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;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const n={all:[],phone:[],totp:[],webauthn:[]};for(const r of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])n.all.push(r),"verified"===r.status&&n[r.factor_type].push(r);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:n}=await this.getSession();if(n)return this._returnResult({data:null,error:n});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:s}=Nt(r.access_token);let i=null;s.aal&&(i=s.aal);let o=i;(null!==(t=null===(e=r.user.factors)||void 0===e?void 0:e.filter(e=>"verified"===e.status))&&void 0!==t?t:[]).length>0&&(o="aal2");return{data:{currentLevel:i,nextLevel:o,currentAuthenticationMethods:s.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;return n?this._returnResult({data:null,error:n}):r?await Gt(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new lt})})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new lt});const i=await Gt(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&Ot()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new lt});const i=await Gt(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&Ot()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await Gt(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new lt})})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;return n?this._returnResult({data:null,error:n}):r?(await Gt(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 lt})})}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;const n=Date.now();if(r=this.jwks.keys.find(t=>t.kid===e),r&&this.jwks_cached_at+6e5>n)return r;const{data:s,error:i}=await Gt(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return s.keys&&0!==s.keys.length?(this.jwks=s,this.jwks_cached_at=n,r=s.keys.find(t=>t.kid===e),r||null):null}async getClaims(e,t={}){try{let r=e;if(!r){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});r=e.session.access_token}const{header:n,payload:s,signature:i,raw:{header:o,payload:a}}=Nt(r);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(s.exp);const l=n.alg&&!n.alg.startsWith("HS")&&n.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(n.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!l){const{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:s,header:n,signature:i},error:null}}const c=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(n.alg),h=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!await crypto.subtle.verify(c,h,i,Et(`${o}.${a}`)))throw new bt("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(e){if(st(e))return this._returnResult({data:null,error:e});throw e}}}Or.nextInstanceID={};const Rr=Or;let qr="";qr="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const Ar={headers:{"X-Client-Info":`supabase-js-${qr}/2.90.1`}},$r={schema:"public"},Ir={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},jr={};function Pr(e){return(Pr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function Nr(e){var t=function(e,t){if("object"!=Pr(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=Pr(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==Pr(t)?t:t+""}function Ur(e,t,r){return(t=Nr(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Lr(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function Br(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Lr(Object(r),!0).forEach(function(t){Ur(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Lr(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const Mr=(e,t,r)=>{const n=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),s=Headers;return async(r,i)=>{var o;const a=null!==(o=await t())&&void 0!==o?o:e;let l=new s(null==i?void 0:i.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${a}`),n(r,Br(Br({},i),{},{headers:l}))}};var zr=class extends Rr{constructor(e){super(e)}},Dr=class{constructor(e,t,r){var n,s;this.supabaseUrl=e,this.supabaseKey=t;const i=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((r=t).endsWith("/")?r:r+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var r}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,a=function(e,t){var r,n;const{db:s,auth:i,realtime:o,global:a}=e,{db:l,auth:c,realtime:h,global:u}=t,d={db:Br(Br({},l),s),auth:Br(Br({},c),i),realtime:Br(Br({},h),o),storage:{},global:Br(Br(Br({},u),a),{},{headers:Br(Br({},null!==(r=null==u?void 0:u.headers)&&void 0!==r?r:{}),null!==(n=null==a?void 0:a.headers)&&void 0!==n?n:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:$r,realtime:jr,auth:Br(Br({},Ir),{},{storageKey:o}),global:Ar});var l;(this.storageKey=null!==(n=a.auth.storageKey)&&void 0!==n?n:"",this.headers=null!==(s=a.global.headers)&&void 0!==s?s:{},a.accessToken)?(this.accessToken=a.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(l=a.auth)&&void 0!==l?l:{},this.headers,a.global.fetch);this.fetch=Mr(t,this._getAccessToken.bind(this),a.global.fetch),this.realtime=this._initRealtimeClient(Br({headers:this.headers,accessToken:this._getAccessToken.bind(this)},a.realtime)),this.accessToken&&this.accessToken().then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new g(new URL("rest/v1",i).href,{headers:this.headers,schema:a.db.schema,fetch:this.fetch}),this.storage=new Ve(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),a.accessToken||this._listenForAuthEvents()}get functions(){return new l(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t,r=this;if(r.accessToken)return await r.accessToken();const{data:n}=await r.auth.getSession();return null!==(e=null===(t=n.session)||void 0===t?void 0:t.access_token)&&void 0!==e?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:s,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},h,u){const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new zr({url:this.authUrl.href,headers:Br(Br({},d),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:s,flowType:o,lock:a,debug:l,throwOnError:c,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new X(this.realtimeUrl.href,Br(Br({},e),{},{params:Br(Br({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}};(function(){if("undefined"!=typeof window)return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(null==t)return!1;const r=t.match(/^v(\d+)\./);return!!r&&parseInt(r[1],10)<=18})()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Hr={mode:"widget",position:"bottom-right",defaultOpen:!1,theme:"dark",features:["prompts","timeline","deployments","elements","captures"],captureConsole:!0,captureNetwork:!0,hotkey:"ctrl+shift+o",apiUrl:"https://orquesta.live"};class Fr{constructor(){this.listeners=new Set,this.state=this.getInitialState()}getInitialState(){return{isConnected:!1,isConnecting:!1,connectionError:null,projectId:null,projectName:null,agentOnline:!1,isAuthenticated:!1,isAuthenticating:!1,user:null,authError:null,requireAuth:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,rightClickEnabled:!0,currentPrompt:null,promptHistory:[],isSubmitting:!1,promptQueue:[],outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1,includeHistory:!1,includeContext:!1}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}setConnected(e,t,r){this.setState({isConnected:!0,isConnecting:!1,connectionError:null,projectId:e,projectName:t,agentOnline:r})}setConnectionError(e){this.setState({isConnected:!1,isConnecting:!1,connectionError:e})}setOpen(e){this.setState({isOpen:e})}toggle(){this.setState({isOpen:!this.state.isOpen})}setActiveTab(e){this.setState({activeTab:e})}setCurrentPrompt(e){this.setState({currentPrompt:e}),e&&!this.state.promptHistory.find(t=>t.id===e.id)&&this.setState({promptHistory:[e,...this.state.promptHistory].slice(0,50)})}updatePrompt(e,t){this.state.currentPrompt?.id===e&&this.setState({currentPrompt:{...this.state.currentPrompt,...t}}),this.setState({promptHistory:this.state.promptHistory.map(r=>r.id===e?{...r,...t}:r)})}addOutputLine(e){const t={...e,id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`};this.setState({outputLines:[...this.state.outputLines,t]})}clearOutput(){this.setState({outputLines:[]})}storePromptOutput(e){this.state.outputLines.length>0&&this.setState({promptOutputs:{...this.state.promptOutputs,[e]:[...this.state.outputLines]}})}addToQueue(e){this.setState({promptQueue:[...this.state.promptQueue,e]})}getNextFromQueue(){if(0===this.state.promptQueue.length)return null;const[e,...t]=this.state.promptQueue;return this.setState({promptQueue:t}),e}clearQueue(){this.setState({promptQueue:[]})}getQueueLength(){return this.state.promptQueue.length}setSelectedElement(e){this.setState({selectedElement:e,isSelectingElement:!1})}startElementSelection(){this.setState({isSelectingElement:!0})}cancelElementSelection(){this.setState({isSelectingElement:!1,selectedElement:null})}setOverlayMode(e){this.setState({overlayMode:e}),"off"===e&&this.setState({highlightedPromptId:null})}setHighlightedPromptId(e){this.setState({highlightedPromptId:e})}setElementMarkers(e){this.setState({elementMarkers:e})}setCommentsForPrompt(e,t){this.setState({comments:{...this.state.comments,[e]:t}})}addComment(e,t){const r=this.state.comments[e]||[];this.setState({comments:{...this.state.comments,[e]:[...r,t]}}),this.setState({promptHistory:this.state.promptHistory.map(t=>t.id===e?{...t,comment_count:(t.comment_count||0)+1}:t)})}setExpandedPromptId(e){this.setState({expandedPromptId:e})}setLoadingComments(e){this.setState({isLoadingComments:e})}addConsoleLogs(e){this.setState({consoleLogs:[...this.state.consoleLogs,...e].slice(-100)})}addNetworkLogs(e){this.setState({networkLogs:[...this.state.networkLogs,...e].slice(-100)})}toggleIncludeConsole(){this.setState({includeConsole:!this.state.includeConsole})}toggleIncludeNetwork(){this.setState({includeNetwork:!this.state.includeNetwork})}toggleIncludeHistory(){this.setState({includeHistory:!this.state.includeHistory})}toggleIncludeContext(){this.setState({includeContext:!this.state.includeContext})}setAuth(e,t){this.setState({user:e,isAuthenticated:t,isAuthenticating:!1,authError:null})}setAuthenticating(e){this.setState({isAuthenticating:e})}setAuthError(e){this.setState({authError:e,isAuthenticating:!1})}setRequireAuth(e){this.setState({requireAuth:e})}reset(){this.state=this.getInitialState(),this.notify()}}class Wr{constructor(){this.buffer=[],this.maxSize=100,this.originalConsole=null,this.errorHandler=null,this.rejectionHandler=null,this.listeners=new Set}start(){if(this.originalConsole)return;this.originalConsole={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};const e=e=>(...t)=>{const r=this.createEntry(e,t);this.addEntry(r),this.originalConsole?.[e](...t)};console.log=e("log"),console.info=e("info"),console.warn=e("warn"),console.error=e("error"),this.errorHandler=e=>{const t=this.createEntry("error",[e.message],e.error?.stack);this.addEntry(t)},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{const t=e.reason instanceof Error?e.reason.message:String(e.reason),r=e.reason instanceof Error?e.reason.stack:void 0,n=this.createEntry("error",[`Unhandled Promise Rejection: ${t}`],r);this.addEntry(n)},window.addEventListener("unhandledrejection",this.rejectionHandler)}stop(){this.originalConsole&&(console.log=this.originalConsole.log,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error,this.originalConsole=null),this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null)}formatArg(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if(null===e)return"null";if(void 0===e)return"undefined";if("object"==typeof e)try{const t=JSON.stringify(e,null,2);if("{}"===t||"[]"===t){const t=Object.prototype.toString.call(e);if("[object Object]"!==t&&"[object Array]"!==t)return t}return t}catch{return Object.prototype.toString.call(e)}return String(e)}createEntry(e,t,r){const n=t.map(e=>this.formatArg(e)).join(" ");return{timestamp:Date.now(),level:e,message:n||"(empty)",args:t,stack:r}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>"error"===e.level||"warn"===e.level)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getRecent(20);return 0===t.length?"":t.map(e=>`${`[${new Date(e.timestamp).toISOString()}] [${e.level.toUpperCase()}]`} ${e.message}${e.stack?`\n${e.stack}`:""}`).join("\n")}}class Kr{constructor(){this.buffer=[],this.maxSize=100,this.originalFetch=null,this.originalXHROpen=null,this.originalXHRSend=null,this.listeners=new Set}start(){this.originalFetch||(this.patchFetch(),this.patchXHR())}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXHROpen&&this.originalXHRSend&&(XMLHttpRequest.prototype.open=this.originalXHROpen,XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHROpen=null,this.originalXHRSend=null)}patchFetch(){this.originalFetch=window.fetch.bind(window),window.fetch=async(e,t)=>{const r="string"==typeof e?e:e instanceof URL?e.href:e.url,n=t?.method||"GET",s=Date.now(),i={timestamp:s,method:n,url:r,requestBody:t?.body};try{const r=await this.originalFetch(e,t);if(i.status=r.status,i.duration=Date.now()-s,!r.ok)try{const e=r.clone();i.responseBody=await e.text()}catch{}return this.addEntry(i),r}catch(e){throw i.duration=Date.now()-s,i.error=e instanceof Error?e.message:String(e),this.addEntry(i),e}}}patchXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;const e=this,t=new WeakMap;XMLHttpRequest.prototype.open=function(r,n,...s){return t.set(this,{method:r,url:"string"==typeof n?n:n.href,startTime:0}),e.originalXHROpen.apply(this,[r,n,...s])},XMLHttpRequest.prototype.send=function(r){const n=t.get(this);return n&&(n.startTime=Date.now(),this.addEventListener("loadend",()=>{const t={timestamp:n.startTime,method:n.method,url:n.url,status:this.status,duration:Date.now()-n.startTime};if(this.status>=400||0===this.status){t.error=this.statusText||"Request failed";try{t.responseBody=this.responseText}catch{}}e.addEntry(t)})),e.originalXHRSend.call(this,r)}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>e.status&&e.status>=400||e.error)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getErrors();return 0===t.length?"":t.map(e=>{const t=new Date(e.timestamp).toISOString(),r=e.status?`[${e.status}]`:"[FAILED]";return`[${t}] ${e.method} ${e.url} ${r}${e.error?` - ${e.error}`:""}`}).join("\n")}}class Jr{constructor(){this.overlay=null,this.highlight=null,this.selectedHighlight=null,this.selectedElement=null,this.isActive=!1,this.onSelect=null,this.onCancel=null,this.globalRightClickHandler=null,this.globalRightClickCallback=null,this.globalRightClickWithPositionCallback=null,this.selectedElementScrollHandler=null,this.handleMouseMove=e=>{if(!this.isActive||!this.highlight)return;const t=document.elementFromPoint(e.clientX,e.clientY);if(!t||t.id?.startsWith("orquesta-"))return;this.selectedElement=t;const r=t.getBoundingClientRect();this.highlight.style.display="block",this.highlight.style.top=`${r.top}px`,this.highlight.style.left=`${r.left}px`,this.highlight.style.width=`${r.width}px`,this.highlight.style.height=`${r.height}px`;const n=this.highlight.querySelector("#orquesta-element-label");if(n){const e=t.tagName.toLowerCase(),r=t.id?`#${t.id}`:"",s=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";n.textContent=`<${e}${r}${s}>`}},this.handleClick=e=>{if(!this.isActive)return;const t=e.target;if(!t.id?.startsWith("orquesta-")&&(e.preventDefault(),e.stopPropagation(),this.selectedElement)){const e=this.getElementContext(this.selectedElement);this.deactivate(),this.onSelect?.(e)}},this.handleKeyDown=e=>{"Escape"===e.key&&this.isActive&&(this.deactivate(),this.onCancel?.())},this.promptHighlightScrollHandler=null}setupGlobalRightClick(e){return this.globalRightClickCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const r=this.getElementContext(t);this.globalRightClickCallback?.(r)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickCallback=null)}}setupGlobalRightClickWithPosition(e){return this.globalRightClickWithPositionCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const r=this.getElementContext(t),n={x:e.clientX,y:e.clientY};this.globalRightClickWithPositionCallback?.(r,n)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickWithPositionCallback=null)}}highlightSelectedElement(e){try{const t=this.safeQuerySelector(e);if(!t)return null;this.removeSelectedHighlight(),this.selectedHighlight=document.createElement("div"),this.selectedHighlight.id="orquesta-selected-element-highlight",this.selectedHighlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #3b82f6;\n background: rgba(59, 130, 246, 0.15);\n z-index: 2147483640;\n transition: all 0.15s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25), 0 0 20px rgba(59, 130, 246, 0.3);\n ",document.body.appendChild(this.selectedHighlight);const r=document.createElement("div");r.id="orquesta-selected-element-label",r.style.cssText='\n position: absolute;\n top: -28px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 8px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ';const n=t.tagName.toLowerCase(),s=t.id?`#${t.id}`:"",i=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";r.textContent=`Selected: <${n}${s}${i}>`,this.selectedHighlight.appendChild(r);const o=()=>{if(!this.selectedHighlight)return;const e=t.getBoundingClientRect();this.selectedHighlight.style.top=e.top-3+"px",this.selectedHighlight.style.left=e.left-3+"px",this.selectedHighlight.style.width=`${e.width+6}px`,this.selectedHighlight.style.height=`${e.height+6}px`};return o(),this.selectedElementScrollHandler=o,window.addEventListener("scroll",this.selectedElementScrollHandler,!0),window.addEventListener("resize",this.selectedElementScrollHandler),t}catch{return null}}removeSelectedHighlight(){this.selectedHighlight&&(this.selectedHighlight.remove(),this.selectedHighlight=null),this.selectedElementScrollHandler&&(window.removeEventListener("scroll",this.selectedElementScrollHandler,!0),window.removeEventListener("resize",this.selectedElementScrollHandler),this.selectedElementScrollHandler=null)}activate(e,t){this.isActive||(this.isActive=!0,this.onSelect=e,this.onCancel=t||null,this.createOverlay(),this.addListeners(),document.body.style.cursor="crosshair")}deactivate(){this.isActive&&(this.isActive=!1,this.removeListeners(),this.removeOverlay(),this.selectedElement=null,document.body.style.cursor="")}isSelecting(){return this.isActive}createOverlay(){this.overlay=document.createElement("div"),this.overlay.id="orquesta-element-selector-overlay",this.overlay.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2147483646;\n pointer-events: none;\n ",document.body.appendChild(this.overlay),this.highlight=document.createElement("div"),this.highlight.id="orquesta-element-highlight",this.highlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 2px solid #3b82f6;\n background: rgba(59, 130, 246, 0.1);\n z-index: 2147483646;\n transition: all 0.1s ease;\n display: none;\n ",document.body.appendChild(this.highlight);const e=document.createElement("div");e.id="orquesta-element-label",e.style.cssText="\n position: absolute;\n bottom: -24px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: monospace;\n padding: 2px 6px;\n border-radius: 2px;\n white-space: nowrap;\n ",this.highlight.appendChild(e)}removeOverlay(){this.overlay?.remove(),this.highlight?.remove(),this.overlay=null,this.highlight=null}addListeners(){document.addEventListener("mousemove",this.handleMouseMove,!0),document.addEventListener("click",this.handleClick,!0),document.addEventListener("keydown",this.handleKeyDown,!0)}removeListeners(){document.removeEventListener("mousemove",this.handleMouseMove,!0),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("keydown",this.handleKeyDown,!0)}highlightElement(e){try{const t=this.safeQuerySelector(e);if(!t)return null;this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null);let r=document.getElementById("orquesta-prompt-highlight");r||(r=document.createElement("div"),r.id="orquesta-prompt-highlight",r.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #8b5cf6;\n background: rgba(139, 92, 246, 0.15);\n z-index: 2147483640;\n transition: top 0.1s ease, left 0.1s ease, width 0.1s ease, height 0.1s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2), 0 0 20px rgba(139, 92, 246, 0.3);\n ",document.body.appendChild(r));let n=r.querySelector("#orquesta-prompt-highlight-label");n||(n=document.createElement("div"),n.id="orquesta-prompt-highlight-label",n.style.cssText='\n position: absolute;\n top: -30px;\n left: 0;\n background: #8b5cf6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 10px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ',r.appendChild(n));const s=t.tagName.toLowerCase(),i=t.id?`#${t.id}`:"",o=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";n.textContent=`Highlighted: <${s}${i}${o}>`;const a=()=>{const e=t.getBoundingClientRect();r.style.display="block",r.style.top=e.top-3+"px",r.style.left=e.left-3+"px",r.style.width=`${e.width+6}px`,r.style.height=`${e.height+6}px`};a(),this.promptHighlightScrollHandler=a,window.addEventListener("scroll",this.promptHighlightScrollHandler,!0),window.addEventListener("resize",this.promptHighlightScrollHandler);const l=t.getBoundingClientRect();return(l.top<0||l.bottom>window.innerHeight)&&t.scrollIntoView({behavior:"smooth",block:"center"}),t}catch{return null}}removeHighlight(){const e=document.getElementById("orquesta-prompt-highlight");e&&(e.style.display="none"),this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null)}safeQuerySelector(e){try{return document.querySelector(e)}catch{return null}}findElement(e,t){try{let r=this.safeQuerySelector(e);if(r)return r;if(t&&(r=document.getElementById(t),r))return r;const n=e.match(/^([a-z]+)\.([a-z0-9_-]+)/i);if(n){const[,e,t]=n;if(r=this.safeQuerySelector(`${e}.${t}`),r)return r}return null}catch{return null}}getElementContext(e){const t=e.getBoundingClientRect(),r={};for(const t of e.attributes)t.name.startsWith("data-")||"class"===t.name||"id"===t.name||(r[t.name]=t.value);return{selector:this.generateSelector(e),tag:e.tagName.toLowerCase(),id:e.id||void 0,className:"string"==typeof e.className?e.className:void 0,textContent:e.textContent?.trim().slice(0,200)||void 0,boundingRect:t,attributes:Object.keys(r).length>0?r:void 0}}isValidCssClass(e){return!/[@:/\[\]()!#]/.test(e)&&!!/^[a-zA-Z_-]/.test(e)}generateSelector(e){if(e.id&&this.isValidCssClass(e.id))return`#${e.id}`;const t=[];let r=e;for(;r&&r!==document.body;){let e=r.tagName.toLowerCase();if(r.id&&this.isValidCssClass(r.id)){e=`#${r.id}`,t.unshift(e);break}if(r.className&&"string"==typeof r.className){const t=r.className.trim().split(/\s+/).filter(e=>this.isValidCssClass(e)).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}const n=r.parentElement;if(n){const t=Array.from(n.children).filter(e=>e.tagName===r.tagName);if(t.length>1){e+=`:nth-child(${t.indexOf(r)+1})`}}t.unshift(e),r=r.parentElement}return t.join(" > ")}}class Gr{constructor(e,t){this.listeners=new Set,this.popupWindow=null,this.messageHandler=null,this.broadcastChannel=null,this.pollInterval=null,this.token=e,this.apiUrl=t,this.state=this.getInitialState()}getInitialState(){return{isAuthenticated:!1,isAuthenticating:!1,user:null,sessionToken:null,expiresAt:null,authError:null}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}getStorageKey(){return`orquesta_embed_session_${this.token.slice(-8)}`}saveSession(e){try{localStorage.setItem(this.getStorageKey(),JSON.stringify(e))}catch{}}loadSession(){try{const e=localStorage.getItem(this.getStorageKey());if(!e)return null;const t=JSON.parse(e);return t.expiresAt&&new Date(t.expiresAt)<new Date?(this.clearSession(),null):t}catch{return null}}clearSession(){try{localStorage.removeItem(this.getStorageKey())}catch{}}async checkSession(){const e=this.loadSession();if(!e)return!1;try{const t=await fetch(`${this.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:e.sessionToken})});if(!t.ok)return this.clearSession(),!1;const r=await t.json();return r.valid?(this.setState({isAuthenticated:!0,user:r.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null}),!0):(this.clearSession(),!1)}catch{return this.setState({isAuthenticated:!0,user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null}),!0}}login(){return new Promise((e,t)=>{this.setState({isAuthenticating:!0,authError:null});const r=Math.random().toString(36).slice(2),n=`eas_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,s=new URL(`${this.apiUrl}/embed/auth`);s.searchParams.set("token",this.token),s.searchParams.set("origin",window.location.origin),s.searchParams.set("state",r),s.searchParams.set("authSession",n);const i=window.screenX+(window.innerWidth-500)/2,o=window.screenY+(window.innerHeight-600)/2;if(this.popupWindow=window.open(s.toString(),"orquesta_auth",`width=500,height=600,left=${i},top=${o},popup=yes`),!this.popupWindow)return this.setState({isAuthenticating:!1,authError:"Popup blocked"}),void t(new Error("Popup blocked. Please allow popups for this site."));this.messageHandler=r=>{if(r.origin!==new URL(this.apiUrl).origin)return;const{type:n,payload:s}=r.data||{};"orquesta_auth_success"===n?(this.handleAuthSuccess(s),e(s),this.cleanup()):"orquesta_auth_error"===n?(this.handleAuthError(s),t(new Error(s.message||"Authentication failed")),this.cleanup()):"orquesta_auth_closed"===n&&(this.setState({isAuthenticating:!1}),t(new Error("Authentication cancelled")),this.cleanup())},window.addEventListener("message",this.messageHandler);const a=this.apiUrl.replace("://orquesta.live","://ws.orquesta.live").replace("://localhost:3113","://localhost:3200");this.pollInterval=setInterval(async()=>{try{const r=await fetch(`${a}/auth/result/${n}`);if(!r.ok)return;const s=await r.json();if(s.pending)return;const{type:i,payload:o}=s;"orquesta_auth_success"===i?(this.handleAuthSuccess(o),e(o),this.cleanup()):"orquesta_auth_error"===i&&(this.handleAuthError(o),t(new Error(o.message||"Authentication failed")),this.cleanup())}catch{}},1500);const l=setInterval(()=>{this.popupWindow?.closed&&(clearInterval(l),this.state.isAuthenticating&&(this.setState({isAuthenticating:!1}),t(new Error("Authentication cancelled")),this.cleanup()))},500)})}handleAuthSuccess(e){const t={user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt};this.saveSession(t),this.setState({isAuthenticated:!0,isAuthenticating:!1,user:t.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt,authError:null})}handleAuthError(e){this.setState({isAuthenticating:!1,authError:e.message})}cleanup(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.popupWindow&&!this.popupWindow.closed&&this.popupWindow.close(),this.popupWindow=null}async logout(){const e=this.loadSession();if(e?.sessionToken)try{await fetch(`${this.apiUrl}/api/embed/session`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:e.sessionToken})})}catch{}this.clearSession(),this.setState(this.getInitialState())}getUser(){return this.state.user}getSessionToken(){return this.state.sessionToken}destroy(){this.cleanup(),this.listeners.clear()}}const Vr=!1,Xr="prompts",Yr="dark";const Qr=new class{constructor(){this.projectId=null}setProjectId(e){this.projectId=e}getKey(e){const t=`orquesta_embed_${e}`;return this.projectId?`${t}_${this.projectId}`:t}get(e){try{const t=localStorage.getItem(this.getKey(e));return t?JSON.parse(t):null}catch{return null}}set(e,t){try{localStorage.setItem(this.getKey(e),JSON.stringify(t))}catch{}}remove(e){try{localStorage.removeItem(this.getKey(e))}catch{}}getState(){return{isOpen:this.get("isOpen")??Vr,position:this.get("position"),size:this.get("size"),activeTab:this.get("activeTab")??Xr,theme:this.get("theme")??Yr}}setState(e){Object.entries(e).forEach(([e,t])=>{void 0!==t&&this.set(e,t)})}clear(){["isOpen","position","size","activeTab","theme"].forEach(e=>this.remove(e))}};class Zr{constructor(e){this.supabase=null,this.channel=null,this.projectId=null,this.authManager=null,this.hotkeyHandler=null,this.config={...Hr,...e},this.state=new Fr,this.consoleCapture=new Wr,this.networkCapture=new Kr,this.elementSelector=new Jr,this.config.requireAuth&&(this.state.setRequireAuth(!0),this.authManager=new Gr(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(e=>{this.state.setState({isAuthenticated:e.isAuthenticated,isAuthenticating:e.isAuthenticating,user:e.user,authError:e.authError})}))}async connect(){if(!this.config.token)throw new Error("Embed token is required");this.state.setState({isConnecting:!0});try{const n=await fetch(`${this.config.apiUrl}/api/embed/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.token})});if(!n.ok){const e=await n.json();throw new Error(e.error||"Failed to validate token")}const s=await n.json();if(!s.valid)throw new Error("Invalid embed token");this.projectId=s.projectId,Qr.setProjectId(s.projectId);const i=s.requireAuth||this.config.requireAuth;i&&!this.authManager?(this.state.setRequireAuth(!0),this.authManager=new Gr(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(e=>{this.state.setState({isAuthenticated:e.isAuthenticated,isAuthenticating:e.isAuthenticating,user:e.user,authError:e.authError})}),await this.authManager.checkSession()):i&&this.state.setRequireAuth(!0),this.supabase=(e=s.supabaseUrl,t=s.supabaseAnonKey,new Dr(e,t,r)),this.channel=this.supabase.channel(s.channelName),this.channel.on("broadcast",{event:"output"},({payload:e})=>{this.handleOutput(e)}).on("broadcast",{event:"complete"},({payload:e})=>{this.handleComplete(e)}).on("broadcast",{event:"error"},({payload:e})=>{this.handleError(e)}).subscribe(e=>{if("SUBSCRIBED"===e){this.state.setConnected(s.projectId,s.project?.name||"Project",s.project?.agent_online||!1),this.config.captureConsole&&(this.consoleCapture.start(),this.consoleCapture.subscribe(e=>{this.state.addConsoleLogs([e])})),this.config.captureNetwork&&(this.networkCapture.start(),this.networkCapture.subscribe(e=>{this.state.addNetworkLogs([e])})),this.setupHotkey(),this.loadTimeline();const e=Qr.getState();this.state.setState({isOpen:this.config.defaultOpen??e.isOpen,activeTab:e.activeTab||"prompts"}),this.config.onReady?.()}else"CHANNEL_ERROR"!==e&&"TIMED_OUT"!==e||this.state.setConnectionError("Failed to connect to channel")})}catch(e){const t=e instanceof Error?e.message:"Connection failed";throw this.state.setConnectionError(t),this.config.onError?.(e instanceof Error?e:new Error(t)),e}var e,t,r}disconnect(){this.channel&&(this.supabase?.removeChannel(this.channel),this.channel=null),this.consoleCapture.stop(),this.networkCapture.stop(),this.elementSelector.deactivate(),this.removeHotkey(),this.authManager&&this.authManager.destroy(),this.state.reset(),this.supabase=null,this.projectId=null}setupHotkey(){if(!this.config.hotkey)return;const e=this.config.hotkey.toLowerCase().split("+"),t=e.pop(),r=new Set(e);this.hotkeyHandler=e=>{if(!e.key)return;const n=r.has("ctrl")===(e.ctrlKey||e.metaKey),s=r.has("shift")===e.shiftKey,i=r.has("alt")===e.altKey,o=e.key.toLowerCase()===t;n&&s&&i&&o&&(e.preventDefault(),this.toggle())},document.addEventListener("keydown",this.hotkeyHandler)}removeHotkey(){this.hotkeyHandler&&(document.removeEventListener("keydown",this.hotkeyHandler),this.hotkeyHandler=null)}handleOutput(e){if(!this.state.getState().currentPrompt)return;let t,r,n,s="stdout",i=e.data;"stderr"===e.type?s="stderr":e.data.includes("Tool:")||e.data.includes("tool_call")?s="tool":(e.data.includes("thinking")||e.data.includes("Thinking"))&&(s="thinking");try{const o=JSON.parse(e.data);if(o.type){switch(o.type){case"thinking":s="thinking",i=o.thinking?.content||e.data;break;case"tool_call":s="tool_call",r=o.tool_call?.name,i=`Using ${r||"tool"}`;break;case"tool_result":s="tool_result",r=o.tool_result?.name,n=o.tool_result?.success,i=n?o.tool_result?.output||"Success":o.tool_result?.error||"Failed";break;case"output":s="output",i=o.output?.content||e.data;break;case"error":s="error",i=o.error?.message||e.data;break;case"system":s="system",i=o.system?.message||o.system?.event||e.data;break;case"progress":s="progress";const t=void 0!==o.progress?.percentage?` (${o.progress.percentage}%)`:"";i=(o.progress?.message||"Processing")+t;break;default:i=o.content||o.message||e.data}t=o}}catch{}this.state.addOutputLine({timestamp:e.timestamp||Date.now(),type:s,content:i,details:t,toolName:r,toolSuccess:n})}handleComplete(e){const t=this.state.getState(),r=0===e.exitCode?"completed":"failed",n=t.currentPrompt?.id;if(t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:r,completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),n&&this.config.onPromptComplete&&this.config.onPromptComplete(n,r),this.config.reloadOnComplete&&"completed"===r){const e=this.config.reloadDelay??1500;return console.log(`[Orquesta Embed] Prompt completed. Reloading page in ${e}ms...`),void setTimeout(()=>{window.location.reload()},e)}this.processQueue()}async processQueue(){const e=this.state.getNextFromQueue();if(e){console.log(`[Orquesta Embed] Processing queued prompt. Remaining in queue: ${this.state.getQueueLength()}`);try{await this.submitPrompt(e.content,e.options)}catch(e){console.error("[Orquesta Embed] Failed to process queued prompt:",e),this.processQueue()}}}handleError(e){const t=this.state.getState();this.state.addOutputLine({timestamp:Date.now(),type:"stderr",content:`Error: ${e.error}`}),t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:"failed",completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),this.processQueue()}async submitPrompt(e,t){if(!this.projectId)throw new Error("Not connected");if(this.config.requireAuth&&!this.state.getState().isAuthenticated)throw new Error("Authentication required. Please log in first.");const r=this.state.getState();if(r.isSubmitting)return this.state.addToQueue({id:`queue-${Date.now()}`,content:e,options:t,queuedAt:Date.now()}),console.log(`[Orquesta Embed] Prompt queued. Queue length: ${this.state.getQueueLength()}`),`queued-${Date.now()}`;this.state.setState({isSubmitting:!0}),this.state.clearOutput();let n=e;const s=t?.elementContext||r.selectedElement;if(s&&(n+=`\n\n--- Element Context ---\nSelector: ${s.selector}\nTag: <${s.tag}>\n${s.id?`ID: ${s.id}`:""}\n${s.className?`Classes: ${s.className}`:""}\n${s.textContent?`Text: ${s.textContent}`:""}\n${s.attributes?`Attributes: ${JSON.stringify(s.attributes)}`:""}`),t?.includeConsole??r.includeConsole){const e=this.consoleCapture.formatForPrompt();e&&(n+=`\n\n--- Console Logs ---\n${e}`)}if(t?.includeNetwork??r.includeNetwork){const e=this.networkCapture.formatForPrompt();e&&(n+=`\n\n--- Network Errors ---\n${e}`)}if(t?.includeHistory??r.includeHistory){const e=r.promptHistory.filter(e=>"completed"===e.status).slice(0,5).reverse();e.length>0&&(n+="\n\n--- Previous Prompts Context ---",e.forEach((e,t)=>{n+=`\n\n[Prompt ${t+1}]: ${e.content}`;const s=r.promptOutputs[e.id];if(s&&s.length>0){const e=s.slice(-10).map(e=>e.content).join("\n");n+=`\n[Output ${t+1}]:\n${e}`}}))}try{const e={"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},t=this.authManager?.getSessionToken();t&&(e["X-Session-Token"]=t);const r=await fetch(`${this.config.apiUrl}/api/embed/prompts`,{method:"POST",headers:e,body:JSON.stringify({projectId:this.projectId,content:n,elementContext:s})});if(!r.ok){const e=await r.json();throw new Error(e.error||"Failed to submit prompt")}const i=(await r.json()).prompt;return this.state.setCurrentPrompt(i),this.state.setSelectedElement(null),this.config.onPromptSubmit?.(i.id),i.id}catch(e){throw this.state.setState({isSubmitting:!1}),e}}async loadTimeline(){if(this.projectId)try{const e=await fetch(`${this.config.apiUrl}/api/embed/prompts?projectId=${this.projectId}&limit=50`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(e.ok){const t=await e.json();this.state.setState({promptHistory:t.prompts||[]})}}catch{}}open(){this.state.setOpen(!0),Qr.set("isOpen",!0)}close(){this.state.setOpen(!1),Qr.set("isOpen",!1)}toggle(){const e=!this.state.getState().isOpen;this.state.setOpen(e),Qr.set("isOpen",e)}startElementSelection(){this.state.startElementSelection(),this.elementSelector.activate(e=>this.state.setSelectedElement(e),()=>this.state.cancelElementSelection())}getState(){return this.state.getState()}subscribe(e){return this.state.subscribe(e)}getConsoleCapture(){return this.consoleCapture}getNetworkCapture(){return this.networkCapture}getElementSelector(){return this.elementSelector}setActiveTab(e){this.state.setActiveTab(e)}async loadComments(e){if(this.projectId){this.state.setLoadingComments(!0);try{const t=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(t.ok){const r=await t.json();this.state.setCommentsForPrompt(e,r.comments||[])}}catch{}finally{this.state.setLoadingComments(!1)}}}async addComment(e,t){if(this.projectId)try{const r=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({content:t})});if(r.ok){const t=await r.json();t.comment&&this.state.addComment(e,t.comment)}}catch(e){throw console.error("Failed to add comment:",e),e}}setOverlayMode(e){if(this.state.setOverlayMode(e),"off"===e)this.elementSelector.removeHighlight(),this.state.setHighlightedPromptId(null);else if("all"===e){const e=this.state.getState().promptHistory.filter(e=>e.element_context?.selector).map(e=>({promptId:e.id,selector:e.element_context.selector,rect:null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}));this.state.setElementMarkers(e)}else this.state.setElementMarkers([])}highlightPromptElement(e){if(!e.element_context?.selector)return void console.warn("Prompt has no element context");this.elementSelector.highlightElement(e.element_context.selector)?(this.state.setHighlightedPromptId(e.id),this.state.setOverlayMode("single")):console.warn("Element not found for prompt:",e.id)}setupGlobalRightClick(e){return this.elementSelector.setupGlobalRightClick(e)}setupGlobalRightClickWithPosition(e){return this.elementSelector.setupGlobalRightClickWithPosition(e)}async login(){if(!this.authManager)throw new Error("Authentication is not enabled. Set requireAuth: true in config.");try{const e=await this.authManager.login();return this.config.onLogin?.(e.user),e.user}catch(e){throw e}}async logout(){if(!this.authManager)throw new Error("Authentication is not enabled.");await this.authManager.logout(),this.config.onLogout?.()}isAuthenticated(){return this.state.getState().isAuthenticated}getUser(){return this.state.getState().user}isAuthRequired(){return this.config.requireAuth||!1}}function en(e,t,r){const n=document.createElement(e);return t&&Object.entries(t).forEach(([e,t])=>{void 0!==t&&!1!==t&&("className"===e?n.className=t:e.startsWith("on")&&"string"==typeof t||(!0===t?n.setAttribute(e,""):n.setAttribute(e,t)))}),r&&r.forEach(e=>{"string"==typeof e?n.appendChild(document.createTextNode(e)):n.appendChild(e)}),n}function tn(e,t,r,n){return e.addEventListener(t,r,n),()=>e.removeEventListener(t,r,n)}function rn(e,t){Object.assign(e.style,t)}function nn(e){e?.parentNode?.removeChild(e)}class sn{constructor(e){this.state=null,this.elements={container:document.createElement("div"),panel:null,trigger:null,promptInput:null,logStream:null,statusBar:null,statusBarMinimized:null,contextMenu:null,elementMarkers:null},this.unsubscribe=null,this.cleanupFunctions=[],this.isMinimized=!1,this.showStatusBar=!0,this.statusBarMinimized=!1,this.lastCompletedPrompt=null,this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,this.builderTerminalCollapsed=!1,this.builderMessages=[],this.builderLastOutputCount=0,this.contextMenuState={isOpen:!1,position:{x:0,y:0},element:null},this.globalRightClickCleanup=null,this.config=e,this.currentMode=e.mode||"widget",this.client=new Zr(e),function(e,t){const r=document.getElementById(t);if(r)return r;const n=document.createElement("style");n.id=t,n.textContent=e,document.head.appendChild(n)}("\n/* Orquesta Embed SDK Styles - Auto-injected */\n/* These styles are scoped to orquesta-* classes to avoid conflicts */\n\n/* Reset for Orquesta elements */\n[class^=\"orquesta-\"],\n[class*=\" orquesta-\"] {\n box-sizing: border-box;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n/* Base colors */\n.orquesta-embed-panel {\n --orq-bg: #18181b;\n --orq-bg-secondary: #27272a;\n --orq-border: #3f3f46;\n --orq-text: #fafafa;\n --orq-text-muted: #a1a1aa;\n --orq-primary: #3b82f6;\n --orq-success: #22c55e;\n --orq-warning: #eab308;\n --orq-error: #ef4444;\n}\n\n/* Scrollbar styling */\n.orquesta-embed-panel ::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-track {\n background: transparent;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb {\n background: #3f3f46;\n border-radius: 3px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb:hover {\n background: #52525b;\n}\n\n/* Animations */\n@keyframes orquesta-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n@keyframes orquesta-pulse {\n 0%, 100% {\n opacity: 1;\n }\n 50% {\n opacity: 0.5;\n }\n}\n\n.orquesta-embed-panel .animate-spin {\n animation: orquesta-spin 1s linear infinite;\n}\n\n.orquesta-embed-panel .animate-pulse {\n animation: orquesta-pulse 2s ease-in-out infinite;\n}\n\n/* Utility classes */\n.orquesta-embed-panel .line-clamp-1 {\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n.orquesta-embed-panel .line-clamp-2 {\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n/* Focus visible */\n.orquesta-embed-panel button:focus-visible,\n.orquesta-embed-panel input:focus-visible,\n.orquesta-embed-panel textarea:focus-visible {\n outline: 2px solid var(--orq-primary);\n outline-offset: 2px;\n}\n\n/* Element selector highlight animation */\n#orquesta-element-highlight {\n animation: orquesta-highlight-pulse 1.5s ease-in-out infinite;\n}\n\n@keyframes orquesta-highlight-pulse {\n 0%, 100% {\n box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4);\n }\n 50% {\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2);\n }\n}\n\n/* Tooltip */\n.orquesta-tooltip {\n position: absolute;\n z-index: 2147483647;\n padding: 4px 8px;\n background: #18181b;\n border: 1px solid #3f3f46;\n border-radius: 4px;\n font-size: 12px;\n color: #fafafa;\n pointer-events: none;\n white-space: nowrap;\n}\n\n/* Transitions */\n.orquesta-embed-panel * {\n transition-property: color, background-color, border-color, opacity, transform;\n transition-duration: 150ms;\n transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);\n}\n\n/* Panel entrance animation */\n.orquesta-embed-panel {\n animation: orquesta-panel-enter 0.2s ease-out;\n}\n\n@keyframes orquesta-panel-enter {\n from {\n opacity: 0;\n transform: scale(0.95) translateY(10px);\n }\n to {\n opacity: 1;\n transform: scale(1) translateY(0);\n }\n}\n\n/* Trigger button */\n.orquesta-embed-trigger {\n animation: orquesta-trigger-enter 0.3s ease-out;\n}\n\n@keyframes orquesta-trigger-enter {\n from {\n opacity: 0;\n transform: scale(0.8);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n}\n\n/* Log stream */\n.orquesta-log-stream {\n background: #0a0a0a;\n border: 1px solid #27272a;\n border-radius: 6px;\n padding: 8px;\n}\n\n/* Timeline item hover */\n.orquesta-timeline button:hover {\n transform: translateX(2px);\n}\n\n/* ============================================ */\n/* Tailwind class overrides - CRITICAL STYLES */\n/* These ensure styles work even when purged */\n/* ============================================ */\n\n/* Explicit background colors */\n.orquesta-embed-panel {\n background-color: #18181b !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel .bg-zinc-950 { background-color: #09090b !important; }\n.orquesta-embed-panel .bg-zinc-900 { background-color: #18181b !important; }\n.orquesta-embed-panel .bg-zinc-800 { background-color: #27272a !important; }\n.orquesta-embed-panel .bg-zinc-700 { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .bg-zinc-600 { background-color: #52525b !important; }\n\n/* Text colors */\n.orquesta-embed-panel .text-white { color: #fafafa !important; }\n.orquesta-embed-panel .text-zinc-100 { color: #f4f4f5 !important; }\n.orquesta-embed-panel .text-zinc-200 { color: #e4e4e7 !important; }\n.orquesta-embed-panel .text-zinc-300 { color: #d4d4d8 !important; }\n.orquesta-embed-panel .text-zinc-400 { color: #a1a1aa !important; }\n.orquesta-embed-panel .text-zinc-500 { color: #71717a !important; }\n.orquesta-embed-panel .text-red-400 { color: #f87171 !important; }\n.orquesta-embed-panel .text-red-300 { color: #fca5a5 !important; }\n.orquesta-embed-panel .text-green-400 { color: #4ade80 !important; }\n.orquesta-embed-panel .text-green-500 { color: #22c55e !important; }\n.orquesta-embed-panel .text-blue-400 { color: #60a5fa !important; }\n.orquesta-embed-panel .text-blue-500 { color: #3b82f6 !important; }\n.orquesta-embed-panel .text-yellow-400 { color: #facc15 !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .text-orange-400 { color: #fb923c !important; }\n.orquesta-embed-panel .text-gray-800 { color: #1f2937 !important; }\n\n/* Border colors */\n.orquesta-embed-panel .border-zinc-700 { border-color: #3f3f46 !important; }\n.orquesta-embed-panel .border-zinc-800 { border-color: #27272a !important; }\n.orquesta-embed-panel .border-red-800 { border-color: #991b1b !important; }\n\n/* Background colors for buttons and UI */\n.orquesta-embed-panel .bg-blue-500 { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .bg-blue-600 { background-color: #2563eb !important; }\n.orquesta-embed-panel .bg-green-400 { background-color: #4ade80 !important; }\n.orquesta-embed-panel .bg-green-500 { background-color: #22c55e !important; }\n.orquesta-embed-panel .bg-green-600 { background-color: #16a34a !important; }\n.orquesta-embed-panel .bg-red-500 { background-color: #ef4444 !important; }\n.orquesta-embed-panel .bg-red-600 { background-color: #dc2626 !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-red-900\\/30 { background-color: rgba(127, 29, 29, 0.3) !important; }\n.orquesta-embed-panel .bg-white { background-color: #ffffff !important; }\n\n/* Hover states */\n.orquesta-embed-panel .hover\\:bg-zinc-700:hover { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .hover\\:bg-zinc-800:hover { background-color: #27272a !important; }\n.orquesta-embed-panel .hover\\:bg-blue-500:hover { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .hover\\:bg-blue-700:hover { background-color: #1d4ed8 !important; }\n.orquesta-embed-panel .hover\\:bg-gray-100:hover { background-color: #f3f4f6 !important; }\n.orquesta-embed-panel .hover\\:text-white:hover { color: #fafafa !important; }\n.orquesta-embed-panel .hover\\:text-zinc-300:hover { color: #d4d4d8 !important; }\n\n/* Form inputs */\n.orquesta-embed-panel input,\n.orquesta-embed-panel textarea {\n background-color: #27272a !important;\n border-color: #3f3f46 !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel input::placeholder,\n.orquesta-embed-panel textarea::placeholder {\n color: #71717a !important;\n}\n\n/* Buttons base */\n.orquesta-embed-panel button {\n background-color: transparent;\n}\n\n.orquesta-embed-panel button:hover {\n background-color: #3f3f46;\n}\n\n/* Rounded borders */\n.orquesta-embed-panel .rounded { border-radius: 0.25rem !important; }\n.orquesta-embed-panel .rounded-md { border-radius: 0.375rem !important; }\n.orquesta-embed-panel .rounded-lg { border-radius: 0.5rem !important; }\n.orquesta-embed-panel .rounded-xl { border-radius: 0.75rem !important; }\n.orquesta-embed-panel .rounded-full { border-radius: 9999px !important; }\n\n/* Border widths */\n.orquesta-embed-panel .border { border-width: 1px !important; }\n.orquesta-embed-panel .border-b { border-bottom-width: 1px !important; }\n.orquesta-embed-panel .border-t { border-top-width: 1px !important; }\n\n/* Padding */\n.orquesta-embed-panel .p-1 { padding: 0.25rem !important; }\n.orquesta-embed-panel .p-2 { padding: 0.5rem !important; }\n.orquesta-embed-panel .p-3 { padding: 0.75rem !important; }\n.orquesta-embed-panel .p-4 { padding: 1rem !important; }\n.orquesta-embed-panel .px-2 { padding-left: 0.5rem !important; padding-right: 0.5rem !important; }\n.orquesta-embed-panel .px-3 { padding-left: 0.75rem !important; padding-right: 0.75rem !important; }\n.orquesta-embed-panel .px-4 { padding-left: 1rem !important; padding-right: 1rem !important; }\n.orquesta-embed-panel .py-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; }\n.orquesta-embed-panel .py-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .py-3 { padding-top: 0.75rem !important; padding-bottom: 0.75rem !important; }\n\n/* Margin */\n.orquesta-embed-panel .m-1 { margin: 0.25rem !important; }\n.orquesta-embed-panel .m-2 { margin: 0.5rem !important; }\n.orquesta-embed-panel .mb-1 { margin-bottom: 0.25rem !important; }\n.orquesta-embed-panel .mb-2 { margin-bottom: 0.5rem !important; }\n.orquesta-embed-panel .mb-4 { margin-bottom: 1rem !important; }\n.orquesta-embed-panel .mt-1 { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .mt-2 { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .mt-3 { margin-top: 0.75rem !important; }\n.orquesta-embed-panel .mt-4 { margin-top: 1rem !important; }\n.orquesta-embed-panel .mr-1 { margin-right: 0.25rem !important; }\n.orquesta-embed-panel .mr-2 { margin-right: 0.5rem !important; }\n.orquesta-embed-panel .mx-1 { margin-left: 0.25rem !important; margin-right: 0.25rem !important; }\n\n/* Gap */\n.orquesta-embed-panel .gap-0\\.5 { gap: 0.125rem !important; }\n.orquesta-embed-panel .gap-1 { gap: 0.25rem !important; }\n.orquesta-embed-panel .gap-1\\.5 { gap: 0.375rem !important; }\n.orquesta-embed-panel .gap-2 { gap: 0.5rem !important; }\n.orquesta-embed-panel .gap-3 { gap: 0.75rem !important; }\n.orquesta-embed-panel .gap-4 { gap: 1rem !important; }\n\n/* Flex */\n.orquesta-embed-panel .flex { display: flex !important; }\n.orquesta-embed-panel .flex-col { flex-direction: column !important; }\n.orquesta-embed-panel .flex-1 { flex: 1 1 0% !important; }\n.orquesta-embed-panel .flex-shrink-0 { flex-shrink: 0 !important; }\n.orquesta-embed-panel .items-center { align-items: center !important; }\n.orquesta-embed-panel .items-start { align-items: flex-start !important; }\n.orquesta-embed-panel .justify-center { justify-content: center !important; }\n.orquesta-embed-panel .justify-between { justify-content: space-between !important; }\n\n/* Width/Height */\n.orquesta-embed-panel .w-full { width: 100% !important; }\n.orquesta-embed-panel .w-2 { width: 0.5rem !important; }\n.orquesta-embed-panel .w-3 { width: 0.75rem !important; }\n.orquesta-embed-panel .w-3\\.5 { width: 0.875rem !important; }\n.orquesta-embed-panel .w-4 { width: 1rem !important; }\n.orquesta-embed-panel .w-5 { width: 1.25rem !important; }\n.orquesta-embed-panel .w-6 { width: 1.5rem !important; }\n.orquesta-embed-panel .w-8 { width: 2rem !important; }\n.orquesta-embed-panel .w-16 { width: 4rem !important; }\n.orquesta-embed-panel .h-2 { height: 0.5rem !important; }\n.orquesta-embed-panel .h-3 { height: 0.75rem !important; }\n.orquesta-embed-panel .h-3\\.5 { height: 0.875rem !important; }\n.orquesta-embed-panel .h-4 { height: 1rem !important; }\n.orquesta-embed-panel .h-5 { height: 1.25rem !important; }\n.orquesta-embed-panel .h-6 { height: 1.5rem !important; }\n.orquesta-embed-panel .h-8 { height: 2rem !important; }\n.orquesta-embed-panel .h-16 { height: 4rem !important; }\n.orquesta-embed-panel .h-full { height: 100% !important; }\n.orquesta-embed-panel .max-w-20 { max-width: 5rem !important; }\n\n/* Font */\n.orquesta-embed-panel .text-xs { font-size: 0.75rem !important; line-height: 1rem !important; }\n.orquesta-embed-panel .text-sm { font-size: 0.875rem !important; line-height: 1.25rem !important; }\n.orquesta-embed-panel .text-lg { font-size: 1.125rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-xl { font-size: 1.25rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-2xl { font-size: 1.5rem !important; line-height: 2rem !important; }\n.orquesta-embed-panel .text-4xl { font-size: 2.25rem !important; line-height: 2.5rem !important; }\n.orquesta-embed-panel .font-medium { font-weight: 500 !important; }\n.orquesta-embed-panel .font-semibold { font-weight: 600 !important; }\n.orquesta-embed-panel .font-bold { font-weight: 700 !important; }\n.orquesta-embed-panel .text-center { text-align: center !important; }\n.orquesta-embed-panel .truncate { overflow: hidden !important; text-overflow: ellipsis !important; white-space: nowrap !important; }\n\n/* Opacity */\n.orquesta-embed-panel .opacity-25 { opacity: 0.25 !important; }\n.orquesta-embed-panel .opacity-50 { opacity: 0.5 !important; }\n.orquesta-embed-panel .opacity-75 { opacity: 0.75 !important; }\n\n/* Overflow */\n.orquesta-embed-panel .overflow-hidden { overflow: hidden !important; }\n.orquesta-embed-panel .overflow-y-auto { overflow-y: auto !important; }\n\n/* Shadow */\n.orquesta-embed-panel .shadow-xl { box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04) !important; }\n.orquesta-embed-panel .shadow-2xl { box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important; }\n.orquesta-embed-panel .shadow-lg { box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05) !important; }\n\n/* Position */\n.orquesta-embed-panel .fixed { position: fixed !important; }\n.orquesta-embed-panel .absolute { position: absolute !important; }\n.orquesta-embed-panel .relative { position: relative !important; }\n.orquesta-embed-panel .top-1 { top: 0.25rem !important; }\n.orquesta-embed-panel .right-1 { right: 0.25rem !important; }\n.orquesta-embed-panel .bottom-0 { bottom: 0 !important; }\n.orquesta-embed-panel .right-0 { right: 0 !important; }\n\n/* Z-index */\n.orquesta-embed-panel .z-\\[2147483647\\] { z-index: 2147483647 !important; }\n\n/* Cursor */\n.orquesta-embed-panel .cursor-move { cursor: move !important; }\n.orquesta-embed-panel .cursor-se-resize { cursor: se-resize !important; }\n.orquesta-embed-panel .cursor-not-allowed { cursor: not-allowed !important; }\n\n/* Select */\n.orquesta-embed-panel .select-none { user-select: none !important; }\n\n/* Disabled states */\n.orquesta-embed-panel .disabled\\:opacity-50:disabled { opacity: 0.5 !important; }\n.orquesta-embed-panel .disabled\\:cursor-not-allowed:disabled { cursor: not-allowed !important; }\n.orquesta-embed-panel .disabled\\:bg-blue-800:disabled { background-color: #1e40af !important; }\n.orquesta-embed-panel .disabled\\:bg-gray-300:disabled { background-color: #d1d5db !important; }\n\n/* Transition */\n.orquesta-embed-panel .transition-colors { transition-property: color, background-color, border-color !important; transition-duration: 150ms !important; }\n.orquesta-embed-panel .transition-all { transition-property: all !important; transition-duration: 150ms !important; }\n\n/* ============================================ */\n/* Action buttons & Comments - Timeline styles */\n/* ============================================ */\n\n/* Purple colors for \"Show on page\" button */\n.orquesta-embed-panel .text-purple-300 { color: #d8b4fe !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-purple-600\\/20 { background-color: rgba(147, 51, 234, 0.2) !important; }\n.orquesta-embed-panel .bg-purple-600\\/30 { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .border-purple-500\\/40 { border-color: rgba(168, 85, 247, 0.4) !important; }\n.orquesta-embed-panel .border-purple-500\\/60 { border-color: rgba(168, 85, 247, 0.6) !important; }\n.orquesta-embed-panel .hover\\:bg-purple-600\\/30:hover { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .hover\\:border-purple-500\\/60:hover { border-color: rgba(168, 85, 247, 0.6) !important; }\n\n/* Zinc with opacity for \"View output\" button */\n.orquesta-embed-panel .bg-zinc-700\\/50 { background-color: rgba(63, 63, 70, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600\\/50 { border-color: rgba(82, 82, 91, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600 { border-color: #52525b !important; }\n.orquesta-embed-panel .border-zinc-500 { border-color: #71717a !important; }\n.orquesta-embed-panel .hover\\:border-zinc-500:hover { border-color: #71717a !important; }\n\n/* Blue with opacity */\n.orquesta-embed-panel .bg-blue-500\\/20 { background-color: rgba(59, 130, 246, 0.2) !important; }\n.orquesta-embed-panel .border-blue-500\\/30 { border-color: rgba(59, 130, 246, 0.3) !important; }\n.orquesta-embed-panel .text-blue-300 { color: #93c5fd !important; }\n.orquesta-embed-panel .text-blue-300\\/70 { color: rgba(147, 197, 253, 0.7) !important; }\n\n/* Additional padding */\n.orquesta-embed-panel .py-1\\.5 { padding-top: 0.375rem !important; padding-bottom: 0.375rem !important; }\n.orquesta-embed-panel .py-0\\.5 { padding-top: 0.125rem !important; padding-bottom: 0.125rem !important; }\n.orquesta-embed-panel .px-1\\.5 { padding-left: 0.375rem !important; padding-right: 0.375rem !important; }\n.orquesta-embed-panel .px-2\\.5 { padding-left: 0.625rem !important; padding-right: 0.625rem !important; }\n.orquesta-embed-panel .pb-2 { padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .pb-3 { padding-bottom: 0.75rem !important; }\n.orquesta-embed-panel .pt-1 { padding-top: 0.25rem !important; }\n\n/* Space utilities */\n.orquesta-embed-panel .space-y-0\\.5 > * + * { margin-top: 0.125rem !important; }\n.orquesta-embed-panel .space-y-1 > * + * { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .space-y-2 > * + * { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .space-y-3 > * + * { margin-top: 0.75rem !important; }\n\n/* Focus states */\n.orquesta-embed-panel .focus\\:outline-none:focus { outline: none !important; }\n.orquesta-embed-panel .focus\\:ring-1:focus { box-shadow: 0 0 0 1px var(--orq-primary, #3b82f6) !important; }\n.orquesta-embed-panel .focus\\:ring-blue-500:focus { --tw-ring-color: #3b82f6 !important; }\n\n/* Placeholder colors */\n.orquesta-embed-panel .placeholder\\:text-zinc-500::placeholder { color: #71717a !important; }\n\n/* Text utilities */\n.orquesta-embed-panel .break-words { word-wrap: break-word !important; overflow-wrap: break-word !important; }\n.orquesta-embed-panel .italic { font-style: italic !important; }\n\n/* Negative margins */\n.orquesta-embed-panel .-mt-1 { margin-top: -0.25rem !important; }\n\n/* Max height */\n.orquesta-embed-panel .max-h-\\[400px\\] { max-height: 400px !important; }\n.orquesta-embed-panel .max-h-\\[150px\\] { max-height: 150px !important; }\n\n/* Font mono */\n.orquesta-embed-panel .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important; }\n\n/* Text sizes */\n.orquesta-embed-panel .text-\\[10px\\] { font-size: 10px !important; line-height: 1.4 !important; }\n.orquesta-embed-panel .text-\\[11px\\] { font-size: 11px !important; line-height: 1.4 !important; }\n\n/* Flex wrap */\n.orquesta-embed-panel .flex-wrap { flex-wrap: wrap !important; }\n\n/* Min width */\n.orquesta-embed-panel .min-w-0 { min-width: 0 !important; }\n\n/* ml-auto for comment button alignment */\n.orquesta-embed-panel .ml-auto { margin-left: auto !important; }\n\n/* Hidden utility */\n.orquesta-embed-panel .hidden { display: none !important; }\n\n/* SVG icon sizing */\n.orquesta-embed-panel svg { flex-shrink: 0; }\n\n/* Mobile responsive */\n@media (max-width: 480px) {\n .orquesta-embed-panel {\n position: fixed !important;\n left: 8px !important;\n right: 8px !important;\n bottom: 8px !important;\n top: auto !important;\n width: auto !important;\n max-height: 70vh !important;\n }\n}\n\n/* Builder Mode */\n.orquesta-builder{display:flex;flex-direction:column;width:100%;height:100vh;background:#0a0a0a;color:#fafafa;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;overflow:hidden}\n.orquesta-builder-header{display:flex;align-items:center;justify-content:space-between;height:48px;padding:0 16px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-header-left{display:flex;align-items:center;gap:12px}\n.orquesta-builder-header-right{display:flex;align-items:center;gap:8px}\n.orquesta-builder-logo{font-weight:700;font-size:14px;color:#fafafa;letter-spacing:-0.02em}\n.orquesta-builder-project{font-size:13px;color:#a1a1aa}\n.orquesta-builder-status{display:flex;align-items:center;gap:6px;font-size:12px;color:#a1a1aa}\n.orquesta-builder-status-dot{width:8px;height:8px;border-radius:50%}\n.orquesta-builder-main{display:flex;flex:1;min-height:0}\n.orquesta-builder-chat{display:flex;flex-direction:column;width:380px;min-width:300px;max-width:50%;border-right:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}\n.orquesta-builder-chat-input{padding:12px 16px;border-top:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-input textarea{width:100%;min-height:60px;max-height:200px;padding:10px 12px;background:#27272a;border:1px solid #3f3f46;border-radius:8px;color:#fafafa;font-size:13px;resize:vertical;outline:none;font-family:inherit}\n.orquesta-builder-chat-input textarea:focus{border-color:#3b82f6}\n.orquesta-builder-chat-input-actions{display:flex;justify-content:space-between;align-items:center;margin-top:8px}\n.orquesta-builder-preview{flex:1;display:flex;flex-direction:column;min-width:0}\n.orquesta-builder-preview-bar{display:flex;align-items:center;height:36px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;gap:8px;flex-shrink:0}\n.orquesta-builder-preview-url{flex:1;padding:4px 10px;background:#27272a;border:1px solid #3f3f46;border-radius:6px;color:#a1a1aa;font-size:12px;font-family:'SF Mono','Fira Code',monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.orquesta-builder-preview-iframe{flex:1;width:100%;border:none;background:#fff}\n.orquesta-builder-terminal{height:200px;min-height:100px;max-height:50vh;border-top:1px solid #27272a;background:#0a0a0a;display:flex;flex-direction:column;flex-shrink:0}\n.orquesta-builder-terminal-header{display:flex;align-items:center;justify-content:space-between;height:32px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-terminal-title{font-size:12px;font-weight:600;color:#a1a1aa;text-transform:uppercase;letter-spacing:0.05em}\n.orquesta-builder-terminal-output{flex:1;overflow-y:auto;padding:8px 12px;font-family:'SF Mono','Fira Code','Cascadia Code',monospace;font-size:12px;line-height:1.5}\n.orquesta-builder-terminal.collapsed{height:32px;min-height:32px}\n.orquesta-builder-terminal.collapsed .orquesta-builder-terminal-output{display:none}\n.orquesta-builder-msg{max-width:90%;padding:10px 14px;border-radius:12px;font-size:13px;line-height:1.5;word-break:break-word}\n.orquesta-builder-msg-user{align-self:flex-end;background:#3b82f6;color:#fff;border-bottom-right-radius:4px}\n.orquesta-builder-msg-system{align-self:flex-start;background:#27272a;color:#fafafa;border-bottom-left-radius:4px}\n.orquesta-builder-msg-status{align-self:center;background:transparent;color:#71717a;font-size:12px;padding:4px 0}\n.orquesta-builder-resizer-h{width:4px;cursor:col-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-h:hover{background:#3b82f6}\n.orquesta-builder-resizer-v{height:4px;cursor:row-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-v:hover{background:#3b82f6}\n.orquesta-builder button{background:transparent;border:none;color:#a1a1aa;cursor:pointer;padding:4px 8px;border-radius:4px;font-size:12px}\n.orquesta-builder button:hover{background:#27272a;color:#fafafa}\n.orquesta-builder-btn-primary{background:#3b82f6!important;color:#fff!important;font-weight:500;padding:6px 16px!important;border-radius:6px!important}\n.orquesta-builder-btn-primary:hover{background:#2563eb!important}\n.orquesta-builder-btn-primary:disabled{opacity:0.5;cursor:not-allowed}\n@media(max-width:768px){.orquesta-builder-main{flex-direction:column}.orquesta-builder-chat{width:100%;max-width:100%;height:50%;border-right:none;border-bottom:1px solid #27272a}.orquesta-builder-resizer-h{display:none}}\n","orquesta-embed-styles"),this.elements.container.id="orquesta-widget-container",document.body.appendChild(this.elements.container),!1!==e.enableGlobalRightClick&&this.setupGlobalRightClick()}setupGlobalRightClick(){this.globalRightClickCleanup=this.client.setupGlobalRightClickWithPosition((e,t)=>{this.client.getElementSelector().deactivate(),this.client.getElementSelector().highlightSelectedElement(e.selector),this.contextMenuState={isOpen:!0,position:t,element:e},this.render()})}async init(){console.log("[Orquesta Embed] v0.1.38"),this.unsubscribe=this.client.subscribe(e=>{this.state=e,this.render()});try{await this.client.connect()}catch(e){throw this.renderError(e instanceof Error?e.message:"Connection failed"),e}}render(){this.state&&("builder"!==this.currentMode?(this.elements.container.innerHTML="",this.cleanupFunctions.forEach(e=>e()),this.cleanupFunctions=[],"completed"!==this.state.currentPrompt?.status&&"failed"!==this.state.currentPrompt?.status||(this.lastCompletedPrompt=this.state.currentPrompt),this.showStatusBar&&this.renderStatusBar(),this.state.isOpen&&!this.isMinimized||this.renderTrigger(),this.state.isOpen&&!this.isMinimized&&this.renderPanel(),this.state.isSelectingElement&&this.renderElementInspector(),this.contextMenuState.isOpen&&this.renderContextMenu(),"all"===this.state.overlayMode&&this.state.elementMarkers.length>0&&this.renderElementMarkers()):this.renderBuilder())}renderTrigger(){const e=this.config.position||"bottom-right",[t,r]=e.split("-"),n=en("button",{className:"orquesta-embed-trigger"},["⬡"]);if(rn(n,{position:"fixed",zIndex:"2147483647",padding:"12px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"50%",boxShadow:"0 10px 25px rgba(0,0,0,0.3)",cursor:"pointer",fontSize:"20px",["top"===t?"top":"bottom"]:"20px",["left"===r?"left":"right"]:"20px"}),this.state?.agentOnline){const e=en("span");rn(e,{position:"absolute",top:"4px",right:"4px",width:"8px",height:"8px",background:"#22c55e",borderRadius:"50%"}),n.appendChild(e)}const s=tn(n,"click",()=>{this.isMinimized=!1,this.client.open()});this.cleanupFunctions.push(s),this.elements.container.appendChild(n),this.elements.trigger=n}renderPanel(){if(!this.state)return;const e=en("div",{className:"orquesta-embed-panel"});rn(e,{position:"fixed",zIndex:"2147483647",width:"400px",height:"500px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"8px",boxShadow:"0 25px 50px rgba(0,0,0,0.5)",display:"flex",flexDirection:"column",overflow:"hidden",right:"20px",bottom:"20px"});const t=this.createHeader();e.appendChild(t);const r=this.createTabs();if(e.appendChild(r),this.state?.connectionError){const t=en("div");rn(t,{margin:"8px 12px",padding:"8px 12px",background:"rgba(127, 29, 29, 0.3)",border:"1px solid rgba(239, 68, 68, 0.3)",borderRadius:"8px",display:"flex",alignItems:"center",gap:"8px"});const r=en("span",{},["⚠️"]);rn(r,{fontSize:"12px"});const n=en("span",{},[this.state.connectionError]);rn(n,{fontSize:"11px",color:"#fca5a5"}),t.appendChild(r),t.appendChild(n),e.appendChild(t)}if(!this.state?.isConnected&&!this.state?.connectionError){const t=en("div");rn(t,{margin:"8px 12px",padding:"8px 12px",background:"rgba(113, 63, 18, 0.3)",border:"1px solid rgba(234, 179, 8, 0.3)",borderRadius:"8px",display:"flex",alignItems:"center",gap:"8px"});const r=en("span",{},["ℹ️"]);rn(r,{fontSize:"12px"});const n=en("span",{},["Reconnecting to Orquesta..."]);rn(n,{fontSize:"11px",color:"#fcd34d"}),t.appendChild(r),t.appendChild(n),e.appendChild(t)}const n=en("div");if(rn(n,{flex:"1",overflowY:"auto",padding:"12px"}),this.state?.requireAuth&&!this.state?.isAuthenticated){const e=this.createAuthOverlay();n.appendChild(e)}else{const e=this.createContent();n.appendChild(e)}e.appendChild(n),this.elements.container.appendChild(e),this.elements.panel=e}createAuthOverlay(){const e=en("div");rn(e,{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",textAlign:"center",padding:"16px"});const t=en("div");rn(t,{width:"64px",height:"64px",borderRadius:"50%",background:"#27272a",display:"flex",alignItems:"center",justifyContent:"center",marginBottom:"16px"});const r=en("span",{},["🔒"]);rn(r,{fontSize:"28px"}),t.appendChild(r),e.appendChild(t);const n=en("h3",{},["Sign in to continue"]);rn(n,{color:"white",fontWeight:"600",margin:"0 0 8px 0",fontSize:"16px"}),e.appendChild(n);const s=en("p",{},["You need to sign in to submit prompts to this project."]);if(rn(s,{color:"#a1a1aa",fontSize:"13px",margin:"0 0 16px 0"}),e.appendChild(s),this.state?.authError){const t=en("div",{},[this.state.authError]);rn(t,{marginBottom:"16px",padding:"8px 12px",background:"rgba(127, 29, 29, 0.3)",border:"1px solid #7f1d1d",borderRadius:"6px",color:"#fca5a5",fontSize:"12px"}),e.appendChild(t)}const i=en("button");if(rn(i,{display:"flex",alignItems:"center",gap:"8px",padding:"10px 20px",background:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"500",fontSize:"14px",color:"#374151"}),this.state?.isAuthenticating){const e=en("span",{},["⏳"]),t=en("span",{},["Signing in..."]);i.appendChild(e),i.appendChild(t),i.style.opacity="0.7"}else{const e=en("span",{},["G"]);rn(e,{fontWeight:"bold",color:"#4285f4"});const t=en("span",{},["Continue with Google"]);i.appendChild(e),i.appendChild(t)}const o=tn(i,"click",()=>{this.state?.isAuthenticating||this.client.login()});this.cleanupFunctions.push(o),e.appendChild(i);const a=en("p",{},["You must be a member of this project's organization."]);return rn(a,{color:"#71717a",fontSize:"11px",marginTop:"16px"}),e.appendChild(a),e}createHeader(){const e=en("div");rn(e,{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",background:"#27272a",borderBottom:"1px solid #3f3f46",cursor:"move"});const t=en("div");rn(t,{display:"flex",alignItems:"center",gap:"8px"});const r=en("span",{},["⬡"]);rn(r,{fontSize:"16px"});const n=en("span",{},["Orquesta"]);if(rn(n,{fontWeight:"600",color:"white",fontSize:"14px"}),t.appendChild(r),t.appendChild(n),this.state?.projectName){const e=en("span",{},[`• ${this.state.projectName}`]);rn(e,{fontSize:"12px",color:"#a1a1aa"}),t.appendChild(e)}const s=en("div");if(rn(s,{display:"flex",alignItems:"center",gap:"4px"}),this.state?.requireAuth)if(this.state.isAuthenticated&&this.state.user){const e=en("div");if(rn(e,{display:"flex",alignItems:"center",gap:"6px",marginRight:"8px"}),this.state.user.avatar_url){const t=en("img",{src:this.state.user.avatar_url});rn(t,{width:"20px",height:"20px",borderRadius:"50%"}),e.appendChild(t)}else{const t=en("div",{},[this.state.user.full_name?.[0]?.toUpperCase()||"?"]);rn(t,{width:"20px",height:"20px",borderRadius:"50%",background:"#52525b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",color:"white"}),e.appendChild(t)}const t=en("span",{},[this.state.user.full_name||"User"]);rn(t,{fontSize:"12px",color:"#d4d4d8",maxWidth:"80px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),e.appendChild(t);const r=en("button",{},["↪"]);rn(r,{padding:"4px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",fontSize:"12px"});const n=tn(r,"click",()=>this.client.logout());this.cleanupFunctions.push(n),e.appendChild(r),s.appendChild(e)}else{const e=en("button",{},[this.state?.isAuthenticating?"...":"Sign in"]);rn(e,{padding:"4px 8px",marginRight:"8px",background:"#2563eb",border:"none",borderRadius:"4px",color:"white",cursor:"pointer",fontSize:"11px"});const t=tn(e,"click",()=>this.client.login());this.cleanupFunctions.push(t),s.appendChild(e)}const i=en("span");rn(i,{width:"8px",height:"8px",borderRadius:"50%",marginRight:"4px",background:this.state?.isConnected?this.state?.agentOnline?"#22c55e":"#71717a":"#ef4444"}),i.title=this.state?.isConnected?this.state?.agentOnline?"Agent online":"Agent offline":"Not connected",s.appendChild(i);const o=en("button",{},["🎯"]);rn(o,{padding:"4px",background:this.state?.rightClickEnabled?"#16a34a":"#3f3f46",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"12px"}),o.title=this.state?.rightClickEnabled?"Right-click enabled":"Right-click disabled";const a=tn(o,"click",()=>{if(this.state){const e=!this.state.rightClickEnabled;this.state.rightClickEnabled=e,e?this.globalRightClickCleanup||this.setupGlobalRightClick():this.globalRightClickCleanup&&(this.globalRightClickCleanup(),this.globalRightClickCleanup=null),this.render()}});this.cleanupFunctions.push(a),s.appendChild(o);const l=en("div");rn(l,{display:"flex",gap:"2px",margin:"0 4px",padding:"2px",background:"#27272a",borderRadius:"4px"});[{mode:"off",icon:"👁️🗨️",title:"Overlay off"},{mode:"single",icon:"👁️",title:"Show selected prompt"},{mode:"all",icon:"📍",title:"Show all prompts"}].forEach(({mode:e,icon:t,title:r})=>{const n=en("button",{},[t]),s=this.state?.overlayMode===e;rn(n,{padding:"4px",background:s?"off"===e?"#3f3f46":"single"===e?"#2563eb":"#7c3aed":"transparent",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"10px",opacity:s?"1":"0.5"}),n.title=r;const i=tn(n,"click",()=>{this.state&&(this.state.overlayMode=e,"all"===e?this.state.elementMarkers=this.state.promptHistory.filter(e=>e.element_context?.selector).map(e=>{let t=null;try{t=document.querySelector(e.element_context.selector)}catch{}return{promptId:e.id,selector:e.element_context.selector,rect:t?.getBoundingClientRect()||null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}}):"off"===e&&(this.state.elementMarkers=[],this.state.highlightedPromptId=null,this.client.getElementSelector().removeHighlight()),this.render())});this.cleanupFunctions.push(i),l.appendChild(n)}),s.appendChild(l);const c=this.createIconButton("⛶",()=>{this.switchMode("builder")});c.title="Expand to builder mode",s.appendChild(c);const h=this.createIconButton("−",()=>{this.isMinimized=!0,this.render()});s.appendChild(h);const u=this.createIconButton("×",()=>{this.client.close()});return s.appendChild(u),e.appendChild(t),e.appendChild(s),e}createIconButton(e,t){const r=en("button",{},[e]);rn(r,{padding:"4px 8px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",borderRadius:"4px",fontSize:"16px"});const n=tn(r,"click",t);this.cleanupFunctions.push(n);const s=tn(r,"mouseenter",()=>{rn(r,{background:"#3f3f46",color:"white"})}),i=tn(r,"mouseleave",()=>{rn(r,{background:"transparent",color:"#a1a1aa"})});return this.cleanupFunctions.push(s,i),r}createTabs(){const e=en("div");rn(e,{padding:"8px 12px",borderBottom:"1px solid #27272a"});const t=en("div");rn(t,{display:"flex",gap:"4px",padding:"4px",background:"#27272a",borderRadius:"8px"});return["prompts","timeline","logs"].forEach(e=>{const r=this.state?.activeTab===e,n=en("button",{},[e.charAt(0).toUpperCase()+e.slice(1)]);rn(n,{flex:"1",padding:"6px 12px",background:r?"#3f3f46":"transparent",border:"none",borderRadius:"6px",color:r?"white":"#a1a1aa",cursor:"pointer",fontSize:"13px",fontWeight:"500"});const s=tn(n,"click",()=>{this.state&&(this.state.activeTab=e,this.render())});this.cleanupFunctions.push(s),t.appendChild(n)}),e.appendChild(t),e}createContent(){const e=en("div");switch(this.state?.activeTab){case"prompts":e.appendChild(this.createPromptsTab());break;case"timeline":e.appendChild(this.createTimelineTab());break;case"logs":e.appendChild(this.createLogsTab())}return e}createPromptsTab(){const e=en("div"),t=async()=>{const e=this.elements.promptInput?.value.trim();if(e&&this.state?.agentOnline&&!this.state?.isSubmitting)try{const t=this.state?.selectedElement?{elementContext:this.state.selectedElement}:void 0;await this.client.submitPrompt(e,t),this.elements.promptInput&&(this.elements.promptInput.value=""),this.state&&(this.state.selectedElement=null,this.render())}catch(e){console.error("Failed to submit prompt:",e)}},r=en("textarea",{placeholder:this.state?.agentOnline?"What would you like to do?":"Agent is offline..."});rn(r,{width:"100%",minHeight:"80px",padding:"8px 12px",background:"#27272a",border:"1px solid #3f3f46",borderRadius:"6px",color:"white",fontSize:"14px",resize:"none",outline:"none"}),r.disabled=!this.state?.agentOnline||this.state?.isSubmitting,this.elements.promptInput=r,e.appendChild(r);const n=tn(r,"keydown",e=>{const r=e;"Enter"===r.key&&(r.metaKey||r.ctrlKey)&&(r.preventDefault(),t())});this.cleanupFunctions.push(n);const s=en("div");if(rn(s,{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"}),this.state?.selectedElement){const e=this.createContextBadge("🎯",`<${this.state.selectedElement.tag}>${this.state.selectedElement.textContent?": "+this.state.selectedElement.textContent.slice(0,20)+(this.state.selectedElement.textContent.length>20?"...":""):""}`,"#1e3a5f","#3b82f6","#93c5fd",()=>{this.state&&(this.state.selectedElement=null,this.render())});s.appendChild(e)}if(this.state?.includeConsole){const e=this.createContextBadge("📋","Console logs","#422006","#eab308","#fcd34d",()=>{this.state&&(this.state.includeConsole=!1,this.render())});s.appendChild(e)}if(this.state?.includeNetwork){const e=this.createContextBadge("🌐","Network errors","#450a0a","#ef4444","#fca5a5",()=>{this.state&&(this.state.includeNetwork=!1,this.render())});s.appendChild(e)}if(this.state?.includeContext){const e=this.createContextBadge("🔗","Session outputs","#3b0764","#a855f7","#d8b4fe",()=>{this.state&&(this.state.includeContext=!1,this.render())});s.appendChild(e)}s.childNodes.length>0&&e.appendChild(s);const i=en("div");rn(i,{display:"flex",gap:"8px",marginTop:"8px"});const o=this.createContextButton(this.state?.selectedElement?"🎯 Element ✓":"🎯 Element",()=>{this.client.startElementSelection()},!!this.state?.selectedElement),a=this.createContextButton("📋 Logs",()=>{this.state&&(this.state.includeConsole=!this.state.includeConsole,this.render())},this.state?.includeConsole),l=this.createContextButton("🌐 Network",()=>{this.state&&(this.state.includeNetwork=!this.state.includeNetwork,this.render())},this.state?.includeNetwork),c=this.createContextButton("🔗 Context",()=>{this.state&&(this.state.includeContext=!this.state.includeContext,this.render())},this.state?.includeContext);i.appendChild(o),i.appendChild(a),i.appendChild(l),i.appendChild(c),e.appendChild(i);const h=en("div");rn(h,{display:"flex",justifyContent:"flex-end",marginTop:"12px"});const u=en("button",{},[this.state?.isSubmitting?"Running...":"Submit (⌘↵)"]);rn(u,{padding:"8px 16px",background:"#3b82f6",border:"none",borderRadius:"6px",color:"white",cursor:"pointer",fontWeight:"500",opacity:!this.state?.agentOnline||this.state?.isSubmitting?"0.5":"1"});const d=tn(u,"click",t);if(this.cleanupFunctions.push(d),h.appendChild(u),e.appendChild(h),this.state?.outputLines.length||this.state?.isSubmitting){const t=en("div");rn(t,{marginTop:"16px",paddingTop:"16px",borderTop:"1px solid #27272a"});const r=this.createLogStream(this.state?.outputLines||[]);t.appendChild(r),e.appendChild(t)}return e}createContextButton(e,t,r){const n=en("button",{},[e]);rn(n,{padding:"4px 8px",background:r?"#3f3f46":"transparent",border:"none",borderRadius:"4px",color:r?"white":"#a1a1aa",cursor:"pointer",fontSize:"12px"});const s=tn(n,"click",t);return this.cleanupFunctions.push(s),n}createContextBadge(e,t,r,n,s,i){const o=en("div");rn(o,{display:"flex",alignItems:"center",gap:"6px",padding:"4px 8px",background:r,border:`1px solid ${n}`,borderRadius:"6px",fontSize:"11px",color:s});const a=en("span",{},[e]),l=en("span",{},[t]),c=en("button",{},["×"]);rn(c,{marginLeft:"4px",background:"none",border:"none",color:s,cursor:"pointer",fontSize:"14px",padding:"0",lineHeight:"1"});const h=tn(c,"click",i);return this.cleanupFunctions.push(h),o.appendChild(a),o.appendChild(l),o.appendChild(c),o}createLogStream(e){const t=en("div",{className:"orquesta-log-stream"});if(rn(t,{maxHeight:"200px",overflowY:"auto",background:"#0a0a0a",border:"1px solid #27272a",borderRadius:"6px",padding:"8px",fontFamily:"monospace",fontSize:"11px"}),this.state?.isSubmitting){const e=en("div");rn(e,{color:"#3b82f6",padding:"4px 0",marginBottom:"4px"}),e.textContent="● Running...",t.appendChild(e)}return[...e].reverse().forEach(e=>{const r=en("div");rn(r,{display:"flex",gap:"8px",padding:"2px 0",color:"stderr"===e.type?"#ef4444":"tool"===e.type?"#3b82f6":"#d4d4d8"});const n=en("span",{},["stderr"===e.type?"✕":"tool"===e.type?"🔧":"›"]);rn(n,{opacity:"0.5",width:"16px",textAlign:"center"});const s=en("span",{},[e.content]);rn(s,{flex:"1",wordBreak:"break-all",whiteSpace:"pre-wrap"}),r.appendChild(n),r.appendChild(s),t.appendChild(r)}),this.elements.logStream=t,t}createTimelineTab(){const e=en("div");if(rn(e,{maxHeight:"400px",overflowY:"auto"}),!this.state?.promptHistory.length){const t=en("div",{},["No prompts yet. Right-click any element to start!"]);return rn(t,{textAlign:"center",padding:"32px",color:"#71717a",fontSize:"14px"}),e.appendChild(t),e}return this.state.promptHistory.forEach(t=>{const r=t.id===this.state?.currentPrompt?.id,n=t.id===this.state?.expandedPromptId,s=en("div");rn(s,{marginBottom:"8px",background:r?"#27272a":"#18181b",border:"1px solid "+(r?"#3b82f6":"#3f3f46"),borderRadius:"8px",transition:"border-color 0.2s"});const i=en("div");rn(i,{display:"flex",alignItems:"flex-start",gap:"10px",padding:"12px",cursor:"pointer"});const o=en("div"),a=t.author?.full_name||"Unknown",l=a[0]?.toUpperCase()||"?";if(t.author?.avatar_url){const e=en("img",{src:t.author.avatar_url});rn(e,{width:"28px",height:"28px",borderRadius:"50%"}),o.appendChild(e)}else rn(o,{width:"28px",height:"28px",borderRadius:"50%",background:"#52525b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:"600",color:"white"}),o.textContent=l;const c=en("div");rn(c,{flex:"1",minWidth:"0"});const h=en("div");rn(h,{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"});const u=en("span",{},[a]);rn(u,{fontSize:"12px",fontWeight:"500",color:"#d4d4d8"});const d=en("span",{},[this.formatDate(t.created_at)]);rn(d,{fontSize:"10px",color:"#71717a"}),h.appendChild(u),h.appendChild(d);const p=en("p",{},[t.content.slice(0,100)+(t.content.length>100?"...":"")]);rn(p,{color:"#e4e4e7",fontSize:"13px",margin:"0 0 8px 0",lineHeight:"1.4"});const m=en("div");if(rn(m,{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"}),t.git_commit_sha){const e=en("span",{},[`🔗 ${t.git_commit_sha.slice(0,7)}`]);rn(e,{padding:"2px 6px",background:"#1e3a5f",border:"1px solid #3b82f6",borderRadius:"4px",fontSize:"10px",color:"#93c5fd",fontFamily:"monospace"}),m.appendChild(e)}if(t.element_context){const e=en("span",{},[`🎯 <${t.element_context.tag}>`]);rn(e,{padding:"2px 6px",background:"rgba(59, 130, 246, 0.2)",border:"1px solid rgba(59, 130, 246, 0.3)",borderRadius:"4px",fontSize:"10px",color:"#60a5fa"}),m.appendChild(e)}if((t.comment_count||0)>0){const e=en("span",{},[`💬 ${t.comment_count}`]);rn(e,{padding:"2px 6px",background:"#27272a",borderRadius:"4px",fontSize:"10px",color:"#a1a1aa"}),m.appendChild(e)}c.appendChild(h),c.appendChild(p),c.appendChild(m);const g=en("div");rn(g,{display:"flex",alignItems:"center",gap:"6px",flexShrink:"0"});const f=en("span");rn(f,{width:"8px",height:"8px",borderRadius:"50%",background:"completed"===t.status?"#22c55e":"failed"===t.status?"#ef4444":"running"===t.status?"#3b82f6":"#71717a"});const b=en("span",{},[t.status]);rn(b,{padding:"2px 8px",background:"completed"===t.status?"#14532d":"failed"===t.status?"#7f1d1d":"running"===t.status?"#1e3a5f":"#27272a",color:"completed"===t.status?"#4ade80":"failed"===t.status?"#f87171":"running"===t.status?"#60a5fa":"#a1a1aa",borderRadius:"9999px",fontSize:"10px",fontWeight:"500"}),g.appendChild(f),g.appendChild(b),i.appendChild(o),i.appendChild(c),i.appendChild(g),s.appendChild(i);const w="completed"===t.status||"failed"===t.status||t.element_context,y=en("div");if(rn(y,{display:w?"flex":"none",alignItems:"center",gap:"8px",padding:"0 12px 10px 50px"}),t.element_context){const e=en("button",{},["👁 Show on page"]);rn(e,{padding:"4px 10px",background:"rgba(124, 58, 237, 0.2)",border:"1px solid rgba(124, 58, 237, 0.4)",borderRadius:"6px",color:"#c4b5fd",fontSize:"11px",cursor:"pointer"});const r=tn(e,"click",e=>{if(e.stopPropagation(),t.element_context){this.client.getElementSelector().highlightSelectedElement(t.element_context.selector);try{const e=document.querySelector(t.element_context.selector);e?.scrollIntoView({behavior:"smooth",block:"center"})}catch{}}});this.cleanupFunctions.push(r),y.appendChild(e)}if("completed"===t.status||"failed"===t.status){const e=en("button",{},[n?"📄 Hide output":"📄 View output"]);rn(e,{padding:"4px 10px",background:n?"#3f3f46":"rgba(63, 63, 70, 0.5)",border:"1px solid rgba(63, 63, 70, 0.5)",borderRadius:"6px",color:n?"white":"#d4d4d8",fontSize:"11px",cursor:"pointer"});const r=tn(e,"click",e=>{e.stopPropagation(),this.state&&(this.state.expandedPromptId=n?null:t.id,this.render())});this.cleanupFunctions.push(r),y.appendChild(e)}if(s.appendChild(y),n){const e=en("div");rn(e,{padding:"0 12px 12px 12px",borderTop:"1px solid #27272a",marginTop:"4px"});const r=en("div");rn(r,{marginTop:"8px",background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"150px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"});const n=this.state?.promptOutputs?.[t.id]||[];if(n.length>0)n.slice(-20).forEach(e=>{const t=en("div",{},[e.content]);rn(t,{color:"stderr"===e.type?"#ef4444":"tool"===e.type?"#3b82f6":"thinking"===e.type?"#71717a":"#d4d4d8",padding:"1px 0",fontStyle:"thinking"===e.type?"italic":"normal"}),r.appendChild(t)});else{const e=en("div",{},["No output recorded for this prompt"]);rn(e,{color:"#71717a",textAlign:"center",padding:"8px"}),r.appendChild(e)}e.appendChild(r),s.appendChild(e)}const v=tn(s,"mouseenter",()=>{r||rn(s,{borderColor:"#52525b"})}),x=tn(s,"mouseleave",()=>{r||rn(s,{borderColor:"#3f3f46"})});this.cleanupFunctions.push(v,x);const _=tn(i,"click",()=>{this.state&&t.element_context&&this.client.getElementSelector().highlightSelectedElement(t.element_context.selector)});this.cleanupFunctions.push(_),e.appendChild(s)}),e}createLogsTab(){const e=en("div"),t=en("div");rn(t,{marginBottom:"16px"});const r=en("div");rn(r,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const n=en("h3",{},["Agent Output"]);if(rn(n,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"}),this.state?.isSubmitting){const e=en("span",{},["Running..."]);rn(e,{fontSize:"11px",color:"#4ade80"}),r.appendChild(n),r.appendChild(e)}else r.appendChild(n);t.appendChild(r);const s=en("div");if(rn(s,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"150px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.outputLines.length)this.state.outputLines.slice(-30).forEach(e=>{const t=en("div",{},[e.content]);rn(t,{color:"stderr"===e.type?"#ef4444":"tool"===e.type?"#3b82f6":"#d4d4d8",padding:"1px 0",wordBreak:"break-all"}),s.appendChild(t)});else{const e=en("div",{},["No agent output yet"]);rn(e,{color:"#71717a",textAlign:"center",padding:"8px"}),s.appendChild(e)}t.appendChild(s),e.appendChild(t);const i=en("div");rn(i,{marginBottom:"16px"});const o=en("div");rn(o,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const a=en("h3",{},["Console Logs"]);rn(a,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"});const l=en("span",{},[`${this.state?.consoleLogs.length||0} entries`]);rn(l,{fontSize:"11px",color:"#71717a"}),o.appendChild(a),o.appendChild(l),i.appendChild(o);const c=en("div");if(rn(c,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"120px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.consoleLogs.length)this.state.consoleLogs.slice(-20).forEach(e=>{const t=en("div");rn(t,{color:"error"===e.level?"#ef4444":"warn"===e.level?"#eab308":"#d4d4d8",padding:"1px 0"}),t.textContent=`[${e.level}] ${e.message}`,c.appendChild(t)});else{const e=en("div",{},["No console logs captured"]);rn(e,{color:"#71717a",textAlign:"center",padding:"8px"}),c.appendChild(e)}i.appendChild(c),e.appendChild(i);const h=en("div"),u=en("div");rn(u,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const d=en("h3",{},["Network Requests"]);rn(d,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"});const p=en("span",{},[`${this.state?.networkLogs.length||0} requests`]);rn(p,{fontSize:"11px",color:"#71717a"}),u.appendChild(d),u.appendChild(p),h.appendChild(u);const m=en("div");if(rn(m,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"120px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.networkLogs.length)this.state.networkLogs.slice(-15).forEach(e=>{const t=en("div");rn(t,{display:"flex",gap:"8px",padding:"2px 0"});const r=en("span",{},[String(e.status||"...")]);rn(r,{color:e.status&&e.status>=400?"#ef4444":e.status&&e.status>=300?"#eab308":"#4ade80"});const n=en("span",{},[e.method]);rn(n,{color:"#a1a1aa"});const s=en("span",{},[e.url]);if(rn(s,{color:"#d4d4d8",flex:"1",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),t.appendChild(r),t.appendChild(n),t.appendChild(s),e.duration){const r=en("span",{},[`${e.duration}ms`]);rn(r,{color:"#71717a"}),t.appendChild(r)}m.appendChild(t)});else{const e=en("div",{},["No network requests captured"]);rn(e,{color:"#71717a",textAlign:"center",padding:"8px"}),m.appendChild(e)}return h.appendChild(m),e.appendChild(h),e}renderElementInspector(){const e=en("div",{className:"orquesta-element-inspector"});rn(e,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"});const t=en("div");rn(t,{position:"absolute",top:"16px",left:"50%",transform:"translateX(-50%)",pointerEvents:"auto",display:"flex",alignItems:"center",gap:"12px",padding:"8px 16px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"8px",boxShadow:"0 10px 25px rgba(0,0,0,0.3)"});const r=en("span",{},["Click on any element to select it, or right-click for options"]);rn(r,{fontSize:"13px",color:"#d4d4d8"});const n=en("button",{},["Cancel (Esc)"]);rn(n,{padding:"4px 12px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",fontSize:"13px"});const s=tn(n,"click",()=>{this.client.getElementSelector().deactivate()});this.cleanupFunctions.push(s),t.appendChild(r),t.appendChild(n),e.appendChild(t),this.elements.container.appendChild(e)}renderStatusBar(){if(!this.state)return;let e="idle";this.state.isConnected?this.state.agentOnline?this.state.isSubmitting||"running"===this.state.currentPrompt?.status?e="running":"completed"===this.state.currentPrompt?.status?e="completed":"failed"===this.state.currentPrompt?.status&&(e="failed"):e="offline":e="connecting";const t=(()=>{switch(e){case"connecting":return{bg:"#27272a",border:"#3f3f46",icon:"⟳",iconBg:"#3f3f46",text:"Connecting to Orquesta...",pulse:!0};case"offline":return{bg:"#27272a",border:"#ef4444",icon:"○",iconBg:"#7f1d1d",text:"Agent offline",pulse:!1};case"running":return{bg:"#172554",border:"#3b82f6",icon:"⟳",iconBg:"#1d4ed8",text:`Running: ${this.state?.currentPrompt?.content.slice(0,50)}${(this.state?.currentPrompt?.content.length||0)>50?"...":""}`,pulse:!0};case"completed":return{bg:"#14532d",border:"#22c55e",icon:"✓",iconBg:"#15803d",text:"Completed"+(this.state?.currentPrompt?.git_commit_sha?` • Commit ${this.state.currentPrompt.git_commit_sha.slice(0,7)}`:""),pulse:!1};case"failed":return{bg:"#450a0a",border:"#ef4444",icon:"✕",iconBg:"#b91c1c",text:"Prompt failed",pulse:!1};default:return{bg:"#18181b",border:"#3f3f46",icon:"⬡",iconBg:"#27272a",text:this.state?.projectName?`${this.state.projectName} • Ready`:"Orquesta Ready",pulse:!1}}})();if(this.statusBarMinimized){const r=en("div",{id:"orquesta-status-bar-minimized"});rn(r,{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483646",display:"flex",alignItems:"center",gap:"6px",padding:"6px 12px",backgroundColor:t.bg,border:`1px solid ${t.border}`,borderRadius:"20px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",cursor:"pointer",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const n=en("span");rn(n,{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"completed"===e?"#22c55e":"failed"===e?"#ef4444":"running"===e?"#3b82f6":"#71717a"});const s=en("span",{},["Orquesta"]);rn(s,{fontSize:"11px",color:"#d4d4d8",fontWeight:"500"}),r.appendChild(n),r.appendChild(s);const i=tn(r,"click",()=>{this.statusBarMinimized=!1,this.render()});return this.cleanupFunctions.push(i),this.elements.container.appendChild(r),void(this.elements.statusBarMinimized=r)}const r=en("div",{id:"orquesta-status-bar"});rn(r,{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483646",display:"flex",alignItems:"center",gap:"10px",padding:"8px 12px 8px 10px",backgroundColor:t.bg,border:`1px solid ${t.border}`,borderRadius:"10px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',maxWidth:"calc(100vw - 40px)"});const n=en("div");rn(n,{width:"28px",height:"28px",borderRadius:"6px",backgroundColor:t.iconBg,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:"0"});const s=en("span",{},[t.icon]);rn(s,{fontSize:"14px",color:"#ffffff"}),n.appendChild(s);const i=en("div");rn(i,{flex:"1",minWidth:"0"});const o=en("div",{},[t.text]);if(rn(o,{fontSize:"12px",fontWeight:"500",color:"#ffffff",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"400px"}),i.appendChild(o),"running"===e){const e=en("div");rn(e,{marginTop:"4px",height:"3px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"2px",overflow:"hidden"});const t=en("div");rn(t,{height:"100%",backgroundColor:"#3b82f6",borderRadius:"2px",width:"30%",animation:"orquesta-progress 2s ease-in-out infinite"}),e.appendChild(t),i.appendChild(e)}const a=en("button",{},["−"]);rn(a,{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",fontSize:"16px",flexShrink:"0"});const l=tn(a,"click",()=>{this.statusBarMinimized=!0,this.render()});this.cleanupFunctions.push(l);const c=en("button",{},["×"]);rn(c,{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",fontSize:"16px",flexShrink:"0"});const h=tn(c,"click",()=>{this.showStatusBar=!1,this.render()});this.cleanupFunctions.push(h),r.appendChild(n),r.appendChild(i),r.appendChild(a),r.appendChild(c);const u=en("style");u.textContent="\n @keyframes orquesta-progress {\n 0% { width: 0%; margin-left: 0%; }\n 50% { width: 40%; margin-left: 30%; }\n 100% { width: 0%; margin-left: 100%; }\n }\n ",r.appendChild(u),this.elements.container.appendChild(r),this.elements.statusBar=r,"completed"!==e&&"failed"!==e||setTimeout(()=>{this.showStatusBar&&!this.statusBarMinimized&&(this.statusBarMinimized=!0,this.render())},5e3)}renderContextMenu(){if(!this.contextMenuState.isOpen||!this.contextMenuState.element)return;const e=en("div",{className:"orquesta-context-menu"});rn(e,{position:"fixed",zIndex:"2147483648",left:`${this.contextMenuState.position.x}px`,top:`${this.contextMenuState.position.y}px`,width:"320px",backgroundColor:"#18181b",border:"1px solid #3f3f46",borderRadius:"12px",boxShadow:"0 25px 50px rgba(0, 0, 0, 0.5)",overflow:"hidden",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const t=en("div");rn(t,{padding:"12px",borderBottom:"1px solid #27272a",backgroundColor:"#27272a"});const r=en("div");rn(r,{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"});const n=en("span",{},["🎯"]),s=en("span",{},["Prompt about element"]);rn(s,{fontWeight:"600",color:"white",fontSize:"14px"}),r.appendChild(n),r.appendChild(s);const i=en("div");rn(i,{display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#3f3f46",borderRadius:"4px",fontSize:"11px",fontFamily:"ui-monospace, monospace",color:"#a1a1aa"});const o=en("span",{},[`<${this.contextMenuState.element.tag}>`]);if(rn(o,{color:"#60a5fa"}),i.appendChild(o),this.contextMenuState.element.className){const e=en("span",{},[`.${this.contextMenuState.element.className.split(" ")[0]}`]);rn(e,{color:"#4ade80"}),i.appendChild(e)}t.appendChild(r),t.appendChild(i);const a=en("div");rn(a,{padding:"12px"});const l=en("textarea",{placeholder:"What would you like to do with this element?"});rn(l,{width:"100%",minHeight:"80px",padding:"10px 12px",backgroundColor:"#27272a",border:"1px solid #3f3f46",borderRadius:"8px",color:"white",fontSize:"14px",resize:"none",outline:"none",marginBottom:"12px"});const c=en("div");rn(c,{display:"flex",gap:"8px",marginBottom:"12px"});const h=(e,t,r)=>{const n=en("button",{},[e]);rn(n,{flex:"1",padding:"6px 10px",backgroundColor:t?"#3f3f46":"transparent",border:"1px solid #3f3f46",borderRadius:"6px",color:t?"white":"#a1a1aa",fontSize:"12px",cursor:"pointer"});const s=tn(n,"click",r);return this.cleanupFunctions.push(s),n},u=h("📋 Logs "+(this.state?.includeConsole?"✓":""),this.state?.includeConsole||!1,()=>{this.state&&(this.state.includeConsole=!this.state.includeConsole,this.render())}),d=h("🌐 Network "+(this.state?.includeNetwork?"✓":""),this.state?.includeNetwork||!1,()=>{this.state&&(this.state.includeNetwork=!this.state.includeNetwork,this.render())});c.appendChild(u),c.appendChild(d);const p=en("div");rn(p,{display:"flex",gap:"8px"});const m=en("button",{},["Open Panel"]);rn(m,{flex:"1",padding:"8px 12px",backgroundColor:"#27272a",border:"1px solid #3f3f46",borderRadius:"6px",color:"#d4d4d8",fontSize:"13px",fontWeight:"500",cursor:"pointer"});const g=tn(m,"click",()=>{this.state&&this.contextMenuState.element&&(this.state.selectedElement=this.contextMenuState.element,this.state.isOpen=!0,this.state.activeTab="prompts"),this.closeContextMenu(),this.isMinimized=!1,this.client.open()});this.cleanupFunctions.push(g);const f=en("button",{},["Submit"]);rn(f,{flex:"1",padding:"8px 12px",backgroundColor:this.state?.agentOnline?"#3b82f6":"#3f3f46",border:"none",borderRadius:"6px",color:"white",fontSize:"13px",fontWeight:"500",cursor:this.state?.agentOnline?"pointer":"not-allowed",opacity:this.state?.agentOnline?"1":"0.5"});const b=tn(f,"click",async()=>{const e=l.value.trim();if(e&&this.state?.agentOnline&&this.contextMenuState.element)try{await this.client.submitPrompt(e,{elementContext:this.contextMenuState.element}),this.closeContextMenu(),this.isMinimized=!1,this.client.open()}catch(e){console.error("Failed to submit:",e)}});this.cleanupFunctions.push(b),p.appendChild(m),p.appendChild(f),a.appendChild(l),a.appendChild(c),a.appendChild(p),e.appendChild(t),e.appendChild(a);const w=tn(document,"click",t=>{e&&!e.contains(t.target)&&this.closeContextMenu()});this.cleanupFunctions.push(w);const y=tn(document,"keydown",e=>{"Escape"===e.key&&this.closeContextMenu()});this.cleanupFunctions.push(y),this.elements.container.appendChild(e),this.elements.contextMenu=e,setTimeout(()=>l.focus(),50)}closeContextMenu(){this.contextMenuState={isOpen:!1,position:{x:0,y:0},element:null},this.client.getElementSelector().removeSelectedHighlight(),this.render()}renderElementMarkers(){if(!this.state||"all"!==this.state.overlayMode)return;const e=en("div",{className:"orquesta-element-markers"});rn(e,{position:"fixed",inset:"0",zIndex:"2147483644",pointerEvents:"none"}),this.state.elementMarkers.forEach(t=>{if(!t.rect)return;const r=en("div");rn(r,{position:"fixed",left:`${t.rect.left}px`,top:`${t.rect.top}px`,width:`${t.rect.width}px`,height:`${t.rect.height}px`,border:"2px solid #7c3aed",borderRadius:"4px",backgroundColor:"rgba(124, 58, 237, 0.1)",pointerEvents:"auto",cursor:"pointer"});const n=en("div");rn(n,{position:"absolute",top:"-8px",right:"-8px",width:"20px",height:"20px",borderRadius:"50%",backgroundColor:"#7c3aed",color:"white",fontSize:"11px",fontWeight:"600",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'}),n.textContent="1",r.appendChild(n);const s=tn(r,"click",()=>{this.state&&(this.state.activeTab="timeline",this.state.expandedPromptId=t.promptId,this.client.open()),this.render()});this.cleanupFunctions.push(s);const i=en("div");rn(i,{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"8px",padding:"8px 12px",backgroundColor:"#18181b",border:"1px solid #3f3f46",borderRadius:"6px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",maxWidth:"250px",display:"none",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const o=en("div",{},[t.content.slice(0,80)+(t.content.length>80?"...":"")]);if(rn(o,{fontSize:"12px",color:"#d4d4d8"}),i.appendChild(o),t.author){const e=en("div",{},[`by ${t.author.full_name}`]);rn(e,{fontSize:"11px",color:"#71717a",marginTop:"4px"}),i.appendChild(e)}r.appendChild(i);const a=tn(r,"mouseenter",()=>{rn(i,{display:"block"})}),l=tn(r,"mouseleave",()=>{rn(i,{display:"none"})});this.cleanupFunctions.push(a,l),e.appendChild(r)}),this.elements.container.appendChild(e),this.elements.elementMarkers=e}renderError(e){const t=en("div",{className:"orquesta-embed-error"});rn(t,{position:"fixed",bottom:"16px",right:"16px",zIndex:"2147483647",padding:"16px",background:"#7f1d1d",border:"1px solid #991b1b",borderRadius:"8px",maxWidth:"300px"});const r=en("div",{},["Orquesta Error"]);rn(r,{fontWeight:"600",color:"white",marginBottom:"4px"});const n=en("div",{},[e]);rn(n,{color:"#fecaca",fontSize:"13px"}),t.appendChild(r),t.appendChild(n),this.elements.container.appendChild(t)}formatDate(e){const t=new Date(e),r=(new Date).getTime()-t.getTime(),n=Math.floor(r/6e4);return n<1?"Just now":n<60?`${n}m ago`:n<1440?`${Math.floor(n/60)}h ago`:`${Math.floor(n/1440)}d ago`}open(){this.isMinimized=!1,this.client.open()}close(){this.client.close()}toggle(){this.client.toggle()}startElementSelection(){this.client.startElementSelection()}async submitPrompt(e,t){return this.client.submitPrompt(e,t)}renderBuilder(){if(!this.state)return;this.builderRoot||this.createBuilderDOM();const e=this.builderRoot?.querySelector(".orquesta-builder-status-dot");e&&(e.style.background=this.state.agentOnline?"#22c55e":"#ef4444");const t=this.builderRoot?.querySelector(".orquesta-builder-status-text");if(t&&(t.textContent=this.state.agentOnline?"Agent online":"Agent offline"),this.state.currentPrompt){const e=this.state.currentPrompt;"running"!==e.status||this.builderMessages.some(t=>t.content===`Running: ${e.content.slice(0,80)}`)||this.builderMessages.push({role:"status",content:`Running: ${e.content.slice(0,80)}${e.content.length>80?"...":""}`}),"completed"!==e.status||this.builderMessages.some(e=>e.content.startsWith("Completed"))||(this.builderMessages.push({role:"status",content:"Completed successfully"}),this.builderPreviewFrame&&(this.builderPreviewFrame.src=this.builderPreviewFrame.src)),"failed"!==e.status||this.builderMessages.some(e=>e.content.startsWith("Failed"))||this.builderMessages.push({role:"status",content:"Failed — check terminal for details"})}this.updateBuilderMessages(),this.updateBuilderTerminal();const r=this.builderRoot?.querySelector(".orquesta-builder-submit");r&&(r.disabled=this.state.isSubmitting||!this.state.agentOnline)}createBuilderDOM(){this.config.container&&("string"==typeof this.config.container?document.querySelector(this.config.container)||document.body:this.config.container);const e=this.config.previewUrl||window.location.href,t=this.state?.projectName||"Project",r=en("div",{className:"orquesta-builder orquesta-embed-panel"}),n=en("div",{className:"orquesta-builder-header"}),s=en("div",{className:"orquesta-builder-header-left"});s.innerHTML=`\n <span class="orquesta-builder-logo">⬡ Orquesta</span>\n <span class="orquesta-builder-project">${this.escapeHtml(t)}</span>\n `;const i=en("div",{className:"orquesta-builder-header-right"});i.innerHTML=`\n <div class="orquesta-builder-status">\n <span class="orquesta-builder-status-dot" style="background:${this.state?.agentOnline?"#22c55e":"#ef4444"}"></span>\n <span class="orquesta-builder-status-text">${this.state?.agentOnline?"Agent online":"Agent offline"}</span>\n </div>\n `;const o=en("button");o.textContent="⊡",o.title="Collapse to widget mode",rn(o,{padding:"4px 8px",background:"transparent",border:"1px solid #3f3f46",borderRadius:"4px",color:"#a1a1aa",cursor:"pointer",fontSize:"14px",marginLeft:"8px"}),this.cleanupFunctions.push(tn(o,"click",()=>{this.switchMode("widget")})),this.cleanupFunctions.push(tn(o,"mouseenter",()=>{rn(o,{background:"#3f3f46",color:"white"})})),this.cleanupFunctions.push(tn(o,"mouseleave",()=>{rn(o,{background:"transparent",color:"#a1a1aa"})})),i.appendChild(o),n.appendChild(s),n.appendChild(i),r.appendChild(n);const a=en("div",{className:"orquesta-builder-main"}),l=en("div",{className:"orquesta-builder-chat"}),c=en("div",{className:"orquesta-builder-chat-messages"});c.innerHTML='\n <div class="orquesta-builder-msg orquesta-builder-msg-system">\n What would you like to build? Describe the feature or change and I\'ll implement it.\n </div>\n ',this.builderMsgContainer=c,l.appendChild(c);const h=en("div",{className:"orquesta-builder-chat-input"}),u=en("textarea",{placeholder:"Describe what you want to build..."});u.setAttribute("rows","3");const d=en("div",{className:"orquesta-builder-chat-input-actions"}),p=en("span");rn(p,{fontSize:"11px",color:"#71717a"}),p.textContent="Enter to send, Shift+Enter for newline";const m=en("button",{className:"orquesta-builder-btn-primary orquesta-builder-submit"});m.textContent="Send",m.disabled=!this.state?.agentOnline,d.appendChild(p),d.appendChild(m),h.appendChild(u),h.appendChild(d),l.appendChild(h);const g=()=>{const e=u.value.trim();e&&!this.state?.isSubmitting&&(u.value="",this.builderMessages.push({role:"user",content:e}),this.updateBuilderMessages(),this.client.submitPrompt(e).catch(e=>{this.builderMessages.push({role:"status",content:`Error: ${e.message}`}),this.updateBuilderMessages()}))};this.cleanupFunctions.push(tn(m,"click",g)),this.cleanupFunctions.push(tn(u,"keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),g())})),a.appendChild(l);const f=en("div",{className:"orquesta-builder-resizer-h"});let b=!1;this.cleanupFunctions.push(tn(f,"mousedown",()=>{b=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none"})),this.cleanupFunctions.push(tn(document,"mousemove",e=>{if(!b)return;const t=Math.max(300,Math.min(e.clientX,.5*window.innerWidth));l.style.width=`${t}px`})),this.cleanupFunctions.push(tn(document,"mouseup",()=>{b&&(b=!1,document.body.style.cursor="",document.body.style.userSelect="")})),a.appendChild(f);const w=en("div",{className:"orquesta-builder-preview"}),y=en("div",{className:"orquesta-builder-preview-bar"}),v=en("div");rn(v,{display:"flex",gap:"6px"}),v.innerHTML='\n <span style="width:12px;height:12px;border-radius:50%;background:#ef4444"></span>\n <span style="width:12px;height:12px;border-radius:50%;background:#eab308"></span>\n <span style="width:12px;height:12px;border-radius:50%;background:#22c55e"></span>\n ',y.appendChild(v);const x=en("div",{className:"orquesta-builder-preview-url"});x.textContent=e,y.appendChild(x);const _=en("button");_.textContent="↻",_.title="Refresh preview",this.cleanupFunctions.push(tn(_,"click",()=>{this.builderPreviewFrame&&(this.builderPreviewFrame.src=this.builderPreviewFrame.src)})),y.appendChild(_),w.appendChild(y);const k=en("iframe",{className:"orquesta-builder-preview-iframe"});k.src=e,k.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),this.builderPreviewFrame=k,w.appendChild(k),a.appendChild(w),r.appendChild(a);const S=en("div",{className:"orquesta-builder-resizer-v"});let C=!1;const E=en("div",{className:"orquesta-builder-terminal"+(this.builderTerminalCollapsed?" collapsed":"")});this.cleanupFunctions.push(tn(S,"mousedown",()=>{C=!0,document.body.style.cursor="row-resize",document.body.style.userSelect="none"})),this.cleanupFunctions.push(tn(document,"mousemove",e=>{if(!C)return;const t=Math.max(100,Math.min(window.innerHeight-e.clientY,.5*window.innerHeight));E.style.height=`${t}px`,this.builderTerminalCollapsed=!1,E.classList.remove("collapsed")})),this.cleanupFunctions.push(tn(document,"mouseup",()=>{C&&(C=!1,document.body.style.cursor="",document.body.style.userSelect="")})),r.appendChild(S);const T=en("div",{className:"orquesta-builder-terminal-header"}),O=en("span",{className:"orquesta-builder-terminal-title"});O.textContent="Terminal";const R=en("button");R.textContent=this.builderTerminalCollapsed?"▲":"▼",R.title="Toggle terminal",this.cleanupFunctions.push(tn(R,"click",()=>{this.builderTerminalCollapsed=!this.builderTerminalCollapsed,E.classList.toggle("collapsed",this.builderTerminalCollapsed),R.textContent=this.builderTerminalCollapsed?"▲":"▼"})),T.appendChild(O),T.appendChild(R),E.appendChild(T);const q=en("div",{className:"orquesta-builder-terminal-output"});this.builderTerminalOutput=q,E.appendChild(q),r.appendChild(E),this.elements.container.innerHTML="",this.elements.container.appendChild(r),this.builderRoot=r,rn(this.elements.container,{position:"fixed",top:"0",left:"0",right:"0",bottom:"0",zIndex:"2147483647"}),u.focus()}updateBuilderMessages(){if(!this.builderMsgContainer)return;const e=this.builderMsgContainer.querySelector(".orquesta-builder-msg-system");this.builderMsgContainer.innerHTML="",e&&this.builderMsgContainer.appendChild(e);for(const e of this.builderMessages){const t=en("div",{className:`orquesta-builder-msg orquesta-builder-msg-${e.role}`});t.textContent=e.content,this.builderMsgContainer.appendChild(t)}this.builderMsgContainer.scrollTop=this.builderMsgContainer.scrollHeight}updateBuilderTerminal(){if(!this.builderTerminalOutput||!this.state)return;const e=this.state.outputLines;if(e.length!==this.builderLastOutputCount){for(let t=this.builderLastOutputCount;t<e.length;t++){const r=e[t],n=en("div");rn(n,{color:this.getTerminalColor(r.type),whiteSpace:"pre-wrap",wordBreak:"break-all"}),n.textContent=r.content,this.builderTerminalOutput.appendChild(n)}this.builderLastOutputCount=e.length,this.builderTerminalOutput.scrollTop=this.builderTerminalOutput.scrollHeight}}getTerminalColor(e){switch(e){case"stderr":case"error":return"#ef4444";case"tool":case"tool_call":return"#3b82f6";case"tool_result":return"#22c55e";case"thinking":return"#71717a";case"system":return"#eab308";case"progress":return"#a78bfa";default:return"#d4d4d8"}}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}switchMode(e){this.currentMode!==e&&(this.currentMode=e,this.elements.container.innerHTML="",this.cleanupFunctions.forEach(e=>e()),this.cleanupFunctions=[],"widget"===e&&(this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,rn(this.elements.container,{position:"",top:"",left:"",right:"",bottom:""}),this.isMinimized=!1,this.client.open()),this.render())}setMode(e){this.switchMode(e)}destroy(){this.unsubscribe?.(),this.cleanupFunctions.forEach(e=>e()),this.globalRightClickCleanup&&(this.globalRightClickCleanup(),this.globalRightClickCleanup=null),this.client.disconnect(),this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,nn(this.elements.container),nn(function(e,t=document){return t.querySelector(e)}("#orquesta-embed-styles"))}showStatus(){this.showStatusBar=!0,this.statusBarMinimized=!1,this.render()}hideStatus(){this.showStatusBar=!1,this.render()}}const on={init(e){const t=new sn(e);return t.init().catch(console.error),t},OrquestaWidget:sn};return"undefined"!=typeof window&&(window.Orquesta=on),e.ConsoleCapture=Wr,e.ElementSelector=Jr,e.NetworkCapture=Kr,e.OrquestaEmbedClient=Zr,e.OrquestaWidget=sn,e.default=on,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
|