(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();function kh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qu={exports:{}},ii={},Ku={exports:{}},N={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Fr=Symbol.for("react.element"),Eh=Symbol.for("react.portal"),Th=Symbol.for("react.fragment"),bh=Symbol.for("react.strict_mode"),Ch=Symbol.for("react.profiler"),Oh=Symbol.for("react.provider"),xh=Symbol.for("react.context"),Rh=Symbol.for("react.forward_ref"),Ph=Symbol.for("react.suspense"),Ah=Symbol.for("react.memo"),jh=Symbol.for("react.lazy"),cl=Symbol.iterator;function Ih(e){return e===null||typeof e!="object"?null:(e=cl&&e[cl]||e["@@iterator"],typeof e=="function"?e:null)}var Gu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ju=Object.assign,Qu={};function Mn(e,t,n){this.props=e,this.context=t,this.refs=Qu,this.updater=n||Gu}Mn.prototype.isReactComponent={};Mn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Mn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Yu(){}Yu.prototype=Mn.prototype;function fa(e,t,n){this.props=e,this.context=t,this.refs=Qu,this.updater=n||Gu}var pa=fa.prototype=new Yu;pa.constructor=fa;Ju(pa,Mn.prototype);pa.isPureReactComponent=!0;var dl=Array.isArray,Xu=Object.prototype.hasOwnProperty,ga={current:null},Zu={key:!0,ref:!0,__self:!0,__source:!0};function ec(e,t,n){var r,s={},i=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(i=""+t.key),t)Xu.call(t,r)&&!Zu.hasOwnProperty(r)&&(s[r]=t[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,re=O[Q];if(0>>1;Qs(Oi,I))$ts(Jr,Oi)?(O[Q]=Jr,O[$t]=I,Q=$t):(O[Q]=Oi,O[Lt]=I,Q=Lt);else if($ts(Jr,I))O[Q]=Jr,O[$t]=I,Q=$t;else break e}}return j}function s(O,j){var I=O.sortIndex-j.sortIndex;return I!==0?I:O.id-j.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],u=[],c=1,p=null,h=3,m=!1,v=!1,y=!1,S=typeof setTimeout=="function"?setTimeout:null,f=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function g(O){for(var j=n(u);j!==null;){if(j.callback===null)r(u);else if(j.startTime<=O)r(u),j.sortIndex=j.expirationTime,t(l,j);else break;j=n(u)}}function w(O){if(y=!1,g(O),!v)if(n(l)!==null)v=!0,bi(E);else{var j=n(u);j!==null&&Ci(w,j.startTime-O)}}function E(O,j){v=!1,y&&(y=!1,f(x),x=-1),m=!0;var I=h;try{for(g(j),p=n(l);p!==null&&(!(p.expirationTime>j)||O&&!ze());){var Q=p.callback;if(typeof Q=="function"){p.callback=null,h=p.priorityLevel;var re=Q(p.expirationTime<=j);j=e.unstable_now(),typeof re=="function"?p.callback=re:p===n(l)&&r(l),g(j)}else r(l);p=n(l)}if(p!==null)var Gr=!0;else{var Lt=n(u);Lt!==null&&Ci(w,Lt.startTime-j),Gr=!1}return Gr}finally{p=null,h=I,m=!1}}var T=!1,b=null,x=-1,U=5,L=-1;function ze(){return!(e.unstable_now()-LO||125Q?(O.sortIndex=I,t(u,O),n(l)===null&&O===n(u)&&(y?(f(x),x=-1):y=!0,Ci(w,I-Q))):(O.sortIndex=re,t(l,O),v||m||(v=!0,bi(E))),O},e.unstable_shouldYield=ze,e.unstable_wrapCallback=function(O){var j=h;return function(){var I=h;h=j;try{return O.apply(this,arguments)}finally{h=I}}}})(ic);sc.exports=ic;var Hh=sc.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var qh=W,Re=Hh;function k(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),uo=Object.prototype.hasOwnProperty,Kh=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,fl={},pl={};function Gh(e){return uo.call(pl,e)?!0:uo.call(fl,e)?!1:Kh.test(e)?pl[e]=!0:(fl[e]=!0,!1)}function Jh(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Qh(e,t,n,r){if(t===null||typeof t>"u"||Jh(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ye(e,t,n,r,s,i,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=o}var ce={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ce[e]=new ye(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ce[t]=new ye(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ce[e]=new ye(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ce[e]=new ye(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){ce[e]=new ye(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ce[e]=new ye(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ce[e]=new ye(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ce[e]=new ye(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ce[e]=new ye(e,5,!1,e.toLowerCase(),null,!1,!1)});var va=/[\-:]([a-z])/g;function ya(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(va,ya);ce[t]=new ye(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(va,ya);ce[t]=new ye(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(va,ya);ce[t]=new ye(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ce[e]=new ye(e,1,!1,e.toLowerCase(),null,!1,!1)});ce.xlinkHref=new ye("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ce[e]=new ye(e,1,!1,e.toLowerCase(),null,!0,!0)});function wa(e,t,n,r){var s=ce.hasOwnProperty(t)?ce[t]:null;(s!==null?s.type!==0:r||!(2a||s[o]!==i[a]){var l=` `+s[o].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{Pi=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?nr(e):""}function Yh(e){switch(e.tag){case 5:return nr(e.type);case 16:return nr("Lazy");case 13:return nr("Suspense");case 19:return nr("SuspenseList");case 0:case 2:case 15:return e=Ai(e.type,!1),e;case 11:return e=Ai(e.type.render,!1),e;case 1:return e=Ai(e.type,!0),e;default:return""}}function po(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case gn:return"Fragment";case pn:return"Portal";case co:return"Profiler";case _a:return"StrictMode";case ho:return"Suspense";case fo:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case lc:return(e.displayName||"Context")+".Consumer";case ac:return(e._context.displayName||"Context")+".Provider";case Sa:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ka:return t=e.displayName||null,t!==null?t:po(e.type)||"Memo";case pt:t=e._payload,e=e._init;try{return po(e(t))}catch{}}return null}function Xh(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return po(t);case 8:return t===_a?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Pt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function cc(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Zh(e){var t=cc(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Xr(e){e._valueTracker||(e._valueTracker=Zh(e))}function dc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=cc(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function js(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function go(e,t){var n=t.checked;return K({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function ml(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Pt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function hc(e,t){t=t.checked,t!=null&&wa(e,"checked",t,!1)}function mo(e,t){hc(e,t);var n=Pt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?vo(e,t.type,n):t.hasOwnProperty("defaultValue")&&vo(e,t.type,Pt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function vl(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function vo(e,t,n){(t!=="number"||js(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var rr=Array.isArray;function On(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=Zr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function wr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var ar={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ef=["Webkit","ms","Moz","O"];Object.keys(ar).forEach(function(e){ef.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ar[t]=ar[e]})});function mc(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||ar.hasOwnProperty(e)&&ar[e]?(""+t).trim():t+"px"}function vc(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=mc(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var tf=K({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function _o(e,t){if(t){if(tf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(k(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(k(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(k(61))}if(t.style!=null&&typeof t.style!="object")throw Error(k(62))}}function So(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ko=null;function Ea(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Eo=null,xn=null,Rn=null;function _l(e){if(e=Hr(e)){if(typeof Eo!="function")throw Error(k(280));var t=e.stateNode;t&&(t=ci(t),Eo(e.stateNode,e.type,t))}}function yc(e){xn?Rn?Rn.push(e):Rn=[e]:xn=e}function wc(){if(xn){var e=xn,t=Rn;if(Rn=xn=null,_l(e),t)for(e=0;e>>=0,e===0?32:31-(ff(e)/pf|0)|0}var es=64,ts=4194304;function sr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function $s(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,i=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~s;a!==0?r=sr(a):(i&=o,i!==0&&(r=sr(i)))}else o=n&~s,o!==0?r=sr(o):i!==0&&(r=sr(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,i=t&-t,s>=i||s===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Wr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ke(t),e[t]=n}function yf(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=ur),Rl=" ",Pl=!1;function zc(e,t){switch(e){case"keyup":return qf.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Bc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var mn=!1;function Gf(e,t){switch(e){case"compositionend":return Bc(t);case"keypress":return t.which!==32?null:(Pl=!0,Rl);case"textInput":return e=t.data,e===Rl&&Pl?null:e;default:return null}}function Jf(e,t){if(mn)return e==="compositionend"||!Aa&&zc(e,t)?(e=Uc(),Es=xa=_t=null,mn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Nl(n)}}function Vc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Vc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Hc(){for(var e=window,t=js();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=js(e.document)}return t}function ja(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function sp(e){var t=Hc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Vc(n.ownerDocument.documentElement,n)){if(r!==null&&ja(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!e.extend&&i>r&&(s=r,r=i,i=s),s=Ll(n,i);var o=Ll(n,r);s&&o&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,vn=null,Ro=null,dr=null,Po=!1;function $l(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Po||vn==null||vn!==js(r)||(r=vn,"selectionStart"in r&&ja(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),dr&&br(dr,r)||(dr=r,r=zs(Ro,"onSelect"),0_n||(e.current=$o[_n],$o[_n]=null,_n--)}function B(e,t){_n++,$o[_n]=e.current,e.current=t}var At={},pe=It(At),Se=It(!1),Qt=At;function Ln(e,t){var n=e.type.contextTypes;if(!n)return At;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function ke(e){return e=e.childContextTypes,e!=null}function Ms(){F(Se),F(pe)}function Wl(e,t,n){if(pe.current!==At)throw Error(k(168));B(pe,t),B(Se,n)}function ed(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(k(108,Xh(e)||"Unknown",s));return K({},n,r)}function Fs(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||At,Qt=pe.current,B(pe,e),B(Se,Se.current),!0}function Vl(e,t,n){var r=e.stateNode;if(!r)throw Error(k(169));n?(e=ed(e,t,Qt),r.__reactInternalMemoizedMergedChildContext=e,F(Se),F(pe),B(pe,e)):F(Se),B(Se,n)}var rt=null,di=!1,Hi=!1;function td(e){rt===null?rt=[e]:rt.push(e)}function mp(e){di=!0,td(e)}function Nt(){if(!Hi&&rt!==null){Hi=!0;var e=0,t=D;try{var n=rt;for(D=1;e>=o,s-=o,st=1<<32-Ke(t)+s|n<x?(U=b,b=null):U=b.sibling;var L=h(f,b,g[x],w);if(L===null){b===null&&(b=U);break}e&&b&&L.alternate===null&&t(f,b),d=i(L,d,x),T===null?E=L:T.sibling=L,T=L,b=U}if(x===g.length)return n(f,b),V&&zt(f,x),E;if(b===null){for(;xx?(U=b,b=null):U=b.sibling;var ze=h(f,b,L.value,w);if(ze===null){b===null&&(b=U);break}e&&b&&ze.alternate===null&&t(f,b),d=i(ze,d,x),T===null?E=ze:T.sibling=ze,T=ze,b=U}if(L.done)return n(f,b),V&&zt(f,x),E;if(b===null){for(;!L.done;x++,L=g.next())L=p(f,L.value,w),L!==null&&(d=i(L,d,x),T===null?E=L:T.sibling=L,T=L);return V&&zt(f,x),E}for(b=r(f,b);!L.done;x++,L=g.next())L=m(b,f,x,L.value,w),L!==null&&(e&&L.alternate!==null&&b.delete(L.key===null?x:L.key),d=i(L,d,x),T===null?E=L:T.sibling=L,T=L);return e&&b.forEach(function(Hn){return t(f,Hn)}),V&&zt(f,x),E}function S(f,d,g,w){if(typeof g=="object"&&g!==null&&g.type===gn&&g.key===null&&(g=g.props.children),typeof g=="object"&&g!==null){switch(g.$$typeof){case Yr:e:{for(var E=g.key,T=d;T!==null;){if(T.key===E){if(E=g.type,E===gn){if(T.tag===7){n(f,T.sibling),d=s(T,g.props.children),d.return=f,f=d;break e}}else if(T.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===pt&&Kl(E)===T.type){n(f,T.sibling),d=s(T,g.props),d.ref=Xn(f,T,g),d.return=f,f=d;break e}n(f,T);break}else t(f,T);T=T.sibling}g.type===gn?(d=Jt(g.props.children,f.mode,w,g.key),d.return=f,f=d):(w=As(g.type,g.key,g.props,null,f.mode,w),w.ref=Xn(f,d,g),w.return=f,f=w)}return o(f);case pn:e:{for(T=g.key;d!==null;){if(d.key===T)if(d.tag===4&&d.stateNode.containerInfo===g.containerInfo&&d.stateNode.implementation===g.implementation){n(f,d.sibling),d=s(d,g.children||[]),d.return=f,f=d;break e}else{n(f,d);break}else t(f,d);d=d.sibling}d=Zi(g,f.mode,w),d.return=f,f=d}return o(f);case pt:return T=g._init,S(f,d,T(g._payload),w)}if(rr(g))return v(f,d,g,w);if(Kn(g))return y(f,d,g,w);ls(f,g)}return typeof g=="string"&&g!==""||typeof g=="number"?(g=""+g,d!==null&&d.tag===6?(n(f,d.sibling),d=s(d,g),d.return=f,f=d):(n(f,d),d=Xi(g,f.mode,w),d.return=f,f=d),o(f)):n(f,d)}return S}var Un=id(!0),od=id(!1),Hs=It(null),qs=null,En=null,$a=null;function Ua(){$a=En=qs=null}function Da(e){var t=Hs.current;F(Hs),e._currentValue=t}function zo(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function An(e,t){qs=e,$a=En=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(_e=!0),e.firstContext=null)}function Ue(e){var t=e._currentValue;if($a!==e)if(e={context:e,memoizedValue:t,next:null},En===null){if(qs===null)throw Error(k(308));En=e,qs.dependencies={lanes:0,firstContext:e}}else En=En.next=e;return t}var Ht=null;function za(e){Ht===null?Ht=[e]:Ht.push(e)}function ad(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,za(t)):(n.next=s.next,s.next=n),t.interleaved=n,ut(e,r)}function ut(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var gt=!1;function Ba(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ld(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function ot(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Ct(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,$&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,ut(e,n)}return s=r.interleaved,s===null?(t.next=t,za(r)):(t.next=s.next,s.next=t),r.interleaved=t,ut(e,n)}function bs(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ba(e,n)}}function Gl(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ks(e,t,n,r){var s=e.updateQueue;gt=!1;var i=s.firstBaseUpdate,o=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var l=a,u=l.next;l.next=null,o===null?i=u:o.next=u,o=l;var c=e.alternate;c!==null&&(c=c.updateQueue,a=c.lastBaseUpdate,a!==o&&(a===null?c.firstBaseUpdate=u:a.next=u,c.lastBaseUpdate=l))}if(i!==null){var p=s.baseState;o=0,c=u=l=null,a=i;do{var h=a.lane,m=a.eventTime;if((r&h)===h){c!==null&&(c=c.next={eventTime:m,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var v=e,y=a;switch(h=t,m=n,y.tag){case 1:if(v=y.payload,typeof v=="function"){p=v.call(m,p,h);break e}p=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=y.payload,h=typeof v=="function"?v.call(m,p,h):v,h==null)break e;p=K({},p,h);break e;case 2:gt=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,h=s.effects,h===null?s.effects=[a]:h.push(a))}else m={eventTime:m,lane:h,tag:a.tag,payload:a.payload,callback:a.callback,next:null},c===null?(u=c=m,l=p):c=c.next=m,o|=h;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;h=a,a=h.next,h.next=null,s.lastBaseUpdate=h,s.shared.pending=null}}while(!0);if(c===null&&(l=p),s.baseState=l,s.firstBaseUpdate=u,s.lastBaseUpdate=c,t=s.shared.interleaved,t!==null){s=t;do o|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);Zt|=o,e.lanes=o,e.memoizedState=p}}function Jl(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Ki.transition;Ki.transition={};try{e(!1),t()}finally{D=n,Ki.transition=r}}function bd(){return De().memoizedState}function _p(e,t,n){var r=xt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Cd(e))Od(t,n);else if(n=ad(e,t,n,r),n!==null){var s=me();Ge(n,e,r,s),xd(n,t,r)}}function Sp(e,t,n){var r=xt(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Cd(e))Od(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,a=i(o,n);if(s.hasEagerState=!0,s.eagerState=a,Je(a,o)){var l=t.interleaved;l===null?(s.next=s,za(t)):(s.next=l.next,l.next=s),t.interleaved=s;return}}catch{}finally{}n=ad(e,t,s,r),n!==null&&(s=me(),Ge(n,e,r,s),xd(n,t,r))}}function Cd(e){var t=e.alternate;return e===q||t!==null&&t===q}function Od(e,t){hr=Js=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function xd(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ba(e,n)}}var Qs={readContext:Ue,useCallback:de,useContext:de,useEffect:de,useImperativeHandle:de,useInsertionEffect:de,useLayoutEffect:de,useMemo:de,useReducer:de,useRef:de,useState:de,useDebugValue:de,useDeferredValue:de,useTransition:de,useMutableSource:de,useSyncExternalStore:de,useId:de,unstable_isNewReconciler:!1},kp={readContext:Ue,useCallback:function(e,t){return Ye().memoizedState=[e,t===void 0?null:t],e},useContext:Ue,useEffect:Yl,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Os(4194308,4,_d.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Os(4194308,4,e,t)},useInsertionEffect:function(e,t){return Os(4,2,e,t)},useMemo:function(e,t){var n=Ye();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ye();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=_p.bind(null,q,e),[r.memoizedState,e]},useRef:function(e){var t=Ye();return e={current:e},t.memoizedState=e},useState:Ql,useDebugValue:Ga,useDeferredValue:function(e){return Ye().memoizedState=e},useTransition:function(){var e=Ql(!1),t=e[0];return e=wp.bind(null,e[1]),Ye().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=q,s=Ye();if(V){if(n===void 0)throw Error(k(407));n=n()}else{if(n=t(),ie===null)throw Error(k(349));Xt&30||hd(r,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,Yl(pd.bind(null,r,i,e),[e]),r.flags|=2048,Ir(9,fd.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Ye(),t=ie.identifierPrefix;if(V){var n=it,r=st;n=(r&~(1<<32-Ke(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ar++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[Xe]=t,e[xr]=r,Dd(e,t,!1,!1),t.stateNode=e;e:{switch(o=So(n,r),n){case"dialog":M("cancel",e),M("close",e),s=r;break;case"iframe":case"object":case"embed":M("load",e),s=r;break;case"video":case"audio":for(s=0;sBn&&(t.flags|=128,r=!0,Zn(i,!1),t.lanes=4194304)}else{if(!r)if(e=Gs(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Zn(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!V)return he(t),null}else 2*Y()-i.renderingStartTime>Bn&&n!==1073741824&&(t.flags|=128,r=!0,Zn(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Y(),t.sibling=null,n=H.current,B(H,r?n&1|2:n&1),t):(he(t),null);case 22:case 23:return el(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?be&1073741824&&(he(t),t.subtreeFlags&6&&(t.flags|=8192)):he(t),null;case 24:return null;case 25:return null}throw Error(k(156,t.tag))}function Pp(e,t){switch(Na(t),t.tag){case 1:return ke(t.type)&&Ms(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Dn(),F(Se),F(pe),Wa(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Fa(t),null;case 13:if(F(H),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(k(340));$n()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return F(H),null;case 4:return Dn(),null;case 10:return Da(t.type._context),null;case 22:case 23:return el(),null;case 24:return null;default:return null}}var cs=!1,fe=!1,Ap=typeof WeakSet=="function"?WeakSet:Set,C=null;function Tn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){J(e,t,r)}else n.current=null}function Go(e,t,n){try{n()}catch(r){J(e,t,r)}}var lu=!1;function jp(e,t){if(Ao=Us,e=Hc(),ja(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,a=-1,l=-1,u=0,c=0,p=e,h=null;t:for(;;){for(var m;p!==n||s!==0&&p.nodeType!==3||(a=o+s),p!==i||r!==0&&p.nodeType!==3||(l=o+r),p.nodeType===3&&(o+=p.nodeValue.length),(m=p.firstChild)!==null;)h=p,p=m;for(;;){if(p===e)break t;if(h===n&&++u===s&&(a=o),h===i&&++c===r&&(l=o),(m=p.nextSibling)!==null)break;p=h,h=p.parentNode}p=m}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(jo={focusedElem:e,selectionRange:n},Us=!1,C=t;C!==null;)if(t=C,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,C=e;else for(;C!==null;){t=C;try{var v=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(v!==null){var y=v.memoizedProps,S=v.memoizedState,f=t.stateNode,d=f.getSnapshotBeforeUpdate(t.elementType===t.type?y:Fe(t.type,y),S);f.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var g=t.stateNode.containerInfo;g.nodeType===1?g.textContent="":g.nodeType===9&&g.documentElement&&g.removeChild(g.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(k(163))}}catch(w){J(t,t.return,w)}if(e=t.sibling,e!==null){e.return=t.return,C=e;break}C=t.return}return v=lu,lu=!1,v}function fr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&Go(t,n,i)}s=s.next}while(s!==r)}}function pi(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Jo(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Md(e){var t=e.alternate;t!==null&&(e.alternate=null,Md(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Xe],delete t[xr],delete t[Lo],delete t[pp],delete t[gp])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Fd(e){return e.tag===5||e.tag===3||e.tag===4}function uu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Fd(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Qo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Bs));else if(r!==4&&(e=e.child,e!==null))for(Qo(e,t,n),e=e.sibling;e!==null;)Qo(e,t,n),e=e.sibling}function Yo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Yo(e,t,n),e=e.sibling;e!==null;)Yo(e,t,n),e=e.sibling}var le=null,Ve=!1;function ft(e,t,n){for(n=n.child;n!==null;)Wd(e,t,n),n=n.sibling}function Wd(e,t,n){if(Ze&&typeof Ze.onCommitFiberUnmount=="function")try{Ze.onCommitFiberUnmount(oi,n)}catch{}switch(n.tag){case 5:fe||Tn(n,t);case 6:var r=le,s=Ve;le=null,ft(e,t,n),le=r,Ve=s,le!==null&&(Ve?(e=le,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):le.removeChild(n.stateNode));break;case 18:le!==null&&(Ve?(e=le,n=n.stateNode,e.nodeType===8?Vi(e.parentNode,n):e.nodeType===1&&Vi(e,n),Er(e)):Vi(le,n.stateNode));break;case 4:r=le,s=Ve,le=n.stateNode.containerInfo,Ve=!0,ft(e,t,n),le=r,Ve=s;break;case 0:case 11:case 14:case 15:if(!fe&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Go(n,t,o),s=s.next}while(s!==r)}ft(e,t,n);break;case 1:if(!fe&&(Tn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){J(n,t,a)}ft(e,t,n);break;case 21:ft(e,t,n);break;case 22:n.mode&1?(fe=(r=fe)||n.memoizedState!==null,ft(e,t,n),fe=r):ft(e,t,n);break;default:ft(e,t,n)}}function cu(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Ap),t.forEach(function(r){var s=Mp.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Be(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=o),r&=~i}if(r=s,r=Y()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Np(r/1960))-r,10e?16:e,St===null)var r=!1;else{if(e=St,St=null,Zs=0,$&6)throw Error(k(331));var s=$;for($|=4,C=e.current;C!==null;){var i=C,o=i.child;if(C.flags&16){var a=i.deletions;if(a!==null){for(var l=0;lY()-Xa?Gt(e,0):Ya|=n),Ee(e,t)}function Yd(e,t){t===0&&(e.mode&1?(t=ts,ts<<=1,!(ts&130023424)&&(ts=4194304)):t=1);var n=me();e=ut(e,t),e!==null&&(Wr(e,t,n),Ee(e,n))}function Bp(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Yd(e,n)}function Mp(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(k(314))}r!==null&&r.delete(t),Yd(e,n)}var Xd;Xd=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Se.current)_e=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return _e=!1,xp(e,t,n);_e=!!(e.flags&131072)}else _e=!1,V&&t.flags&1048576&&nd(t,Vs,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;xs(e,t),e=t.pendingProps;var s=Ln(t,pe.current);An(t,n),s=Ha(null,t,r,e,s,n);var i=qa();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ke(r)?(i=!0,Fs(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Ba(t),s.updater=fi,t.stateNode=s,s._reactInternals=t,Mo(t,r,e,n),t=Vo(null,t,r,!0,i,n)):(t.tag=0,V&&i&&Ia(t),ge(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(xs(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=Wp(r),e=Fe(r,e),s){case 0:t=Wo(null,t,r,e,n);break e;case 1:t=iu(null,t,r,e,n);break e;case 11:t=ru(null,t,r,e,n);break e;case 14:t=su(null,t,r,Fe(r.type,e),n);break e}throw Error(k(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),Wo(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),iu(e,t,r,s,n);case 3:e:{if(Ld(t),e===null)throw Error(k(387));r=t.pendingProps,i=t.memoizedState,s=i.element,ld(e,t),Ks(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=zn(Error(k(423)),t),t=ou(e,t,r,n,s);break e}else if(r!==s){s=zn(Error(k(424)),t),t=ou(e,t,r,n,s);break e}else for(Oe=bt(t.stateNode.containerInfo.firstChild),xe=t,V=!0,qe=null,n=od(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if($n(),r===s){t=ct(e,t,n);break e}ge(e,t,r,n)}t=t.child}return t;case 5:return ud(t),e===null&&Do(t),r=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,o=s.children,Io(r,s)?o=null:i!==null&&Io(r,i)&&(t.flags|=32),Nd(e,t),ge(e,t,o,n),t.child;case 6:return e===null&&Do(t),null;case 13:return $d(e,t,n);case 4:return Ma(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Un(t,null,r,n):ge(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),ru(e,t,r,s,n);case 7:return ge(e,t,t.pendingProps,n),t.child;case 8:return ge(e,t,t.pendingProps.children,n),t.child;case 12:return ge(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,i=t.memoizedProps,o=s.value,B(Hs,r._currentValue),r._currentValue=o,i!==null)if(Je(i.value,o)){if(i.children===s.children&&!Se.current){t=ct(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(i.tag===1){l=ot(-1,n&-n),l.tag=2;var u=i.updateQueue;if(u!==null){u=u.shared;var c=u.pending;c===null?l.next=l:(l.next=c.next,c.next=l),u.pending=l}}i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),zo(i.return,n,t),a.lanes|=n;break}l=l.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(k(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),zo(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ge(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,An(t,n),s=Ue(s),r=r(s),t.flags|=1,ge(e,t,r,n),t.child;case 14:return r=t.type,s=Fe(r,t.pendingProps),s=Fe(r.type,s),su(e,t,r,s,n);case 15:return jd(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),xs(e,t),t.tag=1,ke(r)?(e=!0,Fs(t)):e=!1,An(t,n),Rd(t,r,s),Mo(t,r,s,n),Vo(null,t,r,!0,e,n);case 19:return Ud(e,t,n);case 22:return Id(e,t,n)}throw Error(k(156,t.tag))};function Zd(e,t){return Cc(e,t)}function Fp(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ne(e,t,n,r){return new Fp(e,t,n,r)}function nl(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Wp(e){if(typeof e=="function")return nl(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Sa)return 11;if(e===ka)return 14}return 2}function Rt(e,t){var n=e.alternate;return n===null?(n=Ne(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function As(e,t,n,r,s,i){var o=2;if(r=e,typeof e=="function")nl(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case gn:return Jt(n.children,s,i,t);case _a:o=8,s|=8;break;case co:return e=Ne(12,n,t,s|2),e.elementType=co,e.lanes=i,e;case ho:return e=Ne(13,n,t,s),e.elementType=ho,e.lanes=i,e;case fo:return e=Ne(19,n,t,s),e.elementType=fo,e.lanes=i,e;case uc:return mi(n,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case ac:o=10;break e;case lc:o=9;break e;case Sa:o=11;break e;case ka:o=14;break e;case pt:o=16,r=null;break e}throw Error(k(130,e==null?e:typeof e,""))}return t=Ne(o,n,t,s),t.elementType=e,t.type=r,t.lanes=i,t}function Jt(e,t,n,r){return e=Ne(7,e,r,t),e.lanes=n,e}function mi(e,t,n,r){return e=Ne(22,e,r,t),e.elementType=uc,e.lanes=n,e.stateNode={isHidden:!1},e}function Xi(e,t,n){return e=Ne(6,e,null,t),e.lanes=n,e}function Zi(e,t,n){return t=Ne(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Vp(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ii(0),this.expirationTimes=Ii(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ii(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function rl(e,t,n,r,s,i,o,a,l){return e=new Vp(e,t,n,a,l),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ne(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ba(i),e}function Hp(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(rh)}catch(e){console.error(e)}}rh(),rc.exports=Pe;var Qp=rc.exports,yu=Qp;lo.createRoot=yu.createRoot,lo.hydrateRoot=yu.hydrateRoot;function Yp({title:e="Global Operations",status:t="System Online"}){return _.jsx("header",{className:"area header",children:_.jsxs("div",{className:"header-content",children:[_.jsx("h1",{children:e}),_.jsxs("div",{className:"system-status",children:[_.jsx("span",{className:"status-dot"})," ",t]})]})})}function Xp(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function Zp({summary:e,snapshotDate:t}){return e?_.jsxs("section",{className:"cashflow-summary-grid",children:[_.jsxs("article",{className:"cashflow-card",children:[_.jsx("span",{children:"Data"}),_.jsx("strong",{children:t||"-"})]}),_.jsxs("article",{className:"cashflow-card",children:[_.jsx("span",{children:"Saldo consolidado"}),_.jsx("strong",{children:Xp(e.consolidated_balance)})]}),_.jsxs("article",{className:"cashflow-card",children:[_.jsx("span",{children:"Unidades em risco"}),_.jsx("strong",{children:e.risk_units||0})]}),_.jsxs("article",{className:"cashflow-card",children:[_.jsxs("span",{children:["Desatualizadas (",e.stale_threshold_days||2,"+ dias)"]}),_.jsx("strong",{children:e.stale_units||0})]}),_.jsxs("article",{className:"cashflow-card",children:[_.jsx("span",{children:"Contas negativas"}),_.jsx("strong",{children:e.units_with_negative_accounts||0})]}),_.jsxs("article",{className:"cashflow-card",children:[_.jsx("span",{children:"Total de unidades"}),_.jsx("strong",{children:e.total_units||0})]})]}):null}function eg(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function tg({units:e=[],onSelectUnit:t,selectedUnitId:n}){return _.jsxs("section",{className:"cashflow-ranking",children:[_.jsxs("div",{className:"cashflow-ranking-header",children:[_.jsx("h3",{children:"Ranking de Caixa (Maior → Menor)"}),_.jsxs("span",{children:[e.length," unidades"]})]}),_.jsx("div",{className:"cashflow-table-wrapper",children:_.jsxs("table",{className:"cashflow-table",children:[_.jsx("thead",{children:_.jsxs("tr",{children:[_.jsx("th",{children:"#"}),_.jsx("th",{children:"Unidade"}),_.jsx("th",{children:"Saldo Total"}),_.jsx("th",{children:"Contas Negativas"}),_.jsx("th",{children:"Dias sem input"}),_.jsx("th",{children:"Status"})]})}),_.jsx("tbody",{children:e.map((r,s)=>{const i=[n===r.unit_id?"selected":"",Number(r.total_balance)<0?"risk":"",Number(r.days_since_last_input||0)>=2?"stale":""].filter(Boolean).join(" "),o=r.is_up_to_date?"Atualizado":"Desatualizado";return _.jsxs("tr",{className:i,children:[_.jsx("td",{children:s+1}),_.jsx("td",{children:_.jsx("button",{type:"button",onClick:()=>t(r),children:r.unit_name})}),_.jsx("td",{children:eg(r.total_balance)}),_.jsx("td",{children:r.negative_accounts_count||0}),_.jsx("td",{children:r.days_since_last_input||0}),_.jsx("td",{children:o})]},r.unit_id||`${r.unit_name}-${s}`)})})]})})]})}function ng({selectedDate:e,onDateChange:t,onRefresh:n}){return _.jsxs("section",{className:"cashflow-filter",children:[_.jsxs("div",{className:"cashflow-filter-left",children:[_.jsx("h3",{children:"Fluxo de Caixa por Data"}),_.jsx("p",{children:"Selecione uma data retroativa para comparar o histórico."})]}),_.jsxs("div",{className:"cashflow-filter-controls",children:[_.jsx("label",{htmlFor:"snapshot-date",children:"Data de referência"}),_.jsx("input",{id:"snapshot-date",type:"date",value:e,onChange:r=>t(r.target.value)}),_.jsx("button",{type:"button",onClick:n,children:"Atualizar"})]})]})}function wu(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function rg({unit:e}){if(!e)return _.jsxs("section",{className:"cashflow-unit-detail empty",children:[_.jsx("h3",{children:"Detalhe da Unidade"}),_.jsx("p",{children:"Selecione uma unidade no ranking para ver as contas."})]});const t=Array.isArray(e.accounts)?e.accounts:[],n=r=>{if(!r||typeof r!="object")return null;const s=r.days_since_last_input??r.days_without_input??r.days_since_input??r.input_delay_days;if(s==null||s==="")return null;const i=Number(s);return Number.isFinite(i)?i:null};return _.jsxs("section",{className:"cashflow-unit-detail",children:[_.jsxs("div",{className:"cashflow-unit-header",children:[_.jsx("h3",{children:e.unit_name}),_.jsx("span",{children:wu(e.total_balance)})]}),_.jsxs("div",{className:"cashflow-unit-meta",children:[_.jsxs("span",{children:["Dias sem input: ",e.days_since_last_input||0]}),_.jsxs("span",{children:["Status: ",e.is_up_to_date?"Atualizado":"Desatualizado"]})]}),_.jsx("div",{className:"cashflow-table-wrapper",children:_.jsxs("table",{className:"cashflow-table",children:[_.jsx("thead",{children:_.jsxs("tr",{children:[_.jsx("th",{children:"Conta"}),_.jsx("th",{children:"Dias sem input"}),_.jsx("th",{children:"Saldo"})]})}),_.jsx("tbody",{children:t.map(r=>{const s=Number(r.balance||0)<0,i=n(r);return _.jsxs("tr",{className:s?"risk":"",children:[_.jsx("td",{children:r.name}),_.jsx("td",{children:i??"N/D"}),_.jsx("td",{children:wu(r.balance)})]},r.bank_account_id||r.name)})})]})})]})}function sg(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function ig({history:e=[]}){return _.jsxs("section",{className:"cashflow-history",children:[_.jsxs("div",{className:"cashflow-ranking-header",children:[_.jsx("h3",{children:"Historico Diario"}),_.jsxs("span",{children:[e.length," snapshots"]})]}),_.jsx("div",{className:"cashflow-table-wrapper",children:_.jsxs("table",{className:"cashflow-table",children:[_.jsx("thead",{children:_.jsxs("tr",{children:[_.jsx("th",{children:"Data"}),_.jsx("th",{children:"Saldo consolidado"}),_.jsx("th",{children:"Risco"}),_.jsx("th",{children:"Desatualizadas"}),_.jsx("th",{children:"Contas negativas"})]})}),_.jsx("tbody",{children:e.map((t,n)=>{const r=t.summary||{};return _.jsxs("tr",{children:[_.jsx("td",{children:t.snapshot_date}),_.jsx("td",{children:sg(r.consolidated_balance)}),_.jsx("td",{children:r.risk_units||0}),_.jsx("td",{children:r.stale_units||0}),_.jsx("td",{children:r.units_with_negative_accounts||0})]},`${t.snapshot_date}-${n}`)})})]})})]})}function Si(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);se?(...t)=>e(...t):(...t)=>fetch(...t);class al extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class lg extends al{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class _u extends al{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class Su extends al{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var na;(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"})(na||(na={}));class ug{constructor(t,{headers:n={},customFetch:r,region:s=na.Any}={}){this.url=t,this.headers=n,this.region=s,this.fetch=ag(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t){return og(this,arguments,void 0,function*(n,r={}){var s;let i,o;try{const{headers:a,method:l,body:u,signal:c,timeout:p}=r;let h={},{region:m}=r;m||(m=this.region);const v=new URL(`${this.url}/${n}`);m&&m!=="any"&&(h["x-region"]=m,v.searchParams.set("forceFunctionRegion",m));let y;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",y=u):typeof u=="string"?(h["Content-Type"]="text/plain",y=u):typeof FormData<"u"&&u instanceof FormData?y=u:(h["Content-Type"]="application/json",y=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?y=JSON.stringify(u):y=u;let S=c;p&&(o=new AbortController,i=setTimeout(()=>o.abort(),p),c?(S=o.signal,c.addEventListener("abort",()=>o.abort())):S=o.signal);const f=yield this.fetch(v.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),a),body:y,signal:S}).catch(E=>{throw new lg(E)}),d=f.headers.get("x-relay-error");if(d&&d==="true")throw new _u(f);if(!f.ok)throw new Su(f);let g=((s=f.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),w;return g==="application/json"?w=yield f.json():g==="application/octet-stream"||g==="application/pdf"?w=yield f.blob():g==="text/event-stream"?w=f:g==="multipart/form-data"?w=yield f.formData():w=yield f.text(),{data:w,error:null,response:f}}catch(a){return{data:null,error:a,response:a instanceof Su||a instanceof _u?a.context:void 0}}finally{i&&clearTimeout(i)}})}}var cg=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},dg=class{constructor(e){var t,n,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=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(n=e.isMaybeSingle)!==null&&n!==void 0?n:!1,this.urlLengthLimit=(r=e.urlLengthLimit)!==null&&r!==void 0?r:8e3,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 n=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const r=this.fetch;let s=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,a=null,l=null,u=i.status,c=i.statusText;if(i.ok){var p,h;if(n.method!=="HEAD"){var m;const f=await i.text();f===""||(n.headers.get("Accept")==="text/csv"||n.headers.get("Accept")&&(!((m=n.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=f:a=JSON.parse(f))}const y=(p=n.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),S=(h=i.headers.get("content-range"))===null||h===void 0?void 0:h.split("/");y&&S&&S.length>1&&(l=parseInt(S[1])),n.isMaybeSingle&&n.method==="GET"&&Array.isArray(a)&&(a.length>1?(o={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,u=406,c="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{var v;const y=await i.text();try{o=JSON.parse(y),Array.isArray(o)&&i.status===404&&(a=[],o=null,u=200,c="OK")}catch{i.status===404&&y===""?(u=204,c="No Content"):o={message:y}}if(o&&n.isMaybeSingle&&(!(o==null||(v=o.details)===null||v===void 0)&&v.includes("0 rows"))&&(o=null,u=200,c="OK"),o&&n.shouldThrowOnError)throw new cg(o)}return{error:o,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(s=s.catch(i=>{var o;let a="",l="",u="";const c=i==null?void 0:i.cause;if(c){var p,h,m,v;const f=(p=c==null?void 0:c.message)!==null&&p!==void 0?p:"",d=(h=c==null?void 0:c.code)!==null&&h!==void 0?h:"";a=`${(m=i==null?void 0:i.name)!==null&&m!==void 0?m:"FetchError"}: ${i==null?void 0:i.message}`,a+=` Caused by: ${(v=c==null?void 0:c.name)!==null&&v!==void 0?v:"Error"}: ${f}`,d&&(a+=` (${d})`),c!=null&&c.stack&&(a+=` ${c.stack}`)}else{var y;a=(y=i==null?void 0:i.stack)!==null&&y!==void 0?y:""}const S=this.url.toString().length;return(i==null?void 0:i.name)==="AbortError"||(i==null?void 0:i.code)==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",S>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${S} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((c==null?void 0:c.name)==="HeadersOverflowError"||(c==null?void 0:c.code)==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",S>this.urlLengthLimit&&(l+=`. Your request URL is ${S} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=i==null?void 0:i.name)!==null&&o!==void 0?o:"FetchError"}: ${i==null?void 0:i.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}},hg=class extends dg{select(e){let t=!1;const n=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",n),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:s=r}={}){const i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){const r=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){const s=typeof r>"u"?"offset":`${r}.offset`,i=typeof r>"u"?"limit":`${r}.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 this.method==="GET"?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:n=!1,buffers:r=!1,wal:s=!1,format:i="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,n?"settings":null,r?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const ku=new RegExp("[,()]");var dn=class extends hg{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 n=Array.from(new Set(t)).map(r=>typeof r=="string"&&ku.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){const n=Array.from(new Set(t)).map(r=>typeof r=="string"&&ku.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t=="string"?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 typeof t=="string"?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 typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:n,type:r}={}){let s="";r==="plain"?s="pl":r==="phrase"?s="ph":r==="websearch"&&(s="w");const i=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${s}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([t,n])=>{this.url.searchParams.append(t,`eq.${n}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){const r=n?`${n}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},fg=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:s=8e3}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:n=!1,count:r}=t??{},s=n?"HEAD":"GET";let i=!1;const o=(e??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),r&&l.append("Prefer",`count=${r}`),new dn({method:s,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(e,{count:t,defaultToNull:n=!0}={}){var r;const s="POST",{url:i,headers:o}=this.cloneRequestState();if(t&&o.append("Prefer",`count=${t}`),n||o.append("Prefer","missing=default"),Array.isArray(e)){const a=e.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){const l=[...new Set(a)].map(u=>`"${u}"`);i.searchParams.set("columns",l.join(","))}}return new dn({method:s,url:i,headers:o,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:s=!0}={}){var i;const o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${n?"ignore":"merge"}-duplicates`),t!==void 0&&a.searchParams.set("on_conflict",t),r&&l.append("Prefer",`count=${r}`),s||l.append("Prefer","missing=default"),Array.isArray(e)){const u=e.reduce((c,p)=>c.concat(Object.keys(p)),[]);if(u.length>0){const c=[...new Set(u)].map(p=>`"${p}"`);a.searchParams.set("columns",c.join(","))}}return new dn({method:o,url:a,headers:l,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(e,{count:t}={}){var n;const r="PATCH",{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new dn({method:r,url:s,headers:i,schema:this.schema,body:e,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:e}={}){var t;const n="DELETE",{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new dn({method:n,url:r,headers:s,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function Lr(e){"@babel/helpers - typeof";return Lr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Lr(e)}function pg(e,t){if(Lr(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Lr(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function gg(e){var t=pg(e,"string");return Lr(t)=="symbol"?t:t+""}function mg(e,t,n){return(t=gg(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Eu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function fs(e){for(var t=1;t0?this.fetch=(l,u)=>{const c=new AbortController,p=setTimeout(()=>c.abort(),i),h=u==null?void 0:u.signal;if(h){if(h.aborted)return clearTimeout(p),a(l,u);const m=()=>{clearTimeout(p),c.abort()};return h.addEventListener("abort",m,{once:!0}),a(l,fs(fs({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(p),h.removeEventListener("abort",m)})}return a(l,fs(fs({},u),{},{signal:c.signal})).finally(()=>clearTimeout(p))}:this.fetch=a}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new fg(new URL(`${this.url}/${t}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new sh(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,n={},{head:r=!1,get:s=!1,count:i}={}){var o;let a;const l=new URL(`${this.url}/rpc/${t}`);let u;const c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),p=r&&Object.values(n).some(c);p?(a="POST",u=n):r||s?(a=r?"HEAD":"GET",Object.entries(n).filter(([m,v])=>v!==void 0).map(([m,v])=>[m,Array.isArray(v)?`{${v.join(",")}}`:`${v}`]).forEach(([m,v])=>{l.searchParams.append(m,v)})):(a="POST",u=n);const h=new Headers(this.headers);return p?h.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&h.set("Prefer",`count=${i}`),new dn({method:a,url:l,headers:h,schema:this.schemaName,body:u,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};class yg{constructor(){}static detectEnvironment(){var t;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const n=globalThis.process;if(n){const r=n.versions;if(r&&r.node){const s=r.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: import ws from "ws" new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const t=this.detectEnvironment();if(t.constructor)return t.constructor;let n=t.error||"WebSocket not supported in this environment.";throw t.workaround&&(n+=` Suggested solution: ${t.workaround}`),new Error(n)}static createWebSocket(t,n){const r=this.getWebSocketConstructor();return new r(t,n)}static isWebSocketSupported(){try{const t=this.detectEnvironment();return t.type==="native"||t.type==="ws"}catch{return!1}}}const wg="2.95.3",_g=`realtime-js/${wg}`,Sg="1.0.0",ih="2.0.0",Tu=ih,ra=1e4,kg=1e3,Eg=100;var mt;(function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"})(mt||(mt={}));var ee;(function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"})(ee||(ee={}));var He;(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"})(He||(He={}));var sa;(function(e){e.websocket="websocket"})(sa||(sa={}));var Ft;(function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"})(Ft||(Ft={}));class Tg{constructor(t){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=t??[]}encode(t,n){if(t.event===this.BROADCAST_EVENT&&!(t.payload instanceof ArrayBuffer)&&typeof t.payload.event=="string")return n(this._binaryEncodeUserBroadcastPush(t));let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return n(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(t){var n;return this._isArrayBuffer((n=t.payload)===null||n===void 0?void 0:n.payload)?this._encodeBinaryUserBroadcastPush(t):this._encodeJsonUserBroadcastPush(t)}_encodeBinaryUserBroadcastPush(t){var n,r;const s=(r=(n=t.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(t,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(t){var n,r;const s=(r=(n=t.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:{},o=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(t,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(t,n,r){var s,i;const o=t.topic,a=(s=t.ref)!==null&&s!==void 0?s:"",l=(i=t.join_ref)!==null&&i!==void 0?i:"",u=t.payload.event,c=this.allowedMetadataKeys?this._pick(t.payload,this.allowedMetadataKeys):{},p=Object.keys(c).length===0?"":JSON.stringify(c);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`metadata length ${p.length} exceeds maximum of 255`);const h=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+u.length+p.length,m=new ArrayBuffer(this.HEADER_LENGTH+h);let v=new DataView(m),y=0;v.setUint8(y++,this.KINDS.userBroadcastPush),v.setUint8(y++,l.length),v.setUint8(y++,a.length),v.setUint8(y++,o.length),v.setUint8(y++,u.length),v.setUint8(y++,p.length),v.setUint8(y++,n),Array.from(l,f=>v.setUint8(y++,f.charCodeAt(0))),Array.from(a,f=>v.setUint8(y++,f.charCodeAt(0))),Array.from(o,f=>v.setUint8(y++,f.charCodeAt(0))),Array.from(u,f=>v.setUint8(y++,f.charCodeAt(0))),Array.from(p,f=>v.setUint8(y++,f.charCodeAt(0)));var S=new Uint8Array(m.byteLength+r.byteLength);return S.set(new Uint8Array(m),0),S.set(new Uint8Array(r),m.byteLength),S.buffer}decode(t,n){if(this._isArrayBuffer(t)){let r=this._binaryDecode(t);return n(r)}if(typeof t=="string"){const r=JSON.parse(t),[s,i,o,a,l]=r;return n({join_ref:s,ref:i,topic:o,event:a,payload:l})}return n({})}_binaryDecode(t){const n=new DataView(t),r=n.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(t,n,s)}}_decodeUserBroadcast(t,n,r){const s=n.getUint8(1),i=n.getUint8(2),o=n.getUint8(3),a=n.getUint8(4);let l=this.HEADER_LENGTH+4;const u=r.decode(t.slice(l,l+s));l=l+s;const c=r.decode(t.slice(l,l+i));l=l+i;const p=r.decode(t.slice(l,l+o));l=l+o;const h=t.slice(l,t.byteLength),m=a===this.JSON_ENCODING?JSON.parse(r.decode(h)):h,v={type:this.BROADCAST_EVENT,event:c,payload:m};return o>0&&(v.meta=JSON.parse(p)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:v}}_isArrayBuffer(t){var n;return t instanceof ArrayBuffer||((n=t==null?void 0:t.constructor)===null||n===void 0?void 0:n.name)==="ArrayBuffer"}_pick(t,n){return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(([r])=>n.includes(r)))}}class oh{constructor(t,n){this.callback=t,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=n}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var z;(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"})(z||(z={}));const bu=(e,t,n={})=>{var r;const s=(r=n.skipTypes)!==null&&r!==void 0?r:[];return t?Object.keys(t).reduce((i,o)=>(i[o]=bg(o,e,t,s),i),{}):{}},bg=(e,t,n,r)=>{const s=t.find(a=>a.name===e),i=s==null?void 0:s.type,o=n[e];return i&&!r.includes(i)?ah(i,o):ia(o)},ah=(e,t)=>{if(e.charAt(0)==="_"){const n=e.slice(1,e.length);return Rg(t,n)}switch(e){case z.bool:return Cg(t);case z.float4:case z.float8:case z.int2:case z.int4:case z.int8:case z.numeric:case z.oid:return Og(t);case z.json:case z.jsonb:return xg(t);case z.timestamp:return Pg(t);case z.abstime:case z.date:case z.daterange:case z.int4range:case z.int8range:case z.money:case z.reltime:case z.text:case z.time:case z.timestamptz:case z.timetz:case z.tsrange:case z.tstzrange:return ia(t);default:return ia(t)}},ia=e=>e,Cg=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Og=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},xg=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e},Rg=(e,t)=>{if(typeof e!="string")return e;const n=e.length-1,r=e[n];if(e[0]==="{"&&r==="}"){let i;const o=e.slice(1,n);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>ah(t,a))}return e},Pg=e=>typeof e=="string"?e.replace(" ","T"):e,lh=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 eo{constructor(t,n,r={},s=ra){this.channel=t,this.event=n,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,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(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,n){var r;return this._hasReceived(t)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:t,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:n})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(n))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var Cu;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(Cu||(Cu={}));class mr{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},s=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=mr.syncState(this.state,s,i,o),this.pendingDiffs.forEach(l=>{this.state=mr.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},s=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=mr.syncDiff(this.state,s,i,o),a())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,s){const i=this.cloneDeep(t),o=this.transformState(n),a={},l={};return this.map(i,(u,c)=>{o[u]||(l[u]=c)}),this.map(o,(u,c)=>{const p=i[u];if(p){const h=c.map(S=>S.presence_ref),m=p.map(S=>S.presence_ref),v=c.filter(S=>m.indexOf(S.presence_ref)<0),y=p.filter(S=>h.indexOf(S.presence_ref)<0);v.length>0&&(a[u]=v),y.length>0&&(l[u]=y)}else a[u]=c}),this.syncDiff(i,{joins:a,leaves:l},r,s)}static syncDiff(t,n,r,s){const{joins:i,leaves:o}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(i,(a,l)=>{var u;const c=(u=t[a])!==null&&u!==void 0?u:[];if(t[a]=this.cloneDeep(l),c.length>0){const p=t[a].map(m=>m.presence_ref),h=c.filter(m=>p.indexOf(m.presence_ref)<0);t[a].unshift(...h)}r(a,c,l)}),this.map(o,(a,l)=>{let u=t[a];if(!u)return;const c=l.map(p=>p.presence_ref);u=u.filter(p=>c.indexOf(p.presence_ref)<0),t[a]=u,s(a,u,l),u.length===0&&delete t[a]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const s=t[r];return"metas"in s?n[r]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=s,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Ou;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(Ou||(Ou={}));var vr;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(vr||(vr={}));var nt;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(nt||(nt={}));class Cn{constructor(t,n={config:{}},r){var s,i;if(this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=ee.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config),this.timeout=this.socket.timeout,this.joinPush=new eo(this,He.join,this.params,this.timeout),this.rejoinTimer=new oh(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=ee.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=ee.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=ee.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=ee.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=ee.errored,this.rejoinTimer.scheduleTimeout())}),this._on(He.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new mr(this),this.broadcastEndpointURL=lh(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(t,n=this.timeout){var r,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==ee.closed){const{config:{broadcast:o,presence:a,private:l}}=this.params,u=(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(m=>m.filter))!==null&&s!==void 0?s:[],c=!!this.bindings[vr.PRESENCE]&&this.bindings[vr.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,p={},h={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(p.access_token=this.socket.accessTokenValue),this._onError(m=>t==null?void 0:t(nt.CHANNEL_ERROR,m)),this._onClose(()=>t==null?void 0:t(nt.CLOSED)),this.updateJoinPayload(Object.assign({config:h},p)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",async({postgres_changes:m})=>{var v;if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){t==null||t(nt.SUBSCRIBED);return}else{const y=this.bindings.postgres_changes,S=(v=y==null?void 0:y.length)!==null&&v!==void 0?v:0,f=[];for(let d=0;d{this.state=ee.errored,t==null||t(nt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(nt.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){return this.state===ee.joined&&t===vr.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(t,n,r)}async httpSend(t,n,r={}){var s;if(n==null)return Promise.reject("Payload is required for httpSend()");const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:t,payload:n,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{const u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(t,n={}){var r,s;if(!this._canPush()&&t.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:o}=t,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=n.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=u.body)===null||s===void 0?void 0:s.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;const u=this._push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=ee.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(He.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new eo(this,He.leave,{},t),r.receive("ok",()=>{n(),s("ok")}).receive("timeout",()=>{n(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{r==null||r.destroy()})}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=ee.closed,this.bindings={}}async _fetchWithTimeout(t,n,r){const s=new AbortController,i=setTimeout(()=>s.abort(),r),o=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:s.signal}));return clearTimeout(i),o}_push(t,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new eo(this,t,n,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(t){if(t.startTimeout(),this.pushBuffer.push(t),this.pushBuffer.length>Eg){const n=this.pushBuffer.shift();n&&(n.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${n.event}`,n.payload))}}_onMessage(t,n,r){return n}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,n,r){var s,i;const o=t.toLocaleLowerCase(),{close:a,error:l,leave:u,join:c}=He;if(r&&[a,l,u,c].indexOf(o)>=0&&r!==this._joinRef())return;let h=this._onMessage(o,n,r);if(n&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(m=>{var v,y,S;return((v=m.filter)===null||v===void 0?void 0:v.event)==="*"||((S=(y=m.filter)===null||y===void 0?void 0:y.event)===null||S===void 0?void 0:S.toLocaleLowerCase())===o}).map(m=>m.callback(h,r)):(i=this.bindings[o])===null||i===void 0||i.filter(m=>{var v,y,S,f,d,g;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){const w=m.id,E=(v=m.filter)===null||v===void 0?void 0:v.event;return w&&((y=n.ids)===null||y===void 0?void 0:y.includes(w))&&(E==="*"||(E==null?void 0:E.toLocaleLowerCase())===((S=n.data)===null||S===void 0?void 0:S.type.toLocaleLowerCase()))}else{const w=(d=(f=m==null?void 0:m.filter)===null||f===void 0?void 0:f.event)===null||d===void 0?void 0:d.toLocaleLowerCase();return w==="*"||w===((g=n==null?void 0:n.event)===null||g===void 0?void 0:g.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof h=="object"&&"ids"in h){const v=h.data,{schema:y,table:S,commit_timestamp:f,type:d,errors:g}=v;h=Object.assign(Object.assign({},{schema:y,table:S,commit_timestamp:f,eventType:d,new:{},old:{},errors:g}),this._getPayloadRecords(v))}m.callback(h,r)})}_isClosed(){return this.state===ee.closed}_isJoined(){return this.state===ee.joined}_isJoining(){return this.state===ee.joining}_isLeaving(){return this.state===ee.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const s=t.toLocaleLowerCase(),i={type:s,filter:n,callback:r};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&Cn.isEqual(s.filter,n))})),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}static isFilterValueEqual(t,n){return(t??void 0)===(n??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(He.close,{},t)}_onError(t){this._on(He.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=ee.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=bu(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=bu(t.columns,t.old_record)),n}}const to=()=>{},ps={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Ag=[1e3,2e3,5e3,1e4],jg=1e4,Ig=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class Ng{constructor(t,n){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=ra,this.transport=null,this.heartbeatIntervalMs=ps.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=to,this.ref=0,this.reconnectTimer=null,this.vsn=Tu,this.logger=to,this.conn=null,this.sendBuffer=[],this.serializer=new Tg,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((r=n==null?void 0:n.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=n.params.apikey,this.endPoint=`${t}/${sa.websocket}`,this.httpEndpoint=lh(t),this._initializeOptions(n),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=yg.createWebSocket(this.endpointURL())}catch(t){this._setConnectionState("disconnected");const n=t.message;throw n.includes("Node.js")?new Error(`${n} To use Realtime in Node.js, you need to provide a WebSocket implementation: Option 1: Use Node.js 22+ which has native WebSocket support Option 2: Install and provide the "ws" package: npm install ws import ws from "ws" const client = new RealtimeClient(url, { ...options, transport: ws })`):new Error(`WebSocket not available: ${n}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(t,n){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")},typeof this.conn.close=="function"&&(t?this.conn.close(t,n??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return n==="ok"&&this._remove(t),this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const t=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,n,r){this.logger(t,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case mt.connecting:return Ft.Connecting;case mt.open:return Ft.Open;case mt.closing:return Ft.Closing;default:return Ft.Closed}}isConnected(){return this.connectionState()===Ft.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(t,n={config:{}}){const r=`realtime:${t}`,s=this.getChannels().find(i=>i.topic===r);if(s)return s;{const i=new Cn(`realtime:${t}`,n,this);return this.channels.push(i),i}}push(t){const{topic:n,event:r,payload:s,ref:i}=t,o=()=>{this.encode(t,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${n} ${r} (${i})`,s),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(t=null){this._authPromise=this._performAuth(t);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var t;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(n){this.log("error","error in heartbeat callback",n)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(n){this.log("error","error in heartbeat callback",n)}this._wasManualDisconnect=!1,(t=this.conn)===null||t===void 0||t.close(kg,"heartbeat timeout"),setTimeout(()=>{var n;this.isConnected()||(n=this.reconnectTimer)===null||n===void 0||n.scheduleTimeout()},ps.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(n){this.log("error","error in heartbeat callback",n)}this._setAuthSafely("heartbeat")}onHeartbeat(t){this.heartbeatCallback=t}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let n=this.channels.find(r=>r.topic===t&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${t}"`),n.unsubscribe())}_remove(t){this.channels=this.channels.filter(n=>n.topic!==t.topic)}_onConnMessage(t){this.decode(t.data,n=>{if(n.topic==="phoenix"&&n.event==="phx_reply"&&n.ref&&n.ref===this.pendingHeartbeatRef){const u=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(n.payload.status==="ok"?"ok":"error",u)}catch(c){this.log("error","error in heartbeat callback",c)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:r,event:s,payload:i,ref:o}=n,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${r} ${s} ${a}`.trim(),i),this.channels.filter(u=>u._isMember(r)).forEach(u=>u._trigger(s,i,o)),this._triggerStateCallbacks("message",n)})}_clearTimer(t){var n;t==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):t==="reconnect"&&((n=this.reconnectTimer)===null||n===void 0||n.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=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t),this.conn.readyState===mt.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===mt.open||this.conn.readyState===mt.connecting)try{this.conn.close()}catch(t){this.log("error","Error closing connection",t)}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(t=>t.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(n=>{this.log("error","error waiting for auth on connect",n),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 t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=n=>{this.log("worker","worker error",n.message),this._terminateWorker()},this.workerRef.onmessage=n=>{n.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(t){var n;this._setConnectionState("disconnected"),this.log("transport","close",t),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(n=this.reconnectTimer)===null||n===void 0||n.scheduleTimeout(),this._triggerStateCallbacks("close",t)}_onConnError(t){this._setConnectionState("disconnected"),this.log("transport",`${t}`),this._triggerChanError(),this._triggerStateCallbacks("error",t);try{this.heartbeatCallback("error")}catch(n){this.log("error","error in heartbeat callback",n)}}_triggerChanError(){this.channels.forEach(t=>t._trigger(He.error))}_appendParams(t,n){if(Object.keys(n).length===0)return t;const r=t.match(/\?/)?"&":"?",s=new URLSearchParams(n);return`${t}${r}${s}`}_workerObjectUrl(t){let n;if(t)n=t;else{const r=new Blob([Ig],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}_setConnectionState(t,n=!1){this._connectionState=t,t==="connecting"?this._wasManualDisconnect=!1:t==="disconnecting"&&(this._wasManualDisconnect=n)}async _performAuth(t=null){let n,r=!1;if(t)n=t,r=!0;else if(this.accessToken)try{n=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),n=this.accessTokenValue}else n=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(s=>{const i={access_token:n,version:_g};n&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(He.access_token,{access_token:n})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this._isManualToken()||this.setAuth().catch(n=>{this.log("error",`Error setting auth in ${t}`,n)})}_triggerStateCallbacks(t,n){try{this.stateChangeCallbacks[t].forEach(r=>{try{r(n)}catch(s){this.log("error",`error in ${t} callback`,s)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}_setupReconnectionTimer(){this.reconnectTimer=new oh(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},ps.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(t){var n,r,s,i,o,a,l,u,c,p,h,m;switch(this.transport=(n=t==null?void 0:t.transport)!==null&&n!==void 0?n:null,this.timeout=(r=t==null?void 0:t.timeout)!==null&&r!==void 0?r:ra,this.heartbeatIntervalMs=(s=t==null?void 0:t.heartbeatIntervalMs)!==null&&s!==void 0?s:ps.HEARTBEAT_INTERVAL,this.worker=(i=t==null?void 0:t.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=t==null?void 0:t.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=t==null?void 0:t.heartbeatCallback)!==null&&a!==void 0?a:to,this.vsn=(l=t==null?void 0:t.vsn)!==null&&l!==void 0?l:Tu,t!=null&&t.params&&(this.params=t.params),t!=null&&t.logger&&(this.logger=t.logger),(t!=null&&t.logLevel||t!=null&&t.log_level)&&(this.logLevel=t.logLevel||t.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(u=t==null?void 0:t.reconnectAfterMs)!==null&&u!==void 0?u:v=>Ag[v-1]||jg,this.vsn){case Sg:this.encode=(c=t==null?void 0:t.encode)!==null&&c!==void 0?c:(v,y)=>y(JSON.stringify(v)),this.decode=(p=t==null?void 0:t.decode)!==null&&p!==void 0?p:(v,y)=>y(JSON.parse(v));break;case ih:this.encode=(h=t==null?void 0:t.encode)!==null&&h!==void 0?h:this.serializer.encode.bind(this.serializer),this.decode=(m=t==null?void 0:t.decode)!==null&&m!==void 0?m:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t==null?void 0:t.workerUrl}}}var $r=class extends Error{constructor(e,t){var n;super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType==="CommitStateUnknownException"||[500,502,504].includes(t.status)&&((n=t.icebergType)==null?void 0:n.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Lg(e,t,n){const r=new URL(t,e);if(n)for(const[s,i]of Object.entries(n))i!==void 0&&r.searchParams.set(s,i);return r.toString()}async function $g(e){return!e||e.type==="none"?{}:e.type==="bearer"?{Authorization:`Bearer ${e.token}`}:e.type==="header"?{[e.name]:e.value}:e.type==="custom"?await e.getHeaders():{}}function Ug(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:s,body:i,headers:o}){const a=Lg(e.baseUrl,r,s),l=await $g(e.auth),u=await t(a,{method:n,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),c=await u.text(),p=(u.headers.get("content-type")||"").includes("application/json"),h=p&&c?JSON.parse(c):c;if(!u.ok){const m=p?h:void 0,v=m==null?void 0:m.error;throw new $r((v==null?void 0:v.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:v==null?void 0:v.type,icebergCode:v==null?void 0:v.code,details:m})}return{status:u.status,headers:u.headers,data:h}}}}function gs(e){return e.join("")}var Dg=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:gs(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(e,t){const n={namespace:e.namespace,properties:t==null?void 0:t.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${gs(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${gs(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${gs(e.namespace)}`}),!0}catch(t){if(t instanceof $r&&t.status===404)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(n){if(n instanceof $r&&n.status===409)return;throw n}}};function sn(e){return e.join("")}var zg=class{constructor(e,t="",n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const n={};return this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){const n=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data["metadata-location"],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String((t==null?void 0:t.purge)??!1)}})}async loadTable(e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${sn(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/${sn(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(n){if(n instanceof $r&&n.status===404)return!1;throw n}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof $r&&n.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},Bg=class{constructor(e){var r;let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const n=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Ug({baseUrl:n,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=(r=e.accessDelegation)==null?void 0:r.join(","),this.namespaceOps=new Dg(this.client,t),this.tableOps=new zg(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)}},ki=class extends Error{constructor(e,t="storage",n,r){super(e),this.__isStorageError=!0,this.namespace=t,this.name=t==="vectors"?"StorageVectorsError":"StorageError",this.status=n,this.statusCode=r}};function Ei(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}var ms=class extends ki{constructor(e,t,n,r="storage"){super(e,r,t,n),this.name=r==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},uh=class extends ki{constructor(e,t,n="storage"){super(e,n),this.name=n==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};const Mg=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),Fg=e=>{if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},oa=e=>{if(Array.isArray(e))return e.map(n=>oa(n));if(typeof e=="function"||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([n,r])=>{const s=n.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[s]=oa(r)}),t},Wg=e=>!e||typeof e!="string"||e.length===0||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e);function Ur(e){"@babel/helpers - typeof";return Ur=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ur(e)}function Vg(e,t){if(Ur(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Ur(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Hg(e){var t=Vg(e,"string");return Ur(t)=="symbol"?t:t+""}function qg(e,t,n){return(t=Hg(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function xu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function A(e){for(var t=1;t{var t;return e.msg||e.message||e.error_description||(typeof e.error=="string"?e.error:(t=e.error)===null||t===void 0?void 0:t.message)||JSON.stringify(e)},Kg=async(e,t,n,r)=>{if(e&&typeof e=="object"&&"status"in e&&"ok"in e&&typeof e.status=="number"&&!(n!=null&&n.noResolveJson)){const s=e,i=s.status||500;if(typeof s.json=="function")s.json().then(o=>{const a=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||i+"";t(new ms(Ru(o),i,a,r))}).catch(()=>{if(r==="vectors"){const o=i+"";t(new ms(s.statusText||`HTTP ${i} error`,i,o,r))}else{const o=i+"";t(new ms(s.statusText||`HTTP ${i} error`,i,o,r))}});else{const o=i+"";t(new ms(s.statusText||`HTTP ${i} error`,i,o,r))}}else t(new uh(Ru(e),e,r))},Gg=(e,t,n,r)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"||e==="HEAD"||!r?A(A({},s),n):(Fg(r)?(s.headers=A({"Content-Type":"application/json"},t==null?void 0:t.headers),s.body=JSON.stringify(r)):s.body=r,t!=null&&t.duplex&&(s.duplex=t.duplex),A(A({},s),n))};async function tr(e,t,n,r,s,i,o){return new Promise((a,l)=>{e(n,Gg(t,r,s,i)).then(u=>{if(!u.ok)throw u;if(r!=null&&r.noResolveJson)return u;if(o==="vectors"){const c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>Kg(u,l,r,o))})}function ch(e="storage"){return{get:async(t,n,r,s)=>tr(t,"GET",n,r,s,void 0,e),post:async(t,n,r,s,i)=>tr(t,"POST",n,s,i,r,e),put:async(t,n,r,s,i)=>tr(t,"PUT",n,s,i,r,e),head:async(t,n,r,s)=>tr(t,"HEAD",n,A(A({},r),{},{noResolveJson:!0}),s,void 0,e),remove:async(t,n,r,s,i)=>tr(t,"DELETE",n,s,i,r,e)}}const Jg=ch("storage"),{get:Dr,post:We,put:aa,head:Qg,remove:ll}=Jg,Ce=ch("vectors");var Vn=class{constructor(e,t={},n,r="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.fetch=Mg(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(n){if(t.shouldThrowOnError)throw n;if(Ei(n))return{data:null,error:n};throw n}}},Yg=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ei(t))return{data:null,error:t};throw t}}};let dh;dh=Symbol.toStringTag;var Xg=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[dh]="BlobDownloadBuilder",this.promise=null}asStream(){return new Yg(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(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ei(t))return{data:null,error:t};throw t}}};const Zg={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Pu={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var em=class extends Vn{constructor(e,t={},n,r){super(e,t,r,"storage"),this.bucketId=n}async uploadOrUpdate(e,t,n,r){var s=this;return s.handleOperation(async()=>{let i;const o=A(A({},Pu),r);let a=A(A({},s.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=n,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=s.toBase64(s.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),r!=null&&r.headers&&(a=A(A({},a),r.headers));const u=s._removeEmptyFolders(t),c=s._getFinalPath(u),p=await(e=="PUT"?aa:We)(s.fetch,`${s.url}/object/${c}`,i,A({headers:a},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{path:u,id:p.Id,fullPath:p.Key}})}async upload(e,t,n){return this.uploadOrUpdate("POST",e,t,n)}async uploadToSignedUrl(e,t,n,r){var s=this;const i=s._removeEmptyFolders(e),o=s._getFinalPath(i),a=new URL(s.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",t),s.handleOperation(async()=>{let l;const u=A({upsert:Pu.upsert},r),c=A(A({},s.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&n instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",n)):typeof FormData<"u"&&n instanceof FormData?(l=n,l.append("cacheControl",u.cacheControl)):(l=n,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:i,fullPath:(await aa(s.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(e,t){var n=this;return n.handleOperation(async()=>{let r=n._getFinalPath(e);const s=A({},n.headers);t!=null&&t.upsert&&(s["x-upsert"]="true");const i=await We(n.fetch,`${n.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(n.url+i.url),a=o.searchParams.get("token");if(!a)throw new ki("No token returned by API");return{signedUrl:o.toString(),path:e,token:a}})}async update(e,t,n){return this.uploadOrUpdate("PUT",e,t,n)}async move(e,t,n){var r=this;return r.handleOperation(async()=>await We(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:r.headers}))}async copy(e,t,n){var r=this;return r.handleOperation(async()=>({path:(await We(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:r.headers})).Key}))}async createSignedUrl(e,t,n){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(e),i=await We(r.fetch,`${r.url}/object/sign/${s}`,A({expiresIn:t},n!=null&&n.transform?{transform:n.transform}:{}),{headers:r.headers});const o=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{signedUrl:encodeURI(`${r.url}${i.signedURL}${o}`)}})}async createSignedUrls(e,t,n){var r=this;return r.handleOperation(async()=>{const s=await We(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:t,paths:e},{headers:r.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return s.map(o=>A(A({},o),{},{signedUrl:o.signedURL?encodeURI(`${r.url}${o.signedURL}${i}`):null}))})}download(e,t,n){const r=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),i=s?`?${s}`:"",o=this._getFinalPath(e),a=()=>Dr(this.fetch,`${this.url}/${r}/${o}${i}`,{headers:this.headers,noResolveJson:!0},n);return new Xg(a,this.shouldThrowOnError)}async info(e){var t=this;const n=t._getFinalPath(e);return t.handleOperation(async()=>oa(await Dr(t.fetch,`${t.url}/object/info/${n}`,{headers:t.headers})))}async exists(e){var t=this;const n=t._getFinalPath(e);try{return await Qg(t.fetch,`${t.url}/object/${n}`,{headers:t.headers}),{data:!0,error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(Ei(r)&&r instanceof uh){const s=r.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:r}}throw r}}getPublicUrl(e,t){const n=this._getFinalPath(e),r=[],s=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";s!==""&&r.push(s);const i=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",o=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});o!==""&&r.push(o);let a=r.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${n}${a}`)}}}async remove(e){var t=this;return t.handleOperation(async()=>await ll(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,n){var r=this;return r.handleOperation(async()=>{const s=A(A(A({},Zg),t),{},{prefix:e||""});return await We(r.fetch,`${r.url}/object/list/${r.bucketId}`,s,{headers:r.headers},n)})}async listV2(e,t){var n=this;return n.handleOperation(async()=>{const r=A({},e);return await We(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,r,{headers:n.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?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 tm="2.95.3",Kr={"X-Client-Info":`storage-js/${tm}`};var nm=class extends Vn{constructor(e,t={},n,r){const s=new URL(e);r!=null&&r.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));const i=s.href.replace(/\/$/,""),o=A(A({},Kr),t);super(i,o,n,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const n=t.listBucketOptionsToQueryString(e);return await Dr(t.fetch,`${t.url}/bucket${n}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await Dr(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var n=this;return n.handleOperation(async()=>await We(n.fetch,`${n.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async updateBucket(e,t){var n=this;return n.handleOperation(async()=>await aa(n.fetch,`${n.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await We(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ll(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}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():""}},rm=class extends Vn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=A(A({},Kr),t);super(r,s,n,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await We(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.set("limit",e.limit.toString()),(e==null?void 0:e.offset)!==void 0&&n.set("offset",e.offset.toString()),e!=null&&e.sortColumn&&n.set("sortColumn",e.sortColumn),e!=null&&e.sortOrder&&n.set("sortOrder",e.sortOrder),e!=null&&e.search&&n.set("search",e.search);const r=n.toString(),s=r?`${t.url}/bucket?${r}`:`${t.url}/bucket`;return await Dr(t.fetch,s,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ll(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!Wg(e))throw new ki("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 n=new Bg({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(n,{get(s,i){const o=s[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(s,a),error:null}}catch(l){if(r)throw l;return{data:null,error:l}}}}})}},sm=class extends Vn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=A(A({},Kr),{},{"Content-Type":"application/json"},t);super(r,s,n,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var n=this;return n.handleOperation(async()=>await Ce.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var n=this;return n.handleOperation(async()=>await Ce.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers})||{})}},im=class extends Vn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=A(A({},Kr),{},{"Content-Type":"application/json"},t);super(r,s,n,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},om=class extends Vn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=A(A({},Kr),{},{"Content-Type":"application/json"},t);super(r,s,n,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await Ce.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},am=class extends om{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new lm(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,n=this;return t().call(n,e)}async getBucket(e){var t=()=>super.getBucket,n=this;return t().call(n,e)}async listBuckets(e={}){var t=()=>super.listBuckets,n=this;return t().call(n,e)}async deleteBucket(e){var t=()=>super.deleteBucket,n=this;return t().call(n,e)}},lm=class extends sm{constructor(e,t,n,r){super(e,t,r),this.vectorBucketName=n}async createIndex(e){var t=()=>super.createIndex,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,n=this;return t().call(n,n.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,n=this;return t().call(n,n.vectorBucketName,e)}index(e){return new um(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},um=class extends im{constructor(e,t,n,r,s){super(e,t,s),this.vectorBucketName=n,this.indexName=r}async putVectors(e){var t=()=>super.putVectors,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(e){var t=()=>super.getVectors,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},cm=class extends nm{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new em(this.url,this.headers,e,this.fetch)}get vectors(){return new am(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new rm(this.url+"/iceberg",this.headers,this.fetch)}};const hh="2.95.3",hn=30*1e3,la=3,no=la*hn,dm="http://localhost:9999",hm="supabase.auth.token",fm={"X-Client-Info":`gotrue-js/${hh}`},ua="X-Supabase-Api-Version",fh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},pm=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,gm=10*60*1e3;class zr extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function R(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class mm extends zr{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function vm(e){return R(e)&&e.name==="AuthApiError"}class Wt extends zr{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class ht extends zr{constructor(t,n,r,s){super(t,r,s),this.name=n,this.status=r}}class Te extends ht{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function ro(e){return R(e)&&e.name==="AuthSessionMissingError"}class on extends ht{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class vs extends ht{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class ys extends ht{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function ym(e){return R(e)&&e.name==="AuthImplicitGrantRedirectError"}class Au extends ht{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class wm extends ht{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 ca extends ht{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function so(e){return R(e)&&e.name==="AuthRetryableFetchError"}class ju extends ht{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class da extends ht{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const ni="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Iu=` \r=`.split(""),_m=(()=>{const e=new Array(128);for(let t=0;t=6;){const r=t.queue>>t.queuedBits-6&63;n(ni[r]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const r=t.queue>>t.queuedBits-6&63;n(ni[r]),t.queuedBits-=6}}function ph(e,t,n){const r=_m[e];if(r>-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}}function Lu(e){const t=[],n=o=>{t.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{Em(o,r,n)};for(let o=0;o>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function km(e,t){for(let n=0;n55295&&r<=56319){const s=(r-55296)*1024&65535;r=(e.charCodeAt(n+1)-56320&65535|s)+65536,n+=1}Sm(r,t)}}function Em(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0&&n(t.codepoint)}}function In(e){const t=[],n={queue:0,queuedBits:0},r=s=>{t.push(s)};for(let s=0;st.push(n)),new Uint8Array(t)}function Kt(e){const t=[],n={queue:0,queuedBits:0},r=s=>{t.push(s)};return e.forEach(s=>Nu(s,n,r)),Nu(null,n,r),t.join("")}function bm(e){return Math.round(Date.now()/1e3)+e}function Cm(){return Symbol("auth-callback")}const ae=()=>typeof window<"u"&&typeof document<"u",Ut={tested:!1,writable:!1},gh=()=>{if(!ae())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ut.tested)return Ut.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Ut.tested=!0,Ut.writable=!0}catch{Ut.tested=!0,Ut.writable=!1}return Ut.writable};function Om(e){const t={},n=new URL(e);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((s,i)=>{t[i]=s})}catch{}return n.searchParams.forEach((r,s)=>{t[s]=r}),t}const mh=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),xm=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",fn=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},Dt=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},oe=async(e,t)=>{await e.removeItem(t)};class Ti{constructor(){this.promise=new Ti.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}Ti.promiseConstructor=Promise;function ws(e){const t=e.split(".");if(t.length!==3)throw new da("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),e)})}function Pm(e,t){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await e(i);if(!t(i,null,o)){r(o);return}}catch(o){if(!t(i,o)){s(o);return}}})()})}function Am(e){return("0"+e.toString(16)).substr(-2)}function jm(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let s="";for(let i=0;i<56;i++)s+=n.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(t),Array.from(t,Am).join("")}async function Im(e){const n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function Nm(e){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const n=await Im(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function an(e,t,n=!1){const r=jm();let s=r;n&&(s+="/PASSWORD_RECOVERY"),await fn(e,`${t}-code-verifier`,s);const i=await Nm(r);return[i,r===i?"plain":"s256"]}const Lm=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function $m(e){const t=e.headers.get(ua);if(!t||!t.match(Lm))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function Um(e){if(!e)throw new Error("Missing exp claim");const t=Math.floor(Date.now()/1e3);if(e<=t)throw new Error("JWT has expired")}function Dm(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")}}const zm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ln(e){if(!zm.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function io(){const e={};return new Proxy(e,{get:(t,n)=>{if(n==="__isUserNotAvailableProxy")return!0;if(typeof n=="symbol"){const r=n.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${n}" property of the session object is not supported. Please use getUser() instead.`)},set:(t,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(t,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Bm(e,t){return new Proxy(e,{get:(n,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){const i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(n,r,s)}return!t.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(n,r,s)}})}function $u(e){return JSON.parse(JSON.stringify(e))}const Mt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Mm=[502,503,504];async function Uu(e){var t;if(!xm(e))throw new ca(Mt(e),0);if(Mm.includes(e.status))throw new ca(Mt(e),e.status);let n;try{n=await e.json()}catch(i){throw new Wt(Mt(i),i)}let r;const s=$m(e);if(s&&s.getTime()>=fh["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new ju(Mt(n),e.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new Te}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new ju(Mt(n),e.status,n.weak_password.reasons);throw new mm(Mt(n),e.status||500,r)}const Fm=(e,t,n,r)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),n))};async function P(e,t,n,r){var s;const i=Object.assign({},r==null?void 0:r.headers);i[ua]||(i[ua]=fh["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const o=(s=r==null?void 0:r.query)!==null&&s!==void 0?s:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Wm(e,t,n+a,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(l):{data:Object.assign({},l),error:null}}async function Wm(e,t,n,r,s,i){const o=Fm(t,r,s,i);let a;try{a=await e(n,Object.assign({},o))}catch(l){throw console.error(l),new ca(Mt(l),0)}if(a.ok||await Uu(a),r!=null&&r.noResolveJson)return a;try{return await a.json()}catch(l){await Uu(l)}}function Me(e){var t;let n=null;qm(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=bm(e.expires_in)));const r=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:n,user:r},error:null}}function Du(e){const t=Me(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=e.weak_password),t}function wt(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function Vm(e){return{data:e,error:null}}function Hm(e){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:i}=e,o=Si(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function zu(e){return e}function qm(e){return e.access_token&&e.refresh_token&&e.expires_in}const oo=["global","local","others"];class Km{constructor({url:t="",headers:n={},fetch:r}){this.url=t,this.headers=n,this.fetch=mh(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(t,n=oo[0]){if(oo.indexOf(n)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${oo.join(", ")}`);try{return await P(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(R(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,n={}){try{return await P(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:wt})}catch(r){if(R(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:n}=t,r=Si(t,["options"]),s=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(s.new_email=r==null?void 0:r.newEmail,delete s.newEmail),await P(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Hm,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(R(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(t){try{return await P(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:wt})}catch(n){if(R(n))return{data:{user:null},error:n};throw n}}async listUsers(t){var n,r,s,i,o,a,l;try{const u={nextPage:null,lastPage:0,total:0},c=await P(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:zu});if(c.error)throw c.error;const p=await c.json(),h=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(v=>{const y=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),S=JSON.parse(v.split(";")[1].split("=")[1]);u[`${S}Page`]=y}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},p),u),error:null}}catch(u){if(R(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){ln(t);try{return await P(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:wt})}catch(n){if(R(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){ln(t);try{return await P(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:wt})}catch(r){if(R(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){ln(t);try{return await P(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:wt})}catch(r){if(R(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){ln(t.userId);try{const{data:n,error:r}=await P(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:n,error:r}}catch(n){if(R(n))return{data:null,error:n};throw n}}async _deleteFactor(t){ln(t.userId),ln(t.id);try{return{data:await P(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(R(n))return{data:null,error:n};throw n}}async _listOAuthClients(t){var n,r,s,i,o,a,l;try{const u={nextPage:null,lastPage:0,total:0},c=await P(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:zu});if(c.error)throw c.error;const p=await c.json(),h=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(v=>{const y=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),S=JSON.parse(v.split(";")[1].split("=")[1]);u[`${S}Page`]=y}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},p),u),error:null}}catch(u){if(R(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(t){try{return await P(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(R(n))return{data:null,error:n};throw n}}async _getOAuthClient(t){try{return await P(this.fetch,"GET",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(R(n))return{data:null,error:n};throw n}}async _updateOAuthClient(t,n){try{return await P(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${t}`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(R(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(t){try{return await P(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(R(n))return{data:null,error:n};throw n}}async _regenerateOAuthClientSecret(t){try{return await P(this.fetch,"POST",`${this.url}/admin/oauth/clients/${t}/regenerate_secret`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(R(n))return{data:null,error:n};throw n}}}function Bu(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}const un={debug:!!(globalThis&&gh()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class vh extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class Gm extends vh{}async function Jm(e,t,n){un.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),un.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async s=>{if(s){un.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await n()}finally{un.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}else{if(t===0)throw un.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new Gm(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(un.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await n()}}))}function Qm(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function yh(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function Ym(e){return parseInt(e,16)}function Xm(e){const t=new TextEncoder().encode(e);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function Zm(e){var t;const{chainId:n,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:u,scheme:c,uri:p,version:h}=e;{if(!Number.isInteger(n))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${n}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!p)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(h!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(!((t=e.statement)===null||t===void 0)&&t.includes(` `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}const m=yh(e.address),v=c?`${c}://${r}`:r,y=e.statement?`${e.statement} `:"",S=`${v} wants you to sign in with your Ethereum account: ${m} ${y}`;let f=`URI: ${p} Version: ${h} Chain ID: ${n}${o?` Nonce: ${o}`:""} Issued At: ${i.toISOString()}`;if(s&&(f+=` Expiration Time: ${s.toISOString()}`),a&&(f+=` Not Before: ${a.toISOString()}`),l&&(f+=` Request ID: ${l}`),u){let d=` Resources:`;for(const g of u){if(!g||typeof g!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${g}`);d+=` - ${g}`}f+=d}return`${S} ${f}`}class X extends Error{constructor({message:t,code:n,cause:r,name:s}){var i;super(t,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=n}}class ri extends X{constructor(t,n){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n,message:t}),this.name="WebAuthnUnknownError",this.originalError=n}}function ev({error:e,options:t}){var n,r,s;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new X({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.requireResidentKey)===!0)return new X({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new X({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new X({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new X({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new X({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new X({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new X({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){const o=window.location.hostname;if(wh(o)){if(i.rp.id!==o)return new X({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new X({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new X({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new X({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 X({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function tv({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new X({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new X({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){const r=window.location.hostname;if(wh(r)){if(n.rpId!==r)return new X({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new X({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new X({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 X({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class nv{createNewAbortSignal(){if(this.controller){const n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n)}const t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){const t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}}const rv=new nv;function sv(e){if(!e)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:n,excludeCredentials:r}=e,s=Si(e,["challenge","user","excludeCredentials"]),i=In(t).buffer,o=Object.assign(Object.assign({},n),{id:In(n.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){a.excludeCredentials=new Array(r.length);for(let l=0;l0){i.allowCredentials=new Array(n.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),n=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(const s of e)if(s)for(const i in s){const o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(n(o))r[i]=o;else if(t(o)){const a=r[i];t(a)?r[i]=si(a,o):r[i]=si(o)}else r[i]=o}return r}function hv(e,t){return si(cv,e,t||{})}function fv(e,t){return si(dv,e,t||{})}class pv{constructor(t){this.client=t,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(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:n,friendlyName:r,signal:s},i){var o;try{const{data:a,error:l}=await this.client.mfa.challenge({factorId:t,webauthn:n});if(!a)return{data:null,error:l};const u=s??rv.createNewAbortSignal();if(a.webauthn.type==="create"){const{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){const p=r;if(p)c.name=`${c.id}:${p}`;else{const m=(await this.client.getUser()).data.user,v=((o=m==null?void 0:m.user_metadata)===null||o===void 0?void 0:o.name)||(m==null?void 0:m.email)||(m==null?void 0:m.id)||"User";c.name=`${c.id}:${v}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{const c=hv(a.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:p,error:h}=await lv({publicKey:c,signal:u});return p?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:p}},error:null}:{data:null,error:h}}case"request":{const c=fv(a.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:p,error:h}=await uv(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));return p?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:p}},error:null}:{data:null,error:h}}}}catch(a){return R(a)?{data:null,error:a}:{data:null,error:new Wt("Unexpected error in challenge",a)}}}async _verify({challengeId:t,factorId:n,webauthn:r}){return this.client.mfa.verify({factorId:n,challengeId:t,webauthn:r})}async _authenticate({factorId:t,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!n)return{data:null,error:new zr("rpId is required for WebAuthn authentication")};try{if(!Mu())return{data:null,error:new Wt("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this.challenge({factorId:t,webauthn:{rpId:n,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:a};const{webauthn:l}=o;return this._verify({factorId:t,challengeId:o.challengeId,webauthn:{type:l.type,rpId:n,rpOrigins:r,credential_response:l.credential_response}})}catch(o){return R(o)?{data:null,error:o}:{data:null,error:new Wt("Unexpected error in authenticate",o)}}}async _register({friendlyName:t,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!n)return{data:null,error:new zr("rpId is required for WebAuthn registration")};try{if(!Mu())return{data:null,error:new Wt("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this._enroll({friendlyName:t});if(!o)return await this.client.mfa.listFactors().then(c=>{var p;return(p=c.data)===null||p===void 0?void 0:p.all.find(h=>h.factor_type==="webauthn"&&h.friendly_name===t&&h.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c==null?void 0:c.id}):void 0),{data:null,error:a};const{data:l,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:n,rpOrigins:r},signal:s},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:n,rpOrigins:r,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(o){return R(o)?{data:null,error:o}:{data:null,error:new Wt("Unexpected error in register",o)}}}}Qm();const gv={url:dm,storageKey:hm,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:fm,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function Fu(e,t,n){return await n()}const cn={};class Br{get jwks(){var t,n;return(n=(t=cn[this.storageKey])===null||t===void 0?void 0:t.jwks)!==null&&n!==void 0?n:{keys:[]}}set jwks(t){cn[this.storageKey]=Object.assign(Object.assign({},cn[this.storageKey]),{jwks:t})}get jwks_cached_at(){var t,n;return(n=(t=cn[this.storageKey])===null||t===void 0?void 0:t.cachedAt)!==null&&n!==void 0?n:Number.MIN_SAFE_INTEGER}set jwks_cached_at(t){cn[this.storageKey]=Object.assign(Object.assign({},cn[this.storageKey]),{cachedAt:t})}constructor(t){var n,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},gv),t);if(this.storageKey=i.storageKey,this.instanceID=(n=Br.nextInstanceID[this.storageKey])!==null&&n!==void 0?n:0,Br.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&ae()){const o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Km({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=mh(i.fetch),this.lock=i.lock||Fu,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&ae()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=Jm:this.lock=Fu,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 pv(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:gh()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Bu(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Bu(this.memoryStorage)),ae()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(t){if(this.throwOnError&&t&&t.error)throw t.error;return t}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${hh}) ${new Date().toISOString()}`}_debug(...t){return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var t;try{let n={},r="none";if(ae()&&(n=Om(window.location.href),this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce")),ae()&&this.detectSessionInUrl&&r!=="none"){const{data:s,error:i}=await this._getSessionFromURL(n,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),ym(i)){const l=(t=i.details)===null||t===void 0?void 0:t.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:o,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(n){return R(n)?this._returnResult({error:n}):this._returnResult({error:new Wt("Unexpected error during initialization",n)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,s;try{const i=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=t==null?void 0:t.options)===null||s===void 0?void 0:s.captchaToken}},xform:Me}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(R(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(t){var n,r,s;try{let i;if("email"in t){const{email:c,password:p,options:h}=t;let m=null,v=null;this.flowType==="pkce"&&([m,v]=await an(this.storage,this.storageKey)),i=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h==null?void 0:h.emailRedirectTo,body:{email:c,password:p,data:(n=h==null?void 0:h.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken},code_challenge:m,code_challenge_method:v},xform:Me})}else if("phone"in t){const{phone:c,password:p,options:h}=t;i=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:p,data:(r=h==null?void 0:h.data)!==null&&r!==void 0?r:{},channel:(s=h==null?void 0:h.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:Me})}else throw new vs("You must provide either an email or phone number and a password");const{data:o,error:a}=i;if(a||!o)return await oe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(t){try{let n;if("email"in t){const{email:i,password:o,options:a}=t;n=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Du})}else if("phone"in t){const{phone:i,password:o,options:a}=t;n=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Du})}else throw new vs("You must provide either an email or phone number and a password");const{data:r,error:s}=n;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const i=new on;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(n){if(R(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOAuth(t){var n,r,s,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=t.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(t))}async signInWithWeb3(t){const{chain:n}=t;switch(n){case"ethereum":return await this.signInWithEthereum(t);case"solana":return await this.signInWithSolana(t);default:throw new Error(`@supabase/auth-js: Unsupported chain "${n}"`)}}async signInWithEthereum(t){var n,r,s,i,o,a,l,u,c,p,h;let m,v;if("message"in t)m=t.message,v=t.signature;else{const{chain:y,wallet:S,statement:f,options:d}=t;let g;if(ae())if(typeof S=="object")g=S;else{const U=window;if("ethereum"in U&&typeof U.ethereum=="object"&&"request"in U.ethereum&&typeof U.ethereum.request=="function")g=U.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof S!="object"||!(d!=null&&d.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");g=S}const w=new URL((n=d==null?void 0:d.url)!==null&&n!==void 0?n:window.location.href),E=await g.request({method:"eth_requestAccounts"}).then(U=>U).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!E||E.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const T=yh(E[0]);let b=(r=d==null?void 0:d.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!b){const U=await g.request({method:"eth_chainId"});b=Ym(U)}const x={domain:w.host,address:T,statement:f,uri:w.href,version:"1",chainId:b,nonce:(s=d==null?void 0:d.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=d==null?void 0:d.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=d==null?void 0:d.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=d==null?void 0:d.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=d==null?void 0:d.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=d==null?void 0:d.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=Zm(x),v=await g.request({method:"personal_sign",params:[Xm(m),T]})}try{const{data:y,error:S}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:v},!((p=t.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(h=t.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:Me});if(S)throw S;if(!y||!y.session||!y.user){const f=new on;return this._returnResult({data:{user:null,session:null},error:f})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:S})}catch(y){if(R(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async signInWithSolana(t){var n,r,s,i,o,a,l,u,c,p,h,m;let v,y;if("message"in t)v=t.message,y=t.signature;else{const{chain:S,wallet:f,statement:d,options:g}=t;let w;if(ae())if(typeof f=="object")w=f;else{const T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))w=T.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof f!="object"||!(g!=null&&g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=f}const E=new URL((n=g==null?void 0:g.url)!==null&&n!==void 0?n:window.location.href);if("signIn"in w&&w.signIn){const T=await w.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},g==null?void 0:g.signInWithSolana),{version:"1",domain:E.host,uri:E.href}),d?{statement:d}:null));let b;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")b=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)b=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in b&&"signature"in b&&(typeof b.signedMessage=="string"||b.signedMessage instanceof Uint8Array)&&b.signature instanceof Uint8Array)v=typeof b.signedMessage=="string"?b.signedMessage:new TextDecoder().decode(b.signedMessage),y=b.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in w)||typeof w.signMessage!="function"||!("publicKey"in w)||typeof w!="object"||!w.publicKey||!("toBase58"in w.publicKey)||typeof w.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");v=[`${E.host} wants you to sign in with your Solana account:`,w.publicKey.toBase58(),...d?["",d,""]:[""],"Version: 1",`URI: ${E.href}`,`Issued At: ${(s=(r=g==null?void 0:g.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=g==null?void 0:g.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${g.signInWithSolana.notBefore}`]:[],...!((o=g==null?void 0:g.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${g.signInWithSolana.expirationTime}`]:[],...!((a=g==null?void 0:g.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${g.signInWithSolana.chainId}`]:[],...!((l=g==null?void 0:g.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${g.signInWithSolana.nonce}`]:[],...!((u=g==null?void 0:g.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${g.signInWithSolana.requestId}`]:[],...!((p=(c=g==null?void 0:g.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||p===void 0)&&p.length?["Resources",...g.signInWithSolana.resources.map(b=>`- ${b}`)]:[]].join(` `);const T=await w.signMessage(new TextEncoder().encode(v),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");y=T}}try{const{data:S,error:f}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:v,signature:Kt(y)},!((h=t.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(m=t.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Me});if(f)throw f;if(!S||!S.session||!S.user){const d=new on;return this._returnResult({data:{user:null,session:null},error:d})}return S.session&&(await this._saveSession(S.session),await this._notifyAllSubscribers("SIGNED_IN",S.session)),this._returnResult({data:Object.assign({},S),error:f})}catch(S){if(R(S))return this._returnResult({data:{user:null,session:null},error:S});throw S}}async _exchangeCodeForSession(t){const n=await Dt(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(n??"").split("/");try{if(!r&&this.flowType==="pkce")throw new wm;const{data:i,error:o}=await P(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:Me});if(await oe(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){const a=new on;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:o})}catch(i){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(t){try{const{options:n,provider:r,token:s,access_token:i,nonce:o}=t,a=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:Me}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){const c=new on;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(n){if(R(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOtp(t){var n,r,s,i,o;try{if("email"in t){const{email:a,options:l}=t;let u=null,c=null;this.flowType==="pkce"&&([u,c]=await an(this.storage,this.storageKey));const{error:p}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(n=l==null?void 0:l.data)!==null&&n!==void 0?n:{},create_user:(r=l==null?void 0:l.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in t){const{phone:a,options:l}=t,{data:u,error:c}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l==null?void 0:l.data)!==null&&s!==void 0?s:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:c})}throw new vs("You must provide either an email or phone number.")}catch(a){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(t){var n,r;try{let s,i;"options"in t&&(s=(n=t.options)===null||n===void 0?void 0:n.redirectTo,i=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:a}=await P(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Me});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,u=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(R(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(t){var n,r,s,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await an(this.storage,this.storageKey));const u=await P(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=t==null?void 0:t.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:Vm});return!((i=u.data)===null||i===void 0)&&i.url&&ae()&&!(!((o=t.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new Te;const{error:s}=await P(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(t){if(R(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async resend(t){try{const n=`${this.url}/resend`;if("email"in t){const{email:r,type:s,options:i}=t,{error:o}=await P(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in t){const{phone:r,type:s,options:i}=t,{data:o,error:a}=await P(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a})}throw new vs("You must provide either an email or phone number and a type")}catch(n){if(R(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}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 t=null;const n=await Dt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at*1e3-Date.now()await this._getUser());return n.data.user&&(this.suppressGetSessionWarning=!0),n}async _getUser(t){try{return t?await P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:wt}):await this._useSession(async n=>{var r,s,i;const{data:o,error:a}=n;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Te}:await P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:wt})})}catch(n){if(R(n))return ro(n)&&(await this._removeSession(),await oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:n});throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{const{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new Te;const o=s.session;let a=null,l=null;this.flowType==="pkce"&&t.email!=null&&([a,l]=await an(this.storage,this.storageKey));const{data:u,error:c}=await P(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:wt});if(c)throw c;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(r){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(t){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new Te;const n=Date.now()/1e3;let r=n,s=!0,i=null;const{payload:o}=ws(t.access_token);if(o.exp&&(r=o.exp,s=r<=n),s){const{data:a,error:l}=await this._callRefreshToken(t.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:l}=await this._getUser(t.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:t.access_token,refresh_token:t.refresh_token,user:a.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(n){if(R(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){const{data:o,error:a}=n;if(a)throw a;t=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new Te;const{data:s,error:i}=await this._callRefreshToken(t.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(n){if(R(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async _getSessionFromURL(t,n){try{if(!ae())throw new ys("No browser detected.");if(t.error||t.error_description||t.error_code)throw new ys(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new Au("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ys("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new Au("No code detected.");const{data:d,error:g}=await this._exchangeCodeForSession(t.code);if(g)throw g;const w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:d.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:u}=t;if(!i||!a||!o||!u)throw new ys("No session defined in URL");const c=Math.round(Date.now()/1e3),p=parseInt(a);let h=c+p;l&&(h=parseInt(l));const m=h-c;m*1e3<=hn&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${p}s`);const v=h-p;c-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,h,c):c-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,h,c);const{data:y,error:S}=await this._getUser(i);if(S)throw S;const f={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:p,expires_at:h,refresh_token:o,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:f,redirectType:t.type},error:null})}catch(r){if(R(r))return this._returnResult({data:{session:null,redirectType:null},error:r});throw r}}_isImplicitGrantCallback(t){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),t):!!(t.access_token||t.error_description)}async _isPKCECallback(t){const n=await Dt(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i&&!ro(i))return this._returnResult({error:i});const o=(r=s.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:a}=await this.admin.signOut(o,t);if(a&&!(vm(a)&&(a.status===404||a.status===401||a.status===403)||ro(a)))return this._returnResult({error:a})}return t!=="others"&&(await this._removeSession(),await oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(t){const n=Cm(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,s;try{const{data:{session:i},error:o}=n;if(o)throw o;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(t))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),console.error(i)}})}async resetPasswordForEmail(t,n={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await an(this.storage,this.storageKey,!0));try{return await P(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(i){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async linkIdentity(t){return"token"in t?this.linkIdentityIdToken(t):this.linkIdentityOAuth(t)}async linkIdentityOAuth(t){var n;try{const{data:r,error:s}=await this._useSession(async i=>{var o,a,l,u,c;const{data:p,error:h}=i;if(h)throw h;const m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(o=t.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=t.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=t.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await P(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=p.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(s)throw s;return ae()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),this._returnResult({data:{provider:t.provider,url:r==null?void 0:r.url},error:null})}catch(r){if(R(r))return this._returnResult({data:{provider:t.provider,url:null},error:r});throw r}}async linkIdentityIdToken(t){return await this._useSession(async n=>{var r;try{const{error:s,data:{session:i}}=n;if(s)throw s;const{options:o,provider:a,token:l,access_token:u,nonce:c}=t,p=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i==null?void 0:i.access_token)!==null&&r!==void 0?r:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Me}),{data:h,error:m}=p;return m?this._returnResult({data:{user:null,session:null},error:m}):!h||!h.session||!h.user?this._returnResult({data:{user:null,session:null},error:new on}):(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:m}))}catch(s){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,s;const{data:i,error:o}=n;if(o)throw o;return await P(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async _refreshAccessToken(t){const n=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await Pm(async s=>(s>0&&await Rm(200*Math.pow(2,s-1)),this._debug(n,"refreshing attempt",s),await P(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:Me})),(s,i)=>{const o=200*Math.pow(2,s);return i&&so(i)&&Date.now()+o-r{try{await a.callback(t,n)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;athis._autoRefreshTokenTick(),hn);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t);const n=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=n,n&&typeof n=="object"&&typeof n.unref=="function"?n.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(n)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t);const n=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,n&&clearTimeout(n)}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 t=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((r.expires_at*1e3-t)/hn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${hn}ms, refresh threshold is ${la} ticks`),s<=la&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof vh)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ae()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(t){this._debug("#visibilityChangedCallback","error",t)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,n,r){const s=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,o]=await an(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(r!=null&&r.queryParams){const i=new URLSearchParams(r.queryParams);s.push(i.toString())}return r!=null&&r.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${s.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;return i?this._returnResult({data:null,error:i}):await P(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,s;const{data:i,error:o}=n;if(o)return this._returnResult({data:null,error:o});const a=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:t.factorType==="totp"?{issuer:t.issuer}:{}),{data:l,error:u}=await P(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(t.factorType==="totp"&&l.type==="totp"&&(!((s=l==null?void 0:l.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async _verify(t){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({challenge_id:t.challengeId},"webauthn"in t?{webauthn:Object.assign(Object.assign({},t.webauthn),{credential_response:t.webauthn.type==="create"?ov(t.webauthn.credential_response):av(t.webauthn.credential_response)})}:{code:t.code}),{data:a,error:l}=await P(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:o,headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}})}async _challenge(t){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i)return this._returnResult({data:null,error:i});const o=await P(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:t,headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});if(o.error)return o;const{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:sv(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:iv(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}})}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){var t;const{data:{user:n},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const i of(t=n==null?void 0:n.factors)!==null&&t!==void 0?t:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(t){var n,r,s,i;if(t)try{const{payload:m}=ws(t);let v=null;m.aal&&(v=m.aal);let y=v;const{data:{user:S},error:f}=await this.getUser(t);if(f)return this._returnResult({data:null,error:f});((r=(n=S==null?void 0:S.factors)===null||n===void 0?void 0:n.filter(w=>w.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(y="aal2");const g=m.amr||[];return{data:{currentLevel:v,nextLevel:y,currentAuthenticationMethods:g},error:null}}catch(m){if(R(m))return this._returnResult({data:null,error:m});throw m}const{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=ws(o.access_token);let u=null;l.aal&&(u=l.aal);let c=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(m=>m.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(c="aal2");const h=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:h},error:null}}async _getAuthorizationDetails(t){try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;return s?this._returnResult({data:null,error:s}):r?await P(this.fetch,"GET",`${this.url}/oauth/authorizations/${t}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Te})})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async _approveAuthorization(t,n){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Te});const o=await P(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&ae()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(R(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(t,n){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Te});const o=await P(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&ae()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(R(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await P(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Te})})}catch(t){if(R(t))return this._returnResult({data:null,error:t});throw t}}async _revokeOAuthGrant(t){try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;return s?this._returnResult({data:null,error:s}):r?(await P(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:t.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Te})})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async fetchJwk(t,n={keys:[]}){let r=n.keys.find(a=>a.kid===t);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(a=>a.kid===t),r&&this.jwks_cached_at+gm>s)return r;const{data:i,error:o}=await P(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(a=>a.kid===t),!r)?null:r}async getClaims(t,n={}){try{let r=t;if(!r){const{data:m,error:v}=await this.getSession();if(v||!m.session)return this._returnResult({data:null,error:v});r=m.session.access_token}const{header:s,payload:i,signature:o,raw:{header:a,payload:l}}=ws(r);n!=null&&n.allowExpired||Um(i.exp);const u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,n!=null&&n.keys?{keys:n.keys}:n==null?void 0:n.jwks);if(!u){const{error:m}=await this.getUser(r);if(m)throw m;return{data:{claims:i,header:s,signature:o},error:null}}const c=Dm(s.alg),p=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,p,o,Tm(`${a}.${l}`)))throw new da("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(R(r))return this._returnResult({data:null,error:r});throw r}}}Br.nextInstanceID={};const mv=Br,vv="2.95.3";let or="";typeof Deno<"u"?or="deno":typeof document<"u"?or="web":typeof navigator<"u"&&navigator.product==="ReactNative"?or="react-native":or="node";const yv={"X-Client-Info":`supabase-js-${or}/${vv}`},wv={headers:yv},_v={schema:"public"},Sv={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},kv={};function Mr(e){"@babel/helpers - typeof";return Mr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Mr(e)}function Ev(e,t){if(Mr(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Mr(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Tv(e){var t=Ev(e,"string");return Mr(t)=="symbol"?t:t+""}function bv(e,t,n){return(t=Tv(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Wu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function G(e){for(var t=1;te?(...t)=>e(...t):(...t)=>fetch(...t),Ov=()=>Headers,xv=(e,t,n)=>{const r=Cv(n),s=Ov();return async(i,o)=>{var a;const l=(a=await t())!==null&&a!==void 0?a:e;let u=new s(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",e),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),r(i,G(G({},o),{},{headers:u}))}};function Rv(e){return e.endsWith("/")?e:e+"/"}function Pv(e,t){var n,r;const{db:s,auth:i,realtime:o,global:a}=e,{db:l,auth:u,realtime:c,global:p}=t,h={db:G(G({},l),s),auth:G(G({},u),i),realtime:G(G({},c),o),storage:{},global:G(G(G({},p),a),{},{headers:G(G({},(n=p==null?void 0:p.headers)!==null&&n!==void 0?n:{}),(r=a==null?void 0:a.headers)!==null&&r!==void 0?r:{})}),accessToken:async()=>""};return e.accessToken?h.accessToken=e.accessToken:delete h.accessToken,h}function Av(e){const t=e==null?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(Rv(t))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var jv=class extends mv{constructor(e){super(e)}},Iv=class{constructor(e,t,n){var r,s;this.supabaseUrl=e,this.supabaseKey=t;const i=Av(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={db:_v,realtime:kv,auth:G(G({},Sv),{},{storageKey:o}),global:wv},l=Pv(n??{},a);if(this.storageKey=(r=l.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(s=l.global.headers)!==null&&s!==void 0?s:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=xv(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(G({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new vg(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new cm(this.storageUrl.href,this.headers,this.fetch,n==null?void 0:n.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new ug(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={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}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=this,t,n;if(e.accessToken)return await e.accessToken();const{data:r}=await e.auth.getSession();return(t=(n=r.session)===null||n===void 0?void 0:n.access_token)!==null&&t!==void 0?t:e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:s,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:u},c,p){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new jv({url:this.authUrl.href,headers:G(G({},h),c),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:s,flowType:o,lock:a,debug:l,throwOnError:u,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Ng(this.realtimeUrl.href,G(G({},e),{},{params:G(G({},{apikey:this.supabaseKey}),e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",t==null?void 0:t.access_token)})}_handleTokenChanged(e,t,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const Nv=(e,t,n)=>new Iv(e,t,n);function Lv(){if(typeof window<"u")return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(t==null)return!1;const n=t.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=18:!1}Lv()&&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 _h="https://tnurlgbvfsxwqgwxamni.supabase.co",$v="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InRudXJsZ2J2ZnN4d3Fnd3hhbW5pIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDQ5MTQ1OTksImV4cCI6MjA2MDQ5MDU5OX0.9__EQiZDJ954SmeeJIDTQjOYDjiiRcppai1e8UpuOl4";console.log("Initializing Supabase client with URL:",_h);const $e=Nv(_h,$v,{db:{schema:"public"}});console.log("Supabase client initialized for schema: openclaw");function Uv(){const[e,t]=W.useState([]),[n,r]=W.useState(!0);return W.useEffect(()=>{(async()=>{console.log("Fetching tasks...");const{data:o,error:a}=await $e.from("agent_tasks").select("*").order("updated_at",{ascending:!1});a&&console.error("Error fetching tasks:",a),o&&(console.log("Tasks fetched:",o.length),t(o)),r(!1)})();const i=$e.channel("tasks-changes").on("postgres_changes",{event:"*",schema:"public",table:"agent_tasks"},o=>{o.eventType==="INSERT"?t(a=>[o.new,...a]):o.eventType==="UPDATE"?t(a=>a.map(l=>l.id===o.new.id?o.new:l)):o.eventType==="DELETE"&&t(a=>a.filter(l=>l.id===o.old.id))}).subscribe();return()=>{$e.removeChannel(i)}},[]),{tasks:e,loading:n}}function Dv(e=20){const[t,n]=W.useState([]),[r,s]=W.useState(!0);return W.useEffect(()=>{(async()=>{console.log("Fetching logs...");const{data:a,error:l}=await $e.from("agent_logs").select("*").order("created_at",{ascending:!1}).limit(e);l&&console.error("Error fetching logs:",l),a&&(console.log("Logs fetched:",a.length),n(a)),s(!1)})();const o=$e.channel("logs-changes").on("postgres_changes",{event:"INSERT",schema:"public",table:"agent_logs"},a=>{n(l=>[a.new,...l.slice(0,e-1)])}).subscribe();return()=>{$e.removeChannel(o)}},[e]),{logs:t,loading:r}}const zv=[{name:"Jasmine",id:"Jasmine",role:"Atendimento ao Cliente",desc:"Especialista em recepção e suporte via Telegram/WhatsApp.",powers:{Simpatia:"10/10",Resolução:"8/10"},img:"jasmine_3d.png"},{name:"Shuri",id:"Shuri",role:"Arquitetura e Dev",desc:"Gênio técnica focada em infraestrutura e lógica central.",powers:{Inteligência:"10/10",Lógica:"9/10"},img:"shuri_3d.png"},{name:"Atlas",id:"Atlas",role:"Estrategista de Dados",desc:"Análise detalhada de mercado e inteligência competitiva.",powers:{Análise:"10/10",Estratégia:"9/10"},img:"atlas_3d.png"},{name:"Orion",id:"Orion",role:"Monitor de Marketing",desc:"Vigilância constante de tendências e campanhas.",powers:{Ads:"9/10",Criatividade:"8/10"},img:"orion_3d.png"},{name:"Quill",id:"Quill",role:"Monitor de Competidores",desc:"Especialista em monitoramento de concorrência e social.",powers:{Espionagem:"9/10",Copy:"9/10"},img:"quill_3d.png"}];function Bv(){const[e,t]=W.useState(zv.map(n=>({...n,status:"offline",load:"0%"})));return W.useEffect(()=>{(async()=>{console.log("Fetching presence...");const{data:s,error:i}=await $e.from("agent_presence").select("*");i&&console.error("Error fetching presence:",i),s&&(console.log("Presence fetched:",s.length),t(o=>o.map(a=>{const l=s.find(u=>u.agent_id===a.id);return l?{...a,status:l.status,load:"Em operação"}:a})))})();const r=$e.channel("presence-changes").on("postgres_changes",{event:"*",schema:"public",table:"agent_presence"},s=>{t(i=>i.map(o=>{var a,l;return o.id===((a=s.new)==null?void 0:a.agent_id)||o.id===((l=s.old)==null?void 0:l.agent_id)?{...o,...s.new}:o}))}).subscribe();return()=>{$e.removeChannel(r)}},[]),{agents:e}}const ao="8da141f8-25d5-44d3-8652-fe0052dde949",Vu=2;function ha(e){return typeof e=="number"?e:typeof e=="string"&&Number(e.replace(",","."))||0}function Mv(e){const t=Array.isArray(e)?e[0]:e;if(!t)return{payload:[],summary:null,snapshot_date:null};if(Array.isArray(t))return{payload:t,summary:null,snapshot_date:null};const n=Array.isArray(t.payload)?t.payload:Array.isArray(e)?e:[],r=t.summary||null,s=t.snapshot_date||null;return{payload:n,summary:r,snapshot_date:s}}function Hu(e){const t=e.length;let n=0,r=0,s=0,i=0;const o=e.map(a=>{const l=Array.isArray(a.accounts)?a.accounts:[],u=ha(a.total_balance),c=Number(a.days_since_last_input||0),p=l.filter(h=>ha(h.balance)<0);return c>=Vu&&(s+=1),p.length>0&&(i+=1),u<0&&(r+=1),n+=u,{...a,total_balance:u,days_since_last_input:c,negative_accounts_count:p.length,negative_accounts:p}});return o.sort((a,l)=>l.total_balance-a.total_balance),{units:o,summary:{total_units:t,consolidated_balance:n,risk_units:r,stale_units:s,units_with_negative_accounts:i,stale_threshold_days:Vu}}}function Fv(){const[e,t]=W.useState(new Date().toISOString().slice(0,10)),[n,r]=W.useState(!0),[s,i]=W.useState(null),[o,a]=W.useState({units:[],summary:null,snapshot_date:null}),[l,u]=W.useState([]),c=W.useCallback(async m=>{r(!0),i(null);const v={p_organization_id:ao,p_snapshot_date:m},{data:y,error:S}=await $e.rpc("fn_cashflow_snapshot_get",v);if(S){const w=await $e.rpc("get_units_financial_summary",{p_organization_id:ao});if(w.error){i(`Erro RPC snapshot: ${S.message}. Fallback também falhou: ${w.error.message}`),a({units:[],summary:null,snapshot_date:m}),r(!1);return}const{units:E,summary:T}=Hu(Array.isArray(w.data)?w.data:[]);a({units:E,summary:T,snapshot_date:m}),r(!1);return}const f=Mv(y);if(f.summary){const w=Array.isArray(f.payload)?f.payload.map(E=>({...E,total_balance:ha(E.total_balance),days_since_last_input:Number(E.days_since_last_input||0),accounts:Array.isArray(E.accounts)?E.accounts:[]})):[];w.sort((E,T)=>T.total_balance-E.total_balance),a({units:w,summary:f.summary,snapshot_date:f.snapshot_date||m}),r(!1);return}const{units:d,summary:g}=Hu(f.payload||[]);a({units:d,summary:g,snapshot_date:f.snapshot_date||m}),r(!1)},[]),p=W.useCallback(async m=>{const v=new Date(m||new Date().toISOString().slice(0,10)),y=v.toISOString().slice(0,10),S=new Date(v.getTime()-1e3*60*60*24*90).toISOString().slice(0,10),{data:f,error:d}=await $e.rpc("fn_cashflow_snapshot_range",{p_organization_id:ao,p_from:S,p_to:y});if(d){u([]);return}u(Array.isArray(f)?f:[])},[]);W.useEffect(()=>{c(e),p(e)},[e,c,p]);const h=W.useMemo(()=>o.units.slice(0,5),[o.units]);return{loading:n,error:s,selectedDate:e,setSelectedDate:t,snapshot:o,history:l,topFive:h,refresh:()=>c(e)}}function Wv(){const[e,t]=W.useState("cashflow"),[n,r]=W.useState(null);Uv(),Dv(),Bv();const{loading:s,error:i,selectedDate:o,setSelectedDate:a,snapshot:l,history:u,topFive:c,refresh:p}=Fv(),h=W.useMemo(()=>"Albert Finance - Fluxo de Caixa",[e]),m="Finance Monitor Online";return W.useEffect(()=>{if(!l.units.length){r(null);return}const v=n?l.units.some(y=>y.unit_id===n.unit_id):!1;if(!v&&!n){r(l.units[0]);return}!v&&n&&r(l.units[0])},[l.units,n]),_.jsxs("div",{className:"dashboard-container cashflow-only",children:[!1,_.jsx(Yp,{title:h,status:m}),_.jsx("main",{className:"area main-content",children:_.jsxs("section",{className:"cashflow-layout",children:[_.jsx(ng,{selectedDate:o,onDateChange:a,onRefresh:p}),i&&_.jsx("div",{className:"cashflow-error",children:i}),s?_.jsx("div",{className:"loading-state",children:"Carregando fluxo de caixa..."}):_.jsxs(_.Fragment,{children:[_.jsx(Zp,{summary:l.summary,snapshotDate:l.snapshot_date||o}),_.jsx(tg,{units:l.units,onSelectUnit:r,selectedUnitId:n==null?void 0:n.unit_id}),_.jsx(rg,{unit:n||c[0]}),_.jsx(ig,{history:u})]})]})}),!1,!1]})}lo.createRoot(document.getElementById("root")).render(_.jsx(Dh.StrictMode,{children:_.jsx(Wv,{})}));