(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))a(c);new MutationObserver(c=>{for(const f of c)if(f.type==="childList")for(const p of f.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&a(p)}).observe(document,{childList:!0,subtree:!0});function s(c){const f={};return c.integrity&&(f.integrity=c.integrity),c.referrerPolicy&&(f.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?f.credentials="include":c.crossOrigin==="anonymous"?f.credentials="omit":f.credentials="same-origin",f}function a(c){if(c.ep)return;c.ep=!0;const f=s(c);fetch(c.href,f)}})();function yh(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var ru={exports:{}},ws={},nu={exports:{}},ve={};var Nf;function xm(){if(Nf)return ve;Nf=1;var r=Symbol.for("react.element"),n=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),c=Symbol.for("react.profiler"),f=Symbol.for("react.provider"),p=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),R=Symbol.for("react.lazy"),N=Symbol.iterator;function j(w){return w===null||typeof w!="object"?null:(w=N&&w[N]||w["@@iterator"],typeof w=="function"?w:null)}var O={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},q=Object.assign,Q={};function $(w,E,ee){this.props=w,this.context=E,this.refs=Q,this.updater=ee||O}$.prototype.isReactComponent={},$.prototype.setState=function(w,E){if(typeof w!="object"&&typeof w!="function"&&w!=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,w,E,"setState")},$.prototype.forceUpdate=function(w){this.updater.enqueueForceUpdate(this,w,"forceUpdate")};function fe(){}fe.prototype=$.prototype;function T(w,E,ee){this.props=w,this.context=E,this.refs=Q,this.updater=ee||O}var A=T.prototype=new fe;A.constructor=T,q(A,$.prototype),A.isPureReactComponent=!0;var L=Array.isArray,J=Object.prototype.hasOwnProperty,Y={current:null},ge={key:!0,ref:!0,__self:!0,__source:!0};function me(w,E,ee){var ne,te={},le=null,ie=null;if(E!=null)for(ne in E.ref!==void 0&&(ie=E.ref),E.key!==void 0&&(le=""+E.key),E)J.call(E,ne)&&!ge.hasOwnProperty(ne)&&(te[ne]=E[ne]);var he=arguments.length-2;if(he===1)te.children=ee;else if(1>>1,E=M[w];if(0>>1;wc(te,z))lec(ie,te)?(M[w]=ie,M[le]=z,w=le):(M[w]=te,M[ne]=z,w=ne);else if(lec(ie,z))M[w]=ie,M[le]=z,w=le;else break e}}return H}function c(M,H){var z=M.sortIndex-H.sortIndex;return z!==0?z:M.id-H.id}if(typeof performance=="object"&&typeof performance.now=="function"){var f=performance;r.unstable_now=function(){return f.now()}}else{var p=Date,v=p.now();r.unstable_now=function(){return p.now()-v}}var y=[],x=[],R=1,N=null,j=3,O=!1,q=!1,Q=!1,$=typeof setTimeout=="function"?setTimeout:null,fe=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function A(M){for(var H=s(x);H!==null;){if(H.callback===null)a(x);else if(H.startTime<=M)a(x),H.sortIndex=H.expirationTime,n(y,H);else break;H=s(x)}}function L(M){if(Q=!1,A(M),!q)if(s(y)!==null)q=!0,P(J);else{var H=s(x);H!==null&&W(L,H.startTime-M)}}function J(M,H){q=!1,Q&&(Q=!1,fe(me),me=-1),O=!0;var z=j;try{for(A(H),N=s(y);N!==null&&(!(N.expirationTime>H)||M&&!We());){var w=N.callback;if(typeof w=="function"){N.callback=null,j=N.priorityLevel;var E=w(N.expirationTime<=H);H=r.unstable_now(),typeof E=="function"?N.callback=E:N===s(y)&&a(y),A(H)}else a(y);N=s(y)}if(N!==null)var ee=!0;else{var ne=s(x);ne!==null&&W(L,ne.startTime-H),ee=!1}return ee}finally{N=null,j=z,O=!1}}var Y=!1,ge=null,me=-1,ue=5,Re=-1;function We(){return!(r.unstable_now()-ReM||125w?(M.sortIndex=z,n(x,M),s(y)===null&&M===s(x)&&(Q?(fe(me),me=-1):Q=!0,W(L,z-w))):(M.sortIndex=E,n(y,M),q||O||(q=!0,P(J))),M},r.unstable_shouldYield=We,r.unstable_wrapCallback=function(M){var H=j;return function(){var z=j;j=H;try{return M.apply(this,arguments)}finally{j=z}}}})(ou)),ou}var jf;function Cm(){return jf||(jf=1,su.exports=bm()),su.exports}var Of;function Tm(){if(Of)return wt;Of=1;var r=Au(),n=Cm();function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,i=1;i"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),y=Object.prototype.hasOwnProperty,x=/^[: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]*$/,R={},N={};function j(e){return y.call(N,e)?!0:y.call(R,e)?!1:x.test(e)?N[e]=!0:(R[e]=!0,!1)}function O(e,t,i,o){if(i!==null&&i.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return o?!1:i!==null?!i.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function q(e,t,i,o){if(t===null||typeof t>"u"||O(e,t,i,o))return!0;if(o)return!1;if(i!==null)switch(i.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 Q(e,t,i,o,l,u,h){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=o,this.attributeNamespace=l,this.mustUseProperty=i,this.propertyName=e,this.type=t,this.sanitizeURL=u,this.removeEmptyString=h}var $={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){$[e]=new Q(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];$[t]=new Q(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){$[e]=new Q(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){$[e]=new Q(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){$[e]=new Q(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){$[e]=new Q(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){$[e]=new Q(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){$[e]=new Q(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){$[e]=new Q(e,5,!1,e.toLowerCase(),null,!1,!1)});var fe=/[\-:]([a-z])/g;function T(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(fe,T);$[t]=new Q(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(fe,T);$[t]=new Q(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(fe,T);$[t]=new Q(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){$[e]=new Q(e,1,!1,e.toLowerCase(),null,!1,!1)}),$.xlinkHref=new Q("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){$[e]=new Q(e,1,!1,e.toLowerCase(),null,!0,!0)});function A(e,t,i,o){var l=$.hasOwnProperty(t)?$[t]:null;(l!==null?l.type!==0:o||!(2m||l[h]!==u[m]){var _=` `+l[h].replace(" at new "," at ");return e.displayName&&_.includes("")&&(_=_.replace("",e.displayName)),_}while(1<=h&&0<=m);break}}}finally{ee=!1,Error.prepareStackTrace=i}return(e=e?e.displayName||e.name:"")?E(e):""}function te(e){switch(e.tag){case 5:return E(e.type);case 16:return E("Lazy");case 13:return E("Suspense");case 19:return E("SuspenseList");case 0:case 2:case 15:return e=ne(e.type,!1),e;case 11:return e=ne(e.type.render,!1),e;case 1:return e=ne(e.type,!0),e;default:return""}}function le(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 ge:return"Fragment";case Y:return"Portal";case ue:return"Profiler";case me:return"StrictMode";case Me:return"Suspense";case it:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case We:return(e.displayName||"Context")+".Consumer";case Re:return(e._context.displayName||"Context")+".Provider";case Le:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ke:return t=e.displayName||null,t!==null?t:le(e.type)||"Memo";case P:t=e._payload,e=e._init;try{return le(e(t))}catch{}}return null}function ie(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 le(t);case 8:return t===me?"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 he(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function we(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function _e(e){var t=we(e)?"checked":"value",i=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),o=""+e[t];if(!e.hasOwnProperty(t)&&typeof i<"u"&&typeof i.get=="function"&&typeof i.set=="function"){var l=i.get,u=i.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(h){o=""+h,u.call(this,h)}}),Object.defineProperty(e,t,{enumerable:i.enumerable}),{getValue:function(){return o},setValue:function(h){o=""+h},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ne(e){e._valueTracker||(e._valueTracker=_e(e))}function Ge(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var i=t.getValue(),o="";return e&&(o=we(e)?e.checked?"true":"false":e.value),e=o,e!==i?(t.setValue(e),!0):!1}function Dt(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 mr(e,t){var i=t.checked;return z({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:i??e._wrapperState.initialChecked})}function Dr(e,t){var i=t.defaultValue==null?"":t.defaultValue,o=t.checked!=null?t.checked:t.defaultChecked;i=he(t.value!=null?t.value:i),e._wrapperState={initialChecked:o,initialValue:i,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Sn(e,t){t=t.checked,t!=null&&A(e,"checked",t,!1)}function zr(e,t){Sn(e,t);var i=he(t.value),o=t.type;if(i!=null)o==="number"?(i===0&&e.value===""||e.value!=i)&&(e.value=""+i):e.value!==""+i&&(e.value=""+i);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Ri(e,t.type,i):t.hasOwnProperty("defaultValue")&&Ri(e,t.type,he(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Ui(e,t,i){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var o=t.type;if(!(o!=="submit"&&o!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,i||t===e.value||(e.value=t),e.defaultValue=t}i=e.name,i!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,i!==""&&(e.name=i)}function Ri(e,t,i){(t!=="number"||Dt(e.ownerDocument)!==e)&&(i==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+i&&(e.defaultValue=""+i))}var Fr=Array.isArray;function yr(e,t,i,o){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=xt.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function $r(e,t){if(t){var i=e.firstChild;if(i&&i===e.lastChild&&i.nodeType===3){i.nodeValue=t;return}}e.textContent=t}var Lr={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},ya=["Webkit","ms","Moz","O"];Object.keys(Lr).forEach(function(e){ya.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Lr[t]=Lr[e]})});function Os(e,t,i){return t==null||typeof t=="boolean"||t===""?"":i||typeof t!="number"||t===0||Lr.hasOwnProperty(e)&&Lr[e]?(""+t).trim():t+"px"}function Ds(e,t){e=e.style;for(var i in t)if(t.hasOwnProperty(i)){var o=i.indexOf("--")===0,l=Os(i,t[i],o);i==="float"&&(i="cssFloat"),o?e.setProperty(i,l):e[i]=l}}var wa=z({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 Bi(e,t){if(t){if(wa[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(s(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(s(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(s(61))}if(t.style!=null&&typeof t.style!="object")throw Error(s(62))}}function Ai(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 zs=null;function Et(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Mi=null,B=null,ye=null;function bn(e){if(e=ns(e)){if(typeof Mi!="function")throw Error(s(280));var t=e.stateNode;t&&(t=lo(t),Mi(e.stateNode,e.type,t))}}function Qu(e){B?ye?ye.push(e):ye=[e]:B=e}function Ju(){if(B){var e=B,t=ye;if(ye=B=null,bn(e),t)for(e=0;e>>=0,e===0?32:31-(Dp(e)/zp|0)|0}var qs=64,Hs=4194304;function zi(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 Ks(e,t){var i=e.pendingLanes;if(i===0)return 0;var o=0,l=e.suspendedLanes,u=e.pingedLanes,h=i&268435455;if(h!==0){var m=h&~l;m!==0?o=zi(m):(u&=h,u!==0&&(o=zi(u)))}else h=i&~l,h!==0?o=zi(h):u!==0&&(o=zi(u));if(o===0)return 0;if(t!==0&&t!==o&&(t&l)===0&&(l=o&-o,u=t&-t,l>=u||l===16&&(u&4194240)!==0))return t;if((o&4)!==0&&(o|=i&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=o;0i;i++)t.push(e);return t}function Fi(e,t,i){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-zt(t),e[t]=i}function Vp(e,t){var i=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 o=e.eventTimes;for(e=e.expirationTimes;0=Qi),Ic=" ",kc=!1;function bc(e,t){switch(e){case"keyup":return yg.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Cc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var En=!1;function vg(e,t){switch(e){case"compositionend":return Cc(t);case"keypress":return t.which!==32?null:(kc=!0,Ic);case"textInput":return e=t.data,e===Ic&&kc?null:e;default:return null}}function _g(e,t){if(En)return e==="compositionend"||!ja&&bc(e,t)?(e=yc(),Xs=Ra=xr=null,En=!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:i,offset:t-e};e=o}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=Bc(i)}}function Mc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Mc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function jc(){for(var e=window,t=Dt();t instanceof e.HTMLIFrameElement;){try{var i=typeof t.contentWindow.location.href=="string"}catch{i=!1}if(i)e=t.contentWindow;else break;t=Dt(e.document)}return t}function za(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 Ug(e){var t=jc(),i=e.focusedElem,o=e.selectionRange;if(t!==i&&i&&i.ownerDocument&&Mc(i.ownerDocument.documentElement,i)){if(o!==null&&za(i)){if(t=o.start,e=o.end,e===void 0&&(e=t),"selectionStart"in i)i.selectionStart=t,i.selectionEnd=Math.min(e,i.value.length);else if(e=(t=i.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=i.textContent.length,u=Math.min(o.start,l);o=o.end===void 0?u:Math.min(o.end,l),!e.extend&&u>o&&(l=o,o=u,u=l),l=Ac(i,u);var h=Ac(i,o);l&&h&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==h.node||e.focusOffset!==h.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),u>o?(e.addRange(t),e.extend(h.node,h.offset)):(t.setEnd(h.node,h.offset),e.addRange(t)))}}for(t=[],e=i;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof i.focus=="function"&&i.focus(),i=0;i=document.documentMode,Un=null,Fa=null,Yi=null,$a=!1;function Oc(e,t,i){var o=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;$a||Un==null||Un!==Dt(o)||(o=Un,"selectionStart"in o&&za(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),Yi&&Xi(Yi,o)||(Yi=o,o=so(Fa,"onSelect"),0An||(e.current=Za[An],Za[An]=null,An--)}function Ae(e,t){An++,Za[An]=e.current,e.current=t}var Cr={},at=br(Cr),ht=br(!1),Hr=Cr;function Mn(e,t){var i=e.type.contextTypes;if(!i)return Cr;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var l={},u;for(u in i)l[u]=t[u];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function pt(e){return e=e.childContextTypes,e!=null}function uo(){Oe(ht),Oe(at)}function Yc(e,t,i){if(at.current!==Cr)throw Error(s(168));Ae(at,t),Ae(ht,i)}function Zc(e,t,i){var o=e.stateNode;if(t=t.childContextTypes,typeof o.getChildContext!="function")return i;o=o.getChildContext();for(var l in o)if(!(l in t))throw Error(s(108,ie(e)||"Unknown",l));return z({},i,o)}function co(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Cr,Hr=at.current,Ae(at,e),Ae(ht,ht.current),!0}function ed(e,t,i){var o=e.stateNode;if(!o)throw Error(s(169));i?(e=Zc(e,t,Hr),o.__reactInternalMemoizedMergedChildContext=e,Oe(ht),Oe(at),Ae(at,e)):Oe(ht),Ae(ht,i)}var ir=null,fo=!1,el=!1;function td(e){ir===null?ir=[e]:ir.push(e)}function $g(e){fo=!0,td(e)}function Tr(){if(!el&&ir!==null){el=!0;var e=0,t=Ue;try{var i=ir;for(Ue=1;e>=h,l-=h,sr=1<<32-zt(t)+l|i<pe?(nt=de,de=null):nt=de.sibling;var Ce=D(I,de,k[pe],K);if(Ce===null){de===null&&(de=nt);break}e&&de&&Ce.alternate===null&&t(I,de),S=u(Ce,S,pe),ce===null?se=Ce:ce.sibling=Ce,ce=Ce,de=nt}if(pe===k.length)return i(I,de),De&&Wr(I,pe),se;if(de===null){for(;pepe?(nt=de,de=null):nt=de.sibling;var jr=D(I,de,Ce.value,K);if(jr===null){de===null&&(de=nt);break}e&&de&&jr.alternate===null&&t(I,de),S=u(jr,S,pe),ce===null?se=jr:ce.sibling=jr,ce=jr,de=nt}if(Ce.done)return i(I,de),De&&Wr(I,pe),se;if(de===null){for(;!Ce.done;pe++,Ce=k.next())Ce=V(I,Ce.value,K),Ce!==null&&(S=u(Ce,S,pe),ce===null?se=Ce:ce.sibling=Ce,ce=Ce);return De&&Wr(I,pe),se}for(de=o(I,de);!Ce.done;pe++,Ce=k.next())Ce=G(de,I,pe,Ce.value,K),Ce!==null&&(e&&Ce.alternate!==null&&de.delete(Ce.key===null?pe:Ce.key),S=u(Ce,S,pe),ce===null?se=Ce:ce.sibling=Ce,ce=Ce);return e&&de.forEach(function(Sm){return t(I,Sm)}),De&&Wr(I,pe),se}function He(I,S,k,K){if(typeof k=="object"&&k!==null&&k.type===ge&&k.key===null&&(k=k.props.children),typeof k=="object"&&k!==null){switch(k.$$typeof){case J:e:{for(var se=k.key,ce=S;ce!==null;){if(ce.key===se){if(se=k.type,se===ge){if(ce.tag===7){i(I,ce.sibling),S=l(ce,k.props.children),S.return=I,I=S;break e}}else if(ce.elementType===se||typeof se=="object"&&se!==null&&se.$$typeof===P&&ad(se)===ce.type){i(I,ce.sibling),S=l(ce,k.props),S.ref=is(I,ce,k),S.return=I,I=S;break e}i(I,ce);break}else t(I,ce);ce=ce.sibling}k.type===ge?(S=tn(k.props.children,I.mode,K,k.key),S.return=I,I=S):(K=Fo(k.type,k.key,k.props,null,I.mode,K),K.ref=is(I,S,k),K.return=I,I=K)}return h(I);case Y:e:{for(ce=k.key;S!==null;){if(S.key===ce)if(S.tag===4&&S.stateNode.containerInfo===k.containerInfo&&S.stateNode.implementation===k.implementation){i(I,S.sibling),S=l(S,k.children||[]),S.return=I,I=S;break e}else{i(I,S);break}else t(I,S);S=S.sibling}S=Xl(k,I.mode,K),S.return=I,I=S}return h(I);case P:return ce=k._init,He(I,S,ce(k._payload),K)}if(Fr(k))return Z(I,S,k,K);if(H(k))return re(I,S,k,K);mo(I,k)}return typeof k=="string"&&k!==""||typeof k=="number"?(k=""+k,S!==null&&S.tag===6?(i(I,S.sibling),S=l(S,k),S.return=I,I=S):(i(I,S),S=Gl(k,I.mode,K),S.return=I,I=S),h(I)):i(I,S)}return He}var zn=ld(!0),ud=ld(!1),yo=br(null),wo=null,Fn=null,ol=null;function al(){ol=Fn=wo=null}function ll(e){var t=yo.current;Oe(yo),e._currentValue=t}function ul(e,t,i){for(;e!==null;){var o=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,o!==null&&(o.childLanes|=t)):o!==null&&(o.childLanes&t)!==t&&(o.childLanes|=t),e===i)break;e=e.return}}function $n(e,t){wo=e,ol=Fn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(gt=!0),e.firstContext=null)}function Nt(e){var t=e._currentValue;if(ol!==e)if(e={context:e,memoizedValue:t,next:null},Fn===null){if(wo===null)throw Error(s(308));Fn=e,wo.dependencies={lanes:0,firstContext:e}}else Fn=Fn.next=e;return t}var Qr=null;function cl(e){Qr===null?Qr=[e]:Qr.push(e)}function cd(e,t,i,o){var l=t.interleaved;return l===null?(i.next=i,cl(t)):(i.next=l.next,l.next=i),t.interleaved=i,ar(e,o)}function ar(e,t){e.lanes|=t;var i=e.alternate;for(i!==null&&(i.lanes|=t),i=e,e=e.return;e!==null;)e.childLanes|=t,i=e.alternate,i!==null&&(i.childLanes|=t),i=e,e=e.return;return i.tag===3?i.stateNode:null}var Er=!1;function dl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function dd(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 lr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Ur(e,t,i){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,(be&2)!==0){var l=o.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),o.pending=t,ar(e,i)}return l=o.interleaved,l===null?(t.next=t,cl(o)):(t.next=l.next,l.next=t),o.interleaved=t,ar(e,i)}function vo(e,t,i){if(t=t.updateQueue,t!==null&&(t=t.shared,(i&4194240)!==0)){var o=t.lanes;o&=e.pendingLanes,i|=o,t.lanes=i,ba(e,i)}}function fd(e,t){var i=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,i===o)){var l=null,u=null;if(i=i.firstBaseUpdate,i!==null){do{var h={eventTime:i.eventTime,lane:i.lane,tag:i.tag,payload:i.payload,callback:i.callback,next:null};u===null?l=u=h:u=u.next=h,i=i.next}while(i!==null);u===null?l=u=t:u=u.next=t}else l=u=t;i={baseState:o.baseState,firstBaseUpdate:l,lastBaseUpdate:u,shared:o.shared,effects:o.effects},e.updateQueue=i;return}e=i.lastBaseUpdate,e===null?i.firstBaseUpdate=t:e.next=t,i.lastBaseUpdate=t}function _o(e,t,i,o){var l=e.updateQueue;Er=!1;var u=l.firstBaseUpdate,h=l.lastBaseUpdate,m=l.shared.pending;if(m!==null){l.shared.pending=null;var _=m,C=_.next;_.next=null,h===null?u=C:h.next=C,h=_;var F=e.alternate;F!==null&&(F=F.updateQueue,m=F.lastBaseUpdate,m!==h&&(m===null?F.firstBaseUpdate=C:m.next=C,F.lastBaseUpdate=_))}if(u!==null){var V=l.baseState;h=0,F=C=_=null,m=u;do{var D=m.lane,G=m.eventTime;if((o&D)===D){F!==null&&(F=F.next={eventTime:G,lane:0,tag:m.tag,payload:m.payload,callback:m.callback,next:null});e:{var Z=e,re=m;switch(D=t,G=i,re.tag){case 1:if(Z=re.payload,typeof Z=="function"){V=Z.call(G,V,D);break e}V=Z;break e;case 3:Z.flags=Z.flags&-65537|128;case 0:if(Z=re.payload,D=typeof Z=="function"?Z.call(G,V,D):Z,D==null)break e;V=z({},V,D);break e;case 2:Er=!0}}m.callback!==null&&m.lane!==0&&(e.flags|=64,D=l.effects,D===null?l.effects=[m]:D.push(m))}else G={eventTime:G,lane:D,tag:m.tag,payload:m.payload,callback:m.callback,next:null},F===null?(C=F=G,_=V):F=F.next=G,h|=D;if(m=m.next,m===null){if(m=l.shared.pending,m===null)break;D=m,m=D.next,D.next=null,l.lastBaseUpdate=D,l.shared.pending=null}}while(!0);if(F===null&&(_=V),l.baseState=_,l.firstBaseUpdate=C,l.lastBaseUpdate=F,t=l.shared.interleaved,t!==null){l=t;do h|=l.lane,l=l.next;while(l!==t)}else u===null&&(l.shared.lanes=0);Xr|=h,e.lanes=h,e.memoizedState=V}}function hd(e,t,i){if(e=t.effects,t.effects=null,e!==null)for(t=0;ti?i:4,e(!0);var o=ml.transition;ml.transition={};try{e(!1),t()}finally{Ue=i,ml.transition=o}}function Pd(){return Pt().memoizedState}function Hg(e,t,i){var o=Br(e);if(i={lane:o,action:i,hasEagerState:!1,eagerState:null,next:null},Bd(e))Ad(t,i);else if(i=cd(e,t,i,o),i!==null){var l=ft();Ht(i,e,o,l),Md(i,t,o)}}function Kg(e,t,i){var o=Br(e),l={lane:o,action:i,hasEagerState:!1,eagerState:null,next:null};if(Bd(e))Ad(t,l);else{var u=e.alternate;if(e.lanes===0&&(u===null||u.lanes===0)&&(u=t.lastRenderedReducer,u!==null))try{var h=t.lastRenderedState,m=u(h,i);if(l.hasEagerState=!0,l.eagerState=m,Ft(m,h)){var _=t.interleaved;_===null?(l.next=l,cl(t)):(l.next=_.next,_.next=l),t.interleaved=l;return}}catch{}i=cd(e,t,l,o),i!==null&&(l=ft(),Ht(i,e,o,l),Md(i,t,o))}}function Bd(e){var t=e.alternate;return e===$e||t!==null&&t===$e}function Ad(e,t){ls=Io=!0;var i=e.pending;i===null?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function Md(e,t,i){if((i&4194240)!==0){var o=t.lanes;o&=e.pendingLanes,i|=o,t.lanes=i,ba(e,i)}}var Co={readContext:Nt,useCallback:lt,useContext:lt,useEffect:lt,useImperativeHandle:lt,useInsertionEffect:lt,useLayoutEffect:lt,useMemo:lt,useReducer:lt,useRef:lt,useState:lt,useDebugValue:lt,useDeferredValue:lt,useTransition:lt,useMutableSource:lt,useSyncExternalStore:lt,useId:lt,unstable_isNewReconciler:!1},Wg={readContext:Nt,useCallback:function(e,t){return Xt().memoizedState=[e,t===void 0?null:t],e},useContext:Nt,useEffect:kd,useImperativeHandle:function(e,t,i){return i=i!=null?i.concat([e]):null,ko(4194308,4,Td.bind(null,t,e),i)},useLayoutEffect:function(e,t){return ko(4194308,4,e,t)},useInsertionEffect:function(e,t){return ko(4,2,e,t)},useMemo:function(e,t){var i=Xt();return t=t===void 0?null:t,e=e(),i.memoizedState=[e,t],e},useReducer:function(e,t,i){var o=Xt();return t=i!==void 0?i(t):t,o.memoizedState=o.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},o.queue=e,e=e.dispatch=Hg.bind(null,$e,e),[o.memoizedState,e]},useRef:function(e){var t=Xt();return e={current:e},t.memoizedState=e},useState:xd,useDebugValue:Il,useDeferredValue:function(e){return Xt().memoizedState=e},useTransition:function(){var e=xd(!1),t=e[0];return e=qg.bind(null,e[1]),Xt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,i){var o=$e,l=Xt();if(De){if(i===void 0)throw Error(s(407));i=i()}else{if(i=t(),rt===null)throw Error(s(349));(Gr&30)!==0||yd(o,t,i)}l.memoizedState=i;var u={value:i,getSnapshot:t};return l.queue=u,kd(vd.bind(null,o,u,e),[e]),o.flags|=2048,ds(9,wd.bind(null,o,u,i,t),void 0,null),i},useId:function(){var e=Xt(),t=rt.identifierPrefix;if(De){var i=or,o=sr;i=(o&~(1<<32-zt(o)-1)).toString(32)+i,t=":"+t+"R"+i,i=us++,0<\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=h.createElement(i,{is:o.is}):(e=h.createElement(i),i==="select"&&(h=e,o.multiple?h.multiple=!0:o.size&&(h.size=o.size))):e=h.createElementNS(e,i),e[Jt]=t,e[rs]=o,tf(e,t,!1,!1),t.stateNode=e;e:{switch(h=Ai(i,o),i){case"dialog":je("cancel",e),je("close",e),l=o;break;case"iframe":case"object":case"embed":je("load",e),l=o;break;case"video":case"audio":for(l=0;lKn&&(t.flags|=128,o=!0,fs(u,!1),t.lanes=4194304)}else{if(!o)if(e=So(h),e!==null){if(t.flags|=128,o=!0,i=e.updateQueue,i!==null&&(t.updateQueue=i,t.flags|=4),fs(u,!0),u.tail===null&&u.tailMode==="hidden"&&!h.alternate&&!De)return ut(t),null}else 2*qe()-u.renderingStartTime>Kn&&i!==1073741824&&(t.flags|=128,o=!0,fs(u,!1),t.lanes=4194304);u.isBackwards?(h.sibling=t.child,t.child=h):(i=u.last,i!==null?i.sibling=h:t.child=h,u.last=h)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=qe(),t.sibling=null,i=Fe.current,Ae(Fe,o?i&1|2:i&1),t):(ut(t),null);case 22:case 23:return Wl(),o=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(t.flags|=8192),o&&(t.mode&1)!==0?(Ct&1073741824)!==0&&(ut(t),t.subtreeFlags&6&&(t.flags|=8192)):ut(t),null;case 24:return null;case 25:return null}throw Error(s(156,t.tag))}function tm(e,t){switch(rl(t),t.tag){case 1:return pt(t.type)&&uo(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ln(),Oe(ht),Oe(at),gl(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return hl(t),null;case 13:if(Oe(Fe),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(s(340));Dn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Oe(Fe),null;case 4:return Ln(),null;case 10:return ll(t.type._context),null;case 22:case 23:return Wl(),null;case 24:return null;default:return null}}var Ro=!1,ct=!1,rm=typeof WeakSet=="function"?WeakSet:Set,X=null;function qn(e,t){var i=e.ref;if(i!==null)if(typeof i=="function")try{i(null)}catch(o){Ve(e,t,o)}else i.current=null}function Ml(e,t,i){try{i()}catch(o){Ve(e,t,o)}}var sf=!1;function nm(e,t){if(Wa=Js,e=jc(),za(e)){if("selectionStart"in e)var i={start:e.selectionStart,end:e.selectionEnd};else e:{i=(i=e.ownerDocument)&&i.defaultView||window;var o=i.getSelection&&i.getSelection();if(o&&o.rangeCount!==0){i=o.anchorNode;var l=o.anchorOffset,u=o.focusNode;o=o.focusOffset;try{i.nodeType,u.nodeType}catch{i=null;break e}var h=0,m=-1,_=-1,C=0,F=0,V=e,D=null;t:for(;;){for(var G;V!==i||l!==0&&V.nodeType!==3||(m=h+l),V!==u||o!==0&&V.nodeType!==3||(_=h+o),V.nodeType===3&&(h+=V.nodeValue.length),(G=V.firstChild)!==null;)D=V,V=G;for(;;){if(V===e)break t;if(D===i&&++C===l&&(m=h),D===u&&++F===o&&(_=h),(G=V.nextSibling)!==null)break;V=D,D=V.parentNode}V=G}i=m===-1||_===-1?null:{start:m,end:_}}else i=null}i=i||{start:0,end:0}}else i=null;for(Qa={focusedElem:e,selectionRange:i},Js=!1,X=t;X!==null;)if(t=X,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,X=e;else for(;X!==null;){t=X;try{var Z=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(Z!==null){var re=Z.memoizedProps,He=Z.memoizedState,I=t.stateNode,S=I.getSnapshotBeforeUpdate(t.elementType===t.type?re:Lt(t.type,re),He);I.__reactInternalSnapshotBeforeUpdate=S}break;case 3:var k=t.stateNode.containerInfo;k.nodeType===1?k.textContent="":k.nodeType===9&&k.documentElement&&k.removeChild(k.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(s(163))}}catch(K){Ve(t,t.return,K)}if(e=t.sibling,e!==null){e.return=t.return,X=e;break}X=t.return}return Z=sf,sf=!1,Z}function hs(e,t,i){var o=t.updateQueue;if(o=o!==null?o.lastEffect:null,o!==null){var l=o=o.next;do{if((l.tag&e)===e){var u=l.destroy;l.destroy=void 0,u!==void 0&&Ml(t,i,u)}l=l.next}while(l!==o)}}function No(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var i=t=t.next;do{if((i.tag&e)===e){var o=i.create;i.destroy=o()}i=i.next}while(i!==t)}}function jl(e){var t=e.ref;if(t!==null){var i=e.stateNode;e.tag,e=i,typeof t=="function"?t(e):t.current=e}}function of(e){var t=e.alternate;t!==null&&(e.alternate=null,of(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Jt],delete t[rs],delete t[Ya],delete t[zg],delete t[Fg])),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 af(e){return e.tag===5||e.tag===3||e.tag===4}function lf(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||af(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 Ol(e,t,i){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?i.nodeType===8?i.parentNode.insertBefore(e,t):i.insertBefore(e,t):(i.nodeType===8?(t=i.parentNode,t.insertBefore(e,i)):(t=i,t.appendChild(e)),i=i._reactRootContainer,i!=null||t.onclick!==null||(t.onclick=ao));else if(o!==4&&(e=e.child,e!==null))for(Ol(e,t,i),e=e.sibling;e!==null;)Ol(e,t,i),e=e.sibling}function Dl(e,t,i){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?i.insertBefore(e,t):i.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(Dl(e,t,i),e=e.sibling;e!==null;)Dl(e,t,i),e=e.sibling}var st=null,Vt=!1;function Rr(e,t,i){for(i=i.child;i!==null;)uf(e,t,i),i=i.sibling}function uf(e,t,i){if(Qt&&typeof Qt.onCommitFiberUnmount=="function")try{Qt.onCommitFiberUnmount(Vs,i)}catch{}switch(i.tag){case 5:ct||qn(i,t);case 6:var o=st,l=Vt;st=null,Rr(e,t,i),st=o,Vt=l,st!==null&&(Vt?(e=st,i=i.stateNode,e.nodeType===8?e.parentNode.removeChild(i):e.removeChild(i)):st.removeChild(i.stateNode));break;case 18:st!==null&&(Vt?(e=st,i=i.stateNode,e.nodeType===8?Xa(e.parentNode,i):e.nodeType===1&&Xa(e,i),Hi(e)):Xa(st,i.stateNode));break;case 4:o=st,l=Vt,st=i.stateNode.containerInfo,Vt=!0,Rr(e,t,i),st=o,Vt=l;break;case 0:case 11:case 14:case 15:if(!ct&&(o=i.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){l=o=o.next;do{var u=l,h=u.destroy;u=u.tag,h!==void 0&&((u&2)!==0||(u&4)!==0)&&Ml(i,t,h),l=l.next}while(l!==o)}Rr(e,t,i);break;case 1:if(!ct&&(qn(i,t),o=i.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=i.memoizedProps,o.state=i.memoizedState,o.componentWillUnmount()}catch(m){Ve(i,t,m)}Rr(e,t,i);break;case 21:Rr(e,t,i);break;case 22:i.mode&1?(ct=(o=ct)||i.memoizedState!==null,Rr(e,t,i),ct=o):Rr(e,t,i);break;default:Rr(e,t,i)}}function cf(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var i=e.stateNode;i===null&&(i=e.stateNode=new rm),t.forEach(function(o){var l=fm.bind(null,e,o);i.has(o)||(i.add(o),o.then(l,l))})}}function qt(e,t){var i=t.deletions;if(i!==null)for(var o=0;ol&&(l=h),o&=~u}if(o=l,o=qe()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*sm(o/1960))-o,10e?16:e,Pr===null)var o=!1;else{if(e=Pr,Pr=null,jo=0,(be&6)!==0)throw Error(s(331));var l=be;for(be|=4,X=e.current;X!==null;){var u=X,h=u.child;if((X.flags&16)!==0){var m=u.deletions;if(m!==null){for(var _=0;_qe()-$l?Zr(e,0):Fl|=i),yt(e,t)}function If(e,t){t===0&&((e.mode&1)===0?t=1:(t=Hs,Hs<<=1,(Hs&130023424)===0&&(Hs=4194304)));var i=ft();e=ar(e,t),e!==null&&(Fi(e,t,i),yt(e,i))}function dm(e){var t=e.memoizedState,i=0;t!==null&&(i=t.retryLane),If(e,i)}function fm(e,t){var i=0;switch(e.tag){case 13:var o=e.stateNode,l=e.memoizedState;l!==null&&(i=l.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(s(314))}o!==null&&o.delete(t),If(e,i)}var kf;kf=function(e,t,i){if(e!==null)if(e.memoizedProps!==t.pendingProps||ht.current)gt=!0;else{if((e.lanes&i)===0&&(t.flags&128)===0)return gt=!1,Zg(e,t,i);gt=(e.flags&131072)!==0}else gt=!1,De&&(t.flags&1048576)!==0&&rd(t,po,t.index);switch(t.lanes=0,t.tag){case 2:var o=t.type;Uo(e,t),e=t.pendingProps;var l=Mn(t,at.current);$n(t,i),l=wl(null,t,o,e,l,i);var u=vl();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,pt(o)?(u=!0,co(t)):u=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,dl(t),l.updater=To,t.stateNode=l,l._reactInternals=t,bl(t,o,e,i),t=Ul(null,t,o,!0,u,i)):(t.tag=0,De&&u&&tl(t),dt(null,t,l,i),t=t.child),t;case 16:o=t.elementType;e:{switch(Uo(e,t),e=t.pendingProps,l=o._init,o=l(o._payload),t.type=o,l=t.tag=pm(o),e=Lt(o,e),l){case 0:t=El(null,t,o,e,i);break e;case 1:t=Jd(null,t,o,e,i);break e;case 11:t=qd(null,t,o,e,i);break e;case 14:t=Hd(null,t,o,Lt(o.type,e),i);break e}throw Error(s(306,o,""))}return t;case 0:return o=t.type,l=t.pendingProps,l=t.elementType===o?l:Lt(o,l),El(e,t,o,l,i);case 1:return o=t.type,l=t.pendingProps,l=t.elementType===o?l:Lt(o,l),Jd(e,t,o,l,i);case 3:e:{if(Gd(t),e===null)throw Error(s(387));o=t.pendingProps,u=t.memoizedState,l=u.element,dd(e,t),_o(t,o,null,i);var h=t.memoizedState;if(o=h.element,u.isDehydrated)if(u={element:o,isDehydrated:!1,cache:h.cache,pendingSuspenseBoundaries:h.pendingSuspenseBoundaries,transitions:h.transitions},t.updateQueue.baseState=u,t.memoizedState=u,t.flags&256){l=Vn(Error(s(423)),t),t=Xd(e,t,o,i,l);break e}else if(o!==l){l=Vn(Error(s(424)),t),t=Xd(e,t,o,i,l);break e}else for(bt=kr(t.stateNode.containerInfo.firstChild),kt=t,De=!0,$t=null,i=ud(t,null,o,i),t.child=i;i;)i.flags=i.flags&-3|4096,i=i.sibling;else{if(Dn(),o===l){t=ur(e,t,i);break e}dt(e,t,o,i)}t=t.child}return t;case 5:return pd(t),e===null&&il(t),o=t.type,l=t.pendingProps,u=e!==null?e.memoizedProps:null,h=l.children,Ja(o,l)?h=null:u!==null&&Ja(o,u)&&(t.flags|=32),Qd(e,t),dt(e,t,h,i),t.child;case 6:return e===null&&il(t),null;case 13:return Yd(e,t,i);case 4:return fl(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=zn(t,null,o,i):dt(e,t,o,i),t.child;case 11:return o=t.type,l=t.pendingProps,l=t.elementType===o?l:Lt(o,l),qd(e,t,o,l,i);case 7:return dt(e,t,t.pendingProps,i),t.child;case 8:return dt(e,t,t.pendingProps.children,i),t.child;case 12:return dt(e,t,t.pendingProps.children,i),t.child;case 10:e:{if(o=t.type._context,l=t.pendingProps,u=t.memoizedProps,h=l.value,Ae(yo,o._currentValue),o._currentValue=h,u!==null)if(Ft(u.value,h)){if(u.children===l.children&&!ht.current){t=ur(e,t,i);break e}}else for(u=t.child,u!==null&&(u.return=t);u!==null;){var m=u.dependencies;if(m!==null){h=u.child;for(var _=m.firstContext;_!==null;){if(_.context===o){if(u.tag===1){_=lr(-1,i&-i),_.tag=2;var C=u.updateQueue;if(C!==null){C=C.shared;var F=C.pending;F===null?_.next=_:(_.next=F.next,F.next=_),C.pending=_}}u.lanes|=i,_=u.alternate,_!==null&&(_.lanes|=i),ul(u.return,i,t),m.lanes|=i;break}_=_.next}}else if(u.tag===10)h=u.type===t.type?null:u.child;else if(u.tag===18){if(h=u.return,h===null)throw Error(s(341));h.lanes|=i,m=h.alternate,m!==null&&(m.lanes|=i),ul(h,i,t),h=u.sibling}else h=u.child;if(h!==null)h.return=u;else for(h=u;h!==null;){if(h===t){h=null;break}if(u=h.sibling,u!==null){u.return=h.return,h=u;break}h=h.return}u=h}dt(e,t,l.children,i),t=t.child}return t;case 9:return l=t.type,o=t.pendingProps.children,$n(t,i),l=Nt(l),o=o(l),t.flags|=1,dt(e,t,o,i),t.child;case 14:return o=t.type,l=Lt(o,t.pendingProps),l=Lt(o.type,l),Hd(e,t,o,l,i);case 15:return Kd(e,t,t.type,t.pendingProps,i);case 17:return o=t.type,l=t.pendingProps,l=t.elementType===o?l:Lt(o,l),Uo(e,t),t.tag=1,pt(o)?(e=!0,co(t)):e=!1,$n(t,i),Od(t,o,l),bl(t,o,l,i),Ul(null,t,o,!0,e,i);case 19:return ef(e,t,i);case 22:return Wd(e,t,i)}throw Error(s(156,t.tag))};function bf(e,t){return nc(e,t)}function hm(e,t,i,o){this.tag=e,this.key=i,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=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function At(e,t,i,o){return new hm(e,t,i,o)}function Jl(e){return e=e.prototype,!(!e||!e.isReactComponent)}function pm(e){if(typeof e=="function")return Jl(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Le)return 11;if(e===ke)return 14}return 2}function Mr(e,t){var i=e.alternate;return i===null?(i=At(e.tag,t,e.key,e.mode),i.elementType=e.elementType,i.type=e.type,i.stateNode=e.stateNode,i.alternate=e,e.alternate=i):(i.pendingProps=t,i.type=e.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=e.flags&14680064,i.childLanes=e.childLanes,i.lanes=e.lanes,i.child=e.child,i.memoizedProps=e.memoizedProps,i.memoizedState=e.memoizedState,i.updateQueue=e.updateQueue,t=e.dependencies,i.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},i.sibling=e.sibling,i.index=e.index,i.ref=e.ref,i}function Fo(e,t,i,o,l,u){var h=2;if(o=e,typeof e=="function")Jl(e)&&(h=1);else if(typeof e=="string")h=5;else e:switch(e){case ge:return tn(i.children,l,u,t);case me:h=8,l|=8;break;case ue:return e=At(12,i,t,l|2),e.elementType=ue,e.lanes=u,e;case Me:return e=At(13,i,t,l),e.elementType=Me,e.lanes=u,e;case it:return e=At(19,i,t,l),e.elementType=it,e.lanes=u,e;case W:return $o(i,l,u,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Re:h=10;break e;case We:h=9;break e;case Le:h=11;break e;case ke:h=14;break e;case P:h=16,o=null;break e}throw Error(s(130,e==null?e:typeof e,""))}return t=At(h,i,t,l),t.elementType=e,t.type=o,t.lanes=u,t}function tn(e,t,i,o){return e=At(7,e,o,t),e.lanes=i,e}function $o(e,t,i,o){return e=At(22,e,o,t),e.elementType=W,e.lanes=i,e.stateNode={isHidden:!1},e}function Gl(e,t,i){return e=At(6,e,null,t),e.lanes=i,e}function Xl(e,t,i){return t=At(4,e.children!==null?e.children:[],e.key,t),t.lanes=i,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function gm(e,t,i,o,l){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=ka(0),this.expirationTimes=ka(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ka(0),this.identifierPrefix=o,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Yl(e,t,i,o,l,u,h,m,_){return e=new gm(e,t,i,m,_),t===1?(t=1,u===!0&&(t|=8)):t=0,u=At(3,null,null,t),e.current=u,u.stateNode=e,u.memoizedState={element:o,isDehydrated:i,cache:null,transitions:null,pendingSuspenseBoundaries:null},dl(u),e}function mm(e,t,i){var o=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(n){console.error(n)}}return r(),iu.exports=Tm(),iu.exports}var zf;function Um(){if(zf)return Qo;zf=1;var r=Em();return Qo.createRoot=r.createRoot,Qo.hydrateRoot=r.hydrateRoot,Qo}var Rm=Um(),vs={},Ff;function Nm(){if(Ff)return vs;Ff=1,vs.byteLength=v,vs.toByteArray=x,vs.fromByteArray=j;for(var r=[],n=[],s=typeof Uint8Array<"u"?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,f=a.length;c0)throw new Error("Invalid string. Length must be a multiple of 4");var Q=O.indexOf("=");Q===-1&&(Q=q);var $=Q===q?0:4-Q%4;return[Q,$]}function v(O){var q=p(O),Q=q[0],$=q[1];return(Q+$)*3/4-$}function y(O,q,Q){return(q+Q)*3/4-Q}function x(O){var q,Q=p(O),$=Q[0],fe=Q[1],T=new s(y(O,$,fe)),A=0,L=fe>0?$-4:$,J;for(J=0;J>16&255,T[A++]=q>>8&255,T[A++]=q&255;return fe===2&&(q=n[O.charCodeAt(J)]<<2|n[O.charCodeAt(J+1)]>>4,T[A++]=q&255),fe===1&&(q=n[O.charCodeAt(J)]<<10|n[O.charCodeAt(J+1)]<<4|n[O.charCodeAt(J+2)]>>2,T[A++]=q>>8&255,T[A++]=q&255),T}function R(O){return r[O>>18&63]+r[O>>12&63]+r[O>>6&63]+r[O&63]}function N(O,q,Q){for(var $,fe=[],T=q;TL?L:A+T));return $===1?(q=O[Q-1],fe.push(r[q>>2]+r[q<<4&63]+"==")):$===2&&(q=(O[Q-2]<<8)+O[Q-1],fe.push(r[q>>10]+r[q>>4&63]+r[q<<2&63]+"=")),fe.join("")}return vs}var Mu=Nm(),Jo={exports:{}},$f;function Pm(){return $f||($f=1,(function(r,n){const{hasOwnProperty:s}=Object.prototype,a=fe();a.configure=fe,a.stringify=a,a.default=a,n.stringify=a,n.configure=fe,r.exports=a;const c=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function f(T){return T.length<5e3&&!c.test(T)?`"${T}"`:JSON.stringify(T)}function p(T,A){if(T.length>200||A)return T.sort(A);for(let L=1;LJ;)T[Y]=T[Y-1],Y--;T[Y]=J}return T}const v=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function y(T){return v.call(T)!==void 0&&T.length!==0}function x(T,A,L){T.length= 1`)}return L===void 0?1/0:L}function q(T){return T===1?"1 item":`${T} items`}function Q(T){const A=new Set;for(const L of T)(typeof L=="string"||typeof L=="number")&&A.add(String(L));return A}function $(T){if(s.call(T,"strict")){const A=T.strict;if(typeof A!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(A)return L=>{let J=`Object can not safely be stringified. Received type ${typeof L}`;throw typeof L!="function"&&(J+=` (${L.toString()})`),new Error(J)}}}function fe(T){T={...T};const A=$(T);A&&(T.bigint===void 0&&(T.bigint=!1),"circularValue"in T||(T.circularValue=Error));const L=R(T),J=j(T,"bigint"),Y=N(T),ge=typeof Y=="function"?Y:void 0,me=O(T,"maximumDepth"),ue=O(T,"maximumBreadth");function Re(ke,P,W,M,H,z){let w=P[ke];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(ke)),w=M.call(P,ke,w),typeof w){case"string":return f(w);case"object":{if(w===null)return"null";if(W.indexOf(w)!==-1)return L;let E="",ee=",";const ne=z;if(Array.isArray(w)){if(w.length===0)return"[]";if(meue){const Dt=w.length-ue-1;E+=`${ee}"... ${q(Dt)} not stringified"`}return H!==""&&(E+=` ${ne}`),W.pop(),`[${E}]`}let te=Object.keys(w);const le=te.length;if(le===0)return"{}";if(meue){const _e=le-ue;E+=`${he}"...":${ie}"${q(_e)} not stringified"`,he=ee}return H!==""&&he.length>1&&(E=` ${z}${E} ${ne}`),W.pop(),`{${E}}`}case"number":return isFinite(w)?String(w):A?A(w):"null";case"boolean":return w===!0?"true":"false";case"undefined":return;case"bigint":if(J)return String(w);default:return A?A(w):void 0}}function We(ke,P,W,M,H,z){switch(typeof P=="object"&&P!==null&&typeof P.toJSON=="function"&&(P=P.toJSON(ke)),typeof P){case"string":return f(P);case"object":{if(P===null)return"null";if(W.indexOf(P)!==-1)return L;const w=z;let E="",ee=",";if(Array.isArray(P)){if(P.length===0)return"[]";if(meue){const we=P.length-ue-1;E+=`${ee}"... ${q(we)} not stringified"`}return H!==""&&(E+=` ${w}`),W.pop(),`[${E}]`}W.push(P);let ne="";H!==""&&(z+=H,ee=`, ${z}`,ne=" ");let te="";for(const le of M){const ie=We(le,P[le],W,M,H,z);ie!==void 0&&(E+=`${te}${f(le)}:${ne}${ie}`,te=ee)}return H!==""&&te.length>1&&(E=` ${z}${E} ${w}`),W.pop(),`{${E}}`}case"number":return isFinite(P)?String(P):A?A(P):"null";case"boolean":return P===!0?"true":"false";case"undefined":return;case"bigint":if(J)return String(P);default:return A?A(P):void 0}}function Le(ke,P,W,M,H){switch(typeof P){case"string":return f(P);case"object":{if(P===null)return"null";if(typeof P.toJSON=="function"){if(P=P.toJSON(ke),typeof P!="object")return Le(ke,P,W,M,H);if(P===null)return"null"}if(W.indexOf(P)!==-1)return L;const z=H;if(Array.isArray(P)){if(P.length===0)return"[]";if(meue){const Ge=P.length-ue-1;ie+=`${he}"... ${q(Ge)} not stringified"`}return ie+=` ${z}`,W.pop(),`[${ie}]`}let w=Object.keys(P);const E=w.length;if(E===0)return"{}";if(meue){const ie=E-ue;ne+=`${te}"...": "${q(ie)} not stringified"`,te=ee}return te!==""&&(ne=` ${H}${ne} ${z}`),W.pop(),`{${ne}}`}case"number":return isFinite(P)?String(P):A?A(P):"null";case"boolean":return P===!0?"true":"false";case"undefined":return;case"bigint":if(J)return String(P);default:return A?A(P):void 0}}function Me(ke,P,W){switch(typeof P){case"string":return f(P);case"object":{if(P===null)return"null";if(typeof P.toJSON=="function"){if(P=P.toJSON(ke),typeof P!="object")return Me(ke,P,W);if(P===null)return"null"}if(W.indexOf(P)!==-1)return L;let M="";const H=P.length!==void 0;if(H&&Array.isArray(P)){if(P.length===0)return"[]";if(meue){const ie=P.length-ue-1;M+=`,"... ${q(ie)} not stringified"`}return W.pop(),`[${M}]`}let z=Object.keys(P);const w=z.length;if(w===0)return"{}";if(meue){const ne=w-ue;M+=`${E}"...":"${q(ne)} not stringified"`}return W.pop(),`{${M}}`}case"number":return isFinite(P)?String(P):A?A(P):"null";case"boolean":return P===!0?"true":"false";case"undefined":return;case"bigint":if(J)return String(P);default:return A?A(P):void 0}}function it(ke,P,W){if(arguments.length>1){let M="";if(typeof W=="number"?M=" ".repeat(Math.min(W,10)):typeof W=="string"&&(M=W.slice(0,10)),P!=null){if(typeof P=="function")return Re("",{"":ke},[],P,M,"");if(Array.isArray(P))return We("",ke,[],Q(P),M,"")}if(M.length!==0)return Le("",ke,[],M,"")}return Me("",ke,[])}return it}})(Jo,Jo.exports)),Jo.exports}var Bm=Pm();const wh=yh(Bm);wh.configure;const Lf=wh;var bi=class Yo{__time_duration_micros__;static MICROS_PER_MILLIS=1000n;static getAlgebraicType(){return oe.Product({elements:[{name:"__time_duration_micros__",algebraicType:oe.I64}]})}static isTimeDuration(n){if(n.tag!=="Product")return!1;const s=n.value.elements;if(s.length!==1)return!1;const a=s[0];return a.name==="__time_duration_micros__"&&a.algebraicType.tag==="I64"}get micros(){return this.__time_duration_micros__}get millis(){return Number(this.micros/Yo.MICROS_PER_MILLIS)}constructor(n){this.__time_duration_micros__=n}static fromMillis(n){return new Yo(BigInt(n)*Yo.MICROS_PER_MILLIS)}toString(){const n=this.micros,s=n<0?"-":"+",a=n<0?-n:n,c=a/1000000n,f=a%1000000n;return`${s}${c}.${String(f).padStart(6,"0")}`}},Ci=class rn{__timestamp_micros_since_unix_epoch__;static MICROS_PER_MILLIS=1000n;get microsSinceUnixEpoch(){return this.__timestamp_micros_since_unix_epoch__}constructor(n){this.__timestamp_micros_since_unix_epoch__=n}static getAlgebraicType(){return oe.Product({elements:[{name:"__timestamp_micros_since_unix_epoch__",algebraicType:oe.I64}]})}static isTimestamp(n){if(n.tag!=="Product")return!1;const s=n.value.elements;if(s.length!==1)return!1;const a=s[0];return a.name==="__timestamp_micros_since_unix_epoch__"&&a.algebraicType.tag==="I64"}static UNIX_EPOCH=new rn(0n);static now(){return rn.fromDate(new Date)}toMillis(){return this.microsSinceUnixEpoch/1000n}static fromDate(n){const s=n.getTime(),a=BigInt(s)*rn.MICROS_PER_MILLIS;return new rn(a)}toDate(){const s=this.__timestamp_micros_since_unix_epoch__/rn.MICROS_PER_MILLIS;if(s>BigInt(Number.MAX_SAFE_INTEGER)||sBigInt(Number.MAX_SAFE_INTEGER)||svt.MAX_UUID_BIGINT)throw new Error("Invalid UUID: must be between 0 and `MAX_UUID_BIGINT`");this.__uuid__=n}static fromRandomBytesV4(n){if(n.length!==16)throw new Error("UUID v4 requires 16 bytes");const s=new Uint8Array(n);return s[6]=s[6]&15|64,s[8]=s[8]&63|128,new vt(vt.bytesToBigInt(s))}static fromCounterV7(n,s,a){if(a.length!==4)throw new Error("`fromCounterV7` requires `randomBytes.length == 4`");if(n.value<0)throw new Error("`fromCounterV7` uuid `counter` must be non-negative");if(s.__timestamp_micros_since_unix_epoch__<0)throw new Error("`fromCounterV7` `timestamp` before unix epoch");const c=n.value;n.value=c+1&2147483647;const f=s.toMillis()&0xffffffffffffn,p=new Uint8Array(16);return p[0]=Number(f>>40n&0xffn),p[1]=Number(f>>32n&0xffn),p[2]=Number(f>>24n&0xffn),p[3]=Number(f>>16n&0xffn),p[4]=Number(f>>8n&0xffn),p[5]=Number(f&0xffn),p[7]=c>>>23&255,p[9]=c>>>15&255,p[10]=c>>>7&255,p[11]=(c&127)<<1&255,p[12]|=a[0]&127,p[13]=a[1],p[14]=a[2],p[15]=a[3],p[6]=p[6]&15|112,p[8]=p[8]&63|128,new vt(vt.bytesToBigInt(p))}static parse(n){const s=n.replace(/-/g,"");if(s.length!==32)throw new Error("Invalid hex UUID");let a=0n;for(let c=0;c<32;c+=2)a=a<<8n|BigInt(parseInt(s.slice(c,c+2),16));return new vt(a)}toString(){const s=[...vt.bigIntToBytes(this.__uuid__)].map(a=>a.toString(16).padStart(2,"0")).join("");return s.slice(0,8)+"-"+s.slice(8,12)+"-"+s.slice(12,16)+"-"+s.slice(16,20)+"-"+s.slice(20)}asBigInt(){return this.__uuid__}toBytes(){return vt.bigIntToBytes(this.__uuid__)}static bytesToBigInt(n){let s=0n;for(const a of n)s=s<<8n|BigInt(a);return s}static bigIntToBytes(n){const s=new Uint8Array(16);for(let a=15;a>=0;a--)s[a]=Number(n&0xffn),n>>=8n;return s}getVersion(){const n=this.toBytes()[6]>>4&15;switch(n){case 4:return"V4";case 7:return"V7";default:if(this==vt.NIL)return"Nil";if(this==vt.MAX)return"Max";throw new Error(`Unsupported UUID version: ${n}`)}}getCounter(){const n=this.toBytes(),s=n[7],a=n[9],c=n[10],f=n[11]>>>1;return s<<23|a<<15|c<<7|f|0}compareTo(n){return this.__uuid__n.__uuid__?1:0}static getAlgebraicType(){return oe.Product({elements:[{name:"__uuid__",algebraicType:oe.U128}]})}},ze=class{view;offset=0;constructor(n){this.view=n instanceof DataView?n:new DataView(n.buffer,n.byteOffset,n.byteLength),this.offset=0}reset(n){this.view=n,this.offset=0}get remaining(){return this.view.byteLength-this.offset}#e(n){if(this.offset+n>this.view.byteLength)throw new RangeError(`Tried to read ${n} byte(s) at relative offset ${this.offset}, but only ${this.remaining} byte(s) remain`)}readUInt8Array(){const n=this.readU32();return this.#e(n),this.readBytes(n)}readBool(){const n=this.view.getUint8(this.offset);return this.offset+=1,n!==0}readByte(){const n=this.view.getUint8(this.offset);return this.offset+=1,n}readBytes(n){const s=new Uint8Array(this.view.buffer,this.view.byteOffset+this.offset,n);return this.offset+=n,s}readI8(){const n=this.view.getInt8(this.offset);return this.offset+=1,n}readU8(){return this.readByte()}readI16(){const n=this.view.getInt16(this.offset,!0);return this.offset+=2,n}readU16(){const n=this.view.getUint16(this.offset,!0);return this.offset+=2,n}readI32(){const n=this.view.getInt32(this.offset,!0);return this.offset+=4,n}readU32(){const n=this.view.getUint32(this.offset,!0);return this.offset+=4,n}readI64(){const n=this.view.getBigInt64(this.offset,!0);return this.offset+=8,n}readU64(){const n=this.view.getBigUint64(this.offset,!0);return this.offset+=8,n}readU128(){const n=this.view.getBigUint64(this.offset,!0),s=this.view.getBigUint64(this.offset+8,!0);return this.offset+=16,(s<>BigInt(64);this.view.setBigUint64(this.offset,s,!0),this.view.setBigUint64(this.offset+8,a,!0),this.offset+=16}writeI128(n){this.expandBuffer(16);const s=n&BigInt("0xFFFFFFFFFFFFFFFF"),a=n>>BigInt(64);this.view.setBigInt64(this.offset,s,!0),this.view.setBigInt64(this.offset+8,a,!0),this.offset+=16}writeU256(n){this.expandBuffer(32);const s=BigInt("0xFFFFFFFFFFFFFFFF"),a=n&s,c=n>>BigInt(64)&s,f=n>>BigInt(128)&s,p=n>>BigInt(192);this.view.setBigUint64(this.offset+0,a,!0),this.view.setBigUint64(this.offset+8,c,!0),this.view.setBigUint64(this.offset+16,f,!0),this.view.setBigUint64(this.offset+24,p,!0),this.offset+=32}writeI256(n){this.expandBuffer(32);const s=BigInt("0xFFFFFFFFFFFFFFFF"),a=n&s,c=n>>BigInt(64)&s,f=n>>BigInt(128)&s,p=n>>BigInt(192);this.view.setBigUint64(this.offset+0,a,!0),this.view.setBigUint64(this.offset+8,c,!0),this.view.setBigUint64(this.offset+16,f,!0),this.view.setBigInt64(this.offset+24,p,!0),this.offset+=32}writeF32(n){this.expandBuffer(4),this.view.setFloat32(this.offset,n,!0),this.offset+=4}writeF64(n){this.expandBuffer(8),this.view.setFloat64(this.offset,n,!0),this.offset+=8}writeString(n){const a=new TextEncoder().encode(n);this.writeUInt8Array(a)}};function Is(r,n){if(r===n)return!0;if(typeof r!="object"||r===null||typeof n!="object"||n===null)return!1;const s=Object.keys(r),a=Object.keys(n);if(s.length!==a.length)return!1;for(const c of s)if(!a.includes(c)||!Is(r[c],n[c]))return!1;return!0}function _h(r){return Array.prototype.map.call(r.reverse(),n=>("00"+n.toString(16)).slice(-2)).join("")}function jm(r){if(r.length!=16)throw new Error(`Uint8Array is not 16 bytes long: ${r}`);return new ze(r).readU128()}function Om(r){if(r.length!=32)throw new Error(`Uint8Array is not 32 bytes long: [${r}]`);return new ze(r).readU256()}function Sh(r){r.startsWith("0x")&&(r=r.slice(2));const n=r.match(/.{1,2}/g)||[];return Uint8Array.from(n.map(a=>parseInt(a,16))).reverse()}function Dm(r){return jm(Sh(r))}function zm(r){return Om(Sh(r))}function xh(r){const n=new Pe(16);return n.writeU128(r),n.getBuffer()}function Ih(r){return _h(xh(r))}function kh(r){const n=new Pe(32);return n.writeU256(r),n.getBuffer()}function bh(r){return _h(kh(r))}function Fm(r){const n=Ch(r);return n.charAt(0).toUpperCase()+n.slice(1)}function Ch(r){const n=r.replace(/[-_]+/g,"_").replace(/_([a-zA-Z0-9])/g,(s,a)=>a.toUpperCase());return n.charAt(0).toLowerCase()+n.slice(1)}var Vf=Object.hasOwn,Bs=class fu{__identity__;constructor(n){this.__identity__=typeof n=="string"?zm(n):n}static getAlgebraicType(){return oe.Product({elements:[{name:"__identity__",algebraicType:oe.U256}]})}isEqual(n){return this.toHexString()===n.toHexString()}equals(n){return this.isEqual(n)}toHexString(){return bh(this.__identity__)}toUint8Array(){return kh(this.__identity__)}static fromString(n){return new fu(n)}static zero(){return new fu(0n)}toString(){return this.toHexString()}},bs=new Map,Cs=new Map,oe={Ref:r=>({tag:"Ref",value:r}),Sum:r=>({tag:"Sum",value:r}),Product:r=>({tag:"Product",value:r}),Array:r=>({tag:"Array",value:r}),String:{tag:"String"},Bool:{tag:"Bool"},I8:{tag:"I8"},U8:{tag:"U8"},I16:{tag:"I16"},U16:{tag:"U16"},I32:{tag:"I32"},U32:{tag:"U32"},I64:{tag:"I64"},U64:{tag:"U64"},I128:{tag:"I128"},U128:{tag:"U128"},I256:{tag:"I256"},U256:{tag:"U256"},F32:{tag:"F32"},F64:{tag:"F64"},makeSerializer(r,n){if(r.tag==="Ref"){if(!n)throw new Error("cannot serialize refs without a typespace");for(;r.tag==="Ref";)r=n.types[r.value]}switch(r.tag){case"Product":return pr.makeSerializer(r.value,n);case"Sum":return ua.makeSerializer(r.value,n);case"Array":if(r.value.tag==="U8")return $m;{const s=oe.makeSerializer(r.value,n);return(a,c)=>{a.writeU32(c.length);for(const f of c)s(a,f)}}default:return Th[r.tag]}},serializeValue(r,n,s,a){oe.makeSerializer(n,a)(r,s)},makeDeserializer(r,n){if(r.tag==="Ref"){if(!n)throw new Error("cannot deserialize refs without a typespace");for(;r.tag==="Ref";)r=n.types[r.value]}switch(r.tag){case"Product":return pr.makeDeserializer(r.value,n);case"Sum":return ua.makeDeserializer(r.value,n);case"Array":if(r.value.tag==="U8")return Lm;{const s=oe.makeDeserializer(r.value,n);return a=>{const c=a.readU32(),f=Array(c);for(let p=0;pr.elements.every(({algebraicType:n})=>Vm.has(n.tag)),qm=r=>r.elements.reduce((n,{algebraicType:s})=>n+xi[s.tag],0),Go={Bool:"Uint8",I8:"Int8",U8:"Uint8",I16:"Int16",U16:"Uint16",I32:"Int32",U32:"Uint32",I64:"BigInt64",U64:"BigUint64",F32:"Float32",F64:"Float64"},Zo={__time_duration_micros__:r=>new bi(r.readI64()),__timestamp_micros_since_unix_epoch__:r=>new Ci(r.readI64()),__identity__:r=>new Bs(r.readU256()),__connection_id__:r=>new ga(r.readU128()),__uuid__:r=>new vh(r.readU128())};Object.freeze(Zo);var Hm=()=>({}),Hf=r=>{let n;switch(r.algebraicType.tag){case"String":n="''";break;case"Bool":n="false";break;case"I8":case"U8":case"I16":case"U16":case"I32":case"U32":n="0";break;case"I64":case"U64":case"I128":case"U128":case"I256":case"U256":n="0n";break;case"F32":case"F64":n="0.0";break;default:n="undefined"}return`${r.name}: ${n}`},pr={makeSerializer(r,n){let s=bs.get(r);if(s!=null)return s;if(qf(r)){const p=`"use strict"; writer.expandBuffer(${qm(r)}); const view = writer.view; ${r.elements.map(({name:v,algebraicType:{tag:y}})=>y in Go?`view.set${Go[y]}(writer.offset, value.${v}, ${xi[y]>1?"true":""}); writer.offset += ${xi[y]};`:`writer.write${y}(value.${v});`).join(` `)}`;return s=Function("writer","value",p),bs.set(r,s),s}const a={},c=`"use strict"; `+r.elements.map(f=>`this.${f.name}(writer, value.${f.name});`).join(` `);s=Function("writer","value",c).bind(a),bs.set(r,s);for(const{name:f,algebraicType:p}of r.elements)a[f]=oe.makeSerializer(p,n);return Object.freeze(a),s},serializeValue(r,n,s,a){pr.makeSerializer(n,a)(r,s)},makeDeserializer(r,n){switch(r.elements.length){case 0:return Hm;case 1:{const c=r.elements[0].name;if(Vf(Zo,c))return Zo[c]}}let s=Cs.get(r);if(s!=null)return s;if(qf(r)){const c=`"use strict"; const result = { ${r.elements.map(Hf).join(", ")} }; const view = reader.view; ${r.elements.map(({name:f,algebraicType:{tag:p}})=>p in Go?p==="Bool"?`result.${f} = view.getUint8(reader.offset) !== 0; reader.offset += 1;`:`result.${f} = view.get${Go[p]}(reader.offset, ${xi[p]>1?"true":""}); reader.offset += ${xi[p]};`:`result.${f} = reader.read${p}();`).join(` `)} return result;`;return s=Function("reader",c),Cs.set(r,s),s}const a={};s=Function("reader",`"use strict"; const result = { ${r.elements.map(Hf).join(", ")} }; ${r.elements.map(({name:c})=>`result.${c} = this.${c}(reader);`).join(` `)} return result;`).bind(a),Cs.set(r,s);for(const{name:c,algebraicType:f}of r.elements)a[c]=oe.makeDeserializer(f,n);return Object.freeze(a),s},deserializeValue(r,n,s){return pr.makeDeserializer(n,s)(r)},intoMapKey(r,n){if(r.elements.length===1){const a=r.elements[0].name;if(Vf(Zo,a))return n[a]}const s=new Pe(10);return oe.serializeValue(s,oe.Product(r),n),s.toBase64()}},ua={makeSerializer(r,n){if(r.variants.length==2&&r.variants[0].name==="some"&&r.variants[1].name==="none"){const s=oe.makeSerializer(r.variants[0].algebraicType,n);return(a,c)=>{c!=null?(a.writeByte(0),s(a,c)):a.writeByte(1)}}else if(r.variants.length==2&&r.variants[0].name==="ok"&&r.variants[1].name==="err"){const s=oe.makeSerializer(r.variants[0].algebraicType,n),a=oe.makeSerializer(r.variants[0].algebraicType,n);return(c,f)=>{if("ok"in f)c.writeU8(0),s(c,f.ok);else if("err"in f)c.writeU8(1),a(c,f.err);else throw new TypeError("could not serialize result: object had neither a `ok` nor an `err` field")}}else{let s=bs.get(r);if(s!=null)return s;const a={},c=`switch (value.tag) { ${r.variants.map(({name:f},p)=>` case ${JSON.stringify(f)}: writer.writeByte(${p}); return this.${f}(writer, value.value);`).join(` `)} default: throw new TypeError( \`Could not serialize sum type; unknown tag \${value.tag}\` ) } `;s=Function("writer","value",c).bind(a),bs.set(r,s);for(const{name:f,algebraicType:p}of r.variants)a[f]=oe.makeSerializer(p,n);return Object.freeze(a),s}},serializeValue(r,n,s,a){ua.makeSerializer(n,a)(r,s)},makeDeserializer(r,n){if(r.variants.length==2&&r.variants[0].name==="some"&&r.variants[1].name==="none"){const s=oe.makeDeserializer(r.variants[0].algebraicType,n);return a=>{const c=a.readU8();if(c===0)return s(a);if(c===1)return;throw`Can't deserialize an option type, couldn't find ${c} tag`}}else if(r.variants.length==2&&r.variants[0].name==="ok"&&r.variants[1].name==="err"){const s=oe.makeDeserializer(r.variants[0].algebraicType,n),a=oe.makeDeserializer(r.variants[1].algebraicType,n);return c=>{const f=c.readByte();if(f===0)return{ok:s(c)};if(f===1)return{err:a(c)};throw`Can't deserialize a result type, couldn't find ${f} tag`}}else{let s=Cs.get(r);if(s!=null)return s;const a={};s=Function("reader",`switch (reader.readU8()) { ${r.variants.map(({name:c},f)=>`case ${f}: return { tag: ${JSON.stringify(c)}, value: this.${c}(reader) };`).join(` `)} }`).bind(a),Cs.set(r,s);for(const{name:c,algebraicType:f}of r.variants)a[c]=oe.makeDeserializer(f,n);return Object.freeze(a),s}},deserializeValue(r,n,s){return ua.makeDeserializer(n,s)(r)}},ga=class ea{__connection_id__;constructor(n){this.__connection_id__=n}static getAlgebraicType(){return oe.Product({elements:[{name:"__connection_id__",algebraicType:oe.U128}]})}isZero(){return this.__connection_id__===BigInt(0)}static nullIfZero(n){return n.isZero()?null:n}static random(){function n(){return Math.floor(Math.random()*255)}let s=BigInt(0);for(let a=0;a<16;a++)s=s<c.name==="Interval"),a=n.find(c=>c.name==="Time");return!s||!a?!1:bi.isTimeDuration(s.algebraicType)&&Ci.isTimestamp(a.algebraicType)}},Jm=r=>({tag:"Interval",value:new bi(r)}),Gm=r=>({tag:"Time",value:new Ci(r)}),Uh=Qm,Xm={getAlgebraicType(r){return oe.Sum({variants:[{name:"some",algebraicType:r},{name:"none",algebraicType:oe.Product({elements:[]})}]})}},Ym={getAlgebraicType(r,n){return oe.Sum({variants:[{name:"ok",algebraicType:r},{name:"err",algebraicType:n}]})}},ma=Symbol("QueryBrand"),Zm=r=>!!r&&typeof r=="object"&&ma in r;function ey(r){return r.toSql()}var Kf=class Rh{constructor(n,s,a){if(this.sourceQuery=n,this.filterQuery=s,this.joinCondition=a,n.table.sourceName===s.table.sourceName)throw new Error("Cannot semijoin a table to itself")}[ma]=!0;type="semijoin";build(){return this}where(n){const s=this.sourceQuery.where(n);return new Rh(s,this.filterQuery,this.joinCondition)}toSql(){const n=this.filterQuery,s=this.sourceQuery,a=As(n.table.sourceName),c=As(s.table.sourceName);let f=`SELECT ${c}.* FROM ${a} JOIN ${c} ON ${yn(this.joinCondition)}`;const p=[];if(n.whereClause&&p.push(yn(n.whereClause)),s.whereClause&&p.push(yn(s.whereClause)),p.length>0){const v=p.length===1?p[0]:p.map(Ts).join(" AND ");f+=` WHERE ${v}`}return f}},ty=class ta{constructor(n,s){this.table=n,this.whereClause=s}[ma]=!0;where(n){const s=ay(n(this.table.cols)),a=this.whereClause?this.whereClause.and(s):s;return new ta(this.table,a)}rightSemijoin(n,s){const a=new ta(n),c=s(this.table.indexedCols,n.indexedCols);return new Kf(a,this,c)}leftSemijoin(n,s){const a=new ta(n),c=s(this.table.indexedCols,n.indexedCols);return new Kf(this,a,c)}toSql(){return sy(this.table,this.whereClause)}build(){return this}},ry=class{[ma]=!0;type="table";sourceName;accessorName;cols;indexedCols;tableDef;get columns(){return this.tableDef.columns}get indexes(){return this.tableDef.indexes}get rowType(){return this.tableDef.rowType}get constraints(){return this.tableDef.constraints}constructor(r){this.sourceName=r.sourceName,this.accessorName=r.accessorName,this.cols=iy(r),this.indexedCols=this.cols,this.tableDef=r,Object.freeze(this)}asFrom(){return new ty(this)}rightSemijoin(r,n){return this.asFrom().rightSemijoin(r,n)}leftSemijoin(r,n){return this.asFrom().leftSemijoin(r,n)}build(){return this.asFrom().build()}toSql(){return this.asFrom().toSql()}where(r){return this.asFrom().where(r)}};function ny(r){return new ry(r)}function Nh(r){const n=Object.create(null);for(const s of Object.values(r.tables)){const a=ny(s);n[s.accessorName]=a}return Object.freeze(n)}function iy(r){const n={};for(const s of Object.keys(r.columns)){const a=r.columns[s],c=new oy(r.sourceName,s,a.typeBuilder.algebraicType,a.columnMetadata.name);n[s]=Object.freeze(c)}return Object.freeze(n)}function sy(r,n,s=[]){const c=`SELECT * FROM ${As(r.sourceName)}`,f=[];if(n&&f.push(yn(n)),f.push(...s),f.length===0)return c;const p=f.length===1?f[0]:f.map(Ts).join(" AND ");return`${c} WHERE ${p}`}var oy=class{type="column";column;columnName;table;tsValueType;spacetimeType;constructor(r,n,s,a){this.table=r,this.column=n,this.columnName=a||n,this.spacetimeType=s}eq(r){return new rr({type:"eq",left:this,right:Qn(r)})}ne(r){return new rr({type:"ne",left:this,right:Qn(r)})}lt(r){return new rr({type:"lt",left:this,right:Qn(r)})}lte(r){return new rr({type:"lte",left:this,right:Qn(r)})}gt(r){return new rr({type:"gt",left:this,right:Qn(r)})}gte(r){return new rr({type:"gte",left:this,right:Qn(r)})}};function ra(r){return{type:"literal",value:r}}function Qn(r){return r.type==="literal"||typeof r=="object"&&r!=null&&"type"in r&&r.type==="column"?r:ra(r)}function ay(r){return r instanceof rr?r:typeof r=="boolean"?new rr({type:"eq",left:ra(r),right:ra(!0)}):new rr({type:"eq",left:r,right:ra(!0)})}var rr=class na{constructor(n){this.data=n}and(n){return new na({type:"and",clauses:[this.data,n.data]})}or(n){return new na({type:"or",clauses:[this.data,n.data]})}not(){return new na({type:"not",clause:this.data})}};function yn(r,n){const s=r instanceof rr?r.data:r;switch(s.type){case"eq":return`${Mt(s.left)} = ${Mt(s.right)}`;case"ne":return`${Mt(s.left)} <> ${Mt(s.right)}`;case"gt":return`${Mt(s.left)} > ${Mt(s.right)}`;case"gte":return`${Mt(s.left)} >= ${Mt(s.right)}`;case"lt":return`${Mt(s.left)} < ${Mt(s.right)}`;case"lte":return`${Mt(s.left)} <= ${Mt(s.right)}`;case"and":return s.clauses.map(a=>yn(a)).map(Ts).join(" AND ");case"or":return s.clauses.map(a=>yn(a)).map(Ts).join(" OR ");case"not":return`NOT ${Ts(yn(s.clause))}`}}function Ts(r){return`(${r})`}function Mt(r,n){if(uy(r))return ly(r.value);const s=r.table;return`${As(s)}.${As(r.columnName)}`}function ly(r){if(r==null)return"NULL";if(r instanceof Bs||r instanceof ga)return`0x${r.toHexString()}`;if(r instanceof Ci)return`'${r.toISOString()}'`;switch(typeof r){case"number":case"bigint":return String(r);case"boolean":return r?"TRUE":"FALSE";case"string":return`'${r.replace(/'/g,"''")}'`;default:return`'${JSON.stringify(r).replace(/'/g,"''")}'`}}function As(r){return`"${r.replace(/"/g,'""')}"`}function uy(r){return r.type==="literal"}function g(r,n){return{...r,...n}}var Te=class{type;algebraicType;constructor(r){this.algebraicType=r}optional(){return new ca(this)}serialize(r,n){(this.serialize=oe.makeSerializer(this.algebraicType))(r,n)}deserialize(r){return(this.deserialize=oe.makeDeserializer(this.algebraicType))(r)}},cy=class extends Te{constructor(){super(oe.U8)}index(r="btree"){return new Jn(this,g(U,{indexType:r}))}unique(){return new Jn(this,g(U,{isUnique:!0}))}primaryKey(){return new Jn(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new Jn(this,g(U,{isAutoIncrement:!0}))}default(r){return new Jn(this,g(U,{defaultValue:r}))}name(r){return new Jn(this,g(U,{name:r}))}},dy=class extends Te{constructor(){super(oe.U16)}index(r="btree"){return new Gn(this,g(U,{indexType:r}))}unique(){return new Gn(this,g(U,{isUnique:!0}))}primaryKey(){return new Gn(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new Gn(this,g(U,{isAutoIncrement:!0}))}default(r){return new Gn(this,g(U,{defaultValue:r}))}name(r){return new Gn(this,g(U,{name:r}))}},fy=class extends Te{constructor(){super(oe.U32)}index(r="btree"){return new Xn(this,g(U,{indexType:r}))}unique(){return new Xn(this,g(U,{isUnique:!0}))}primaryKey(){return new Xn(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new Xn(this,g(U,{isAutoIncrement:!0}))}default(r){return new Xn(this,g(U,{defaultValue:r}))}name(r){return new Xn(this,g(U,{name:r}))}},hy=class extends Te{constructor(){super(oe.U64)}index(r="btree"){return new Yn(this,g(U,{indexType:r}))}unique(){return new Yn(this,g(U,{isUnique:!0}))}primaryKey(){return new Yn(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new Yn(this,g(U,{isAutoIncrement:!0}))}default(r){return new Yn(this,g(U,{defaultValue:r}))}name(r){return new Yn(this,g(U,{name:r}))}},py=class extends Te{constructor(){super(oe.U128)}index(r="btree"){return new Zn(this,g(U,{indexType:r}))}unique(){return new Zn(this,g(U,{isUnique:!0}))}primaryKey(){return new Zn(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new Zn(this,g(U,{isAutoIncrement:!0}))}default(r){return new Zn(this,g(U,{defaultValue:r}))}name(r){return new Zn(this,g(U,{name:r}))}},gy=class extends Te{constructor(){super(oe.U256)}index(r="btree"){return new ei(this,g(U,{indexType:r}))}unique(){return new ei(this,g(U,{isUnique:!0}))}primaryKey(){return new ei(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new ei(this,g(U,{isAutoIncrement:!0}))}default(r){return new ei(this,g(U,{defaultValue:r}))}name(r){return new ei(this,g(U,{name:r}))}},my=class extends Te{constructor(){super(oe.I8)}index(r="btree"){return new ti(this,g(U,{indexType:r}))}unique(){return new ti(this,g(U,{isUnique:!0}))}primaryKey(){return new ti(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new ti(this,g(U,{isAutoIncrement:!0}))}default(r){return new ti(this,g(U,{defaultValue:r}))}name(r){return new ti(this,g(U,{name:r}))}},yy=class extends Te{constructor(){super(oe.I16)}index(r="btree"){return new ri(this,g(U,{indexType:r}))}unique(){return new ri(this,g(U,{isUnique:!0}))}primaryKey(){return new ri(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new ri(this,g(U,{isAutoIncrement:!0}))}default(r){return new ri(this,g(U,{defaultValue:r}))}name(r){return new ri(this,g(U,{name:r}))}},wy=class extends Te{constructor(){super(oe.I32)}index(r="btree"){return new ni(this,g(U,{indexType:r}))}unique(){return new ni(this,g(U,{isUnique:!0}))}primaryKey(){return new ni(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new ni(this,g(U,{isAutoIncrement:!0}))}default(r){return new ni(this,g(U,{defaultValue:r}))}name(r){return new ni(this,g(U,{name:r}))}},vy=class extends Te{constructor(){super(oe.I64)}index(r="btree"){return new ii(this,g(U,{indexType:r}))}unique(){return new ii(this,g(U,{isUnique:!0}))}primaryKey(){return new ii(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new ii(this,g(U,{isAutoIncrement:!0}))}default(r){return new ii(this,g(U,{defaultValue:r}))}name(r){return new ii(this,g(U,{name:r}))}},_y=class extends Te{constructor(){super(oe.I128)}index(r="btree"){return new si(this,g(U,{indexType:r}))}unique(){return new si(this,g(U,{isUnique:!0}))}primaryKey(){return new si(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new si(this,g(U,{isAutoIncrement:!0}))}default(r){return new si(this,g(U,{defaultValue:r}))}name(r){return new si(this,g(U,{name:r}))}},Sy=class extends Te{constructor(){super(oe.I256)}index(r="btree"){return new oi(this,g(U,{indexType:r}))}unique(){return new oi(this,g(U,{isUnique:!0}))}primaryKey(){return new oi(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new oi(this,g(U,{isAutoIncrement:!0}))}default(r){return new oi(this,g(U,{defaultValue:r}))}name(r){return new oi(this,g(U,{name:r}))}},xy=class extends Te{constructor(){super(oe.F32)}default(r){return new Qf(this,g(U,{defaultValue:r}))}name(r){return new Qf(this,g(U,{name:r}))}},Wf=class extends Te{constructor(){super(oe.F64)}default(r){return new Jf(this,g(U,{defaultValue:r}))}name(r){return new Jf(this,g(U,{name:r}))}},Iy=class extends Te{constructor(){super(oe.Bool)}index(r="btree"){return new _s(this,g(U,{indexType:r}))}unique(){return new _s(this,g(U,{isUnique:!0}))}primaryKey(){return new _s(this,g(U,{isPrimaryKey:!0}))}default(r){return new _s(this,g(U,{defaultValue:r}))}name(r){return new _s(this,g(U,{name:r}))}},ky=class extends Te{constructor(){super(oe.String)}index(r="btree"){return new Ss(this,g(U,{indexType:r}))}unique(){return new Ss(this,g(U,{isUnique:!0}))}primaryKey(){return new Ss(this,g(U,{isPrimaryKey:!0}))}default(r){return new Ss(this,g(U,{defaultValue:r}))}name(r){return new Ss(this,g(U,{name:r}))}},hu=class extends Te{element;constructor(r){super(oe.Array(r.algebraicType)),this.element=r}default(r){return new Gf(this,g(U,{defaultValue:r}))}name(r){return new Gf(this,g(U,{name:r}))}},by=class extends Te{constructor(){super(oe.Array(oe.U8))}default(r){return new Xf(g(U,{defaultValue:r}))}name(r){return new Xf(g(U,{name:r}))}},ca=class extends Te{value;constructor(r){super(Xm.getAlgebraicType(r.algebraicType)),this.value=r}default(r){return new Yf(this,g(U,{defaultValue:r}))}name(r){return new Yf(this,g(U,{name:r}))}},ki=class extends Te{typeName;elements;constructor(r,n){function s(a){return Object.keys(a).map(c=>({name:c,get algebraicType(){return a[c].algebraicType}}))}super(oe.Product({elements:s(r)})),this.typeName=n,this.elements=r}default(r){return new Zf(this,g(U,{defaultValue:r}))}name(r){return new Zf(this,g(U,{name:r}))}},pu=class extends Te{ok;err;constructor(r,n){super(Ym.getAlgebraicType(r.algebraicType,n.algebraicType)),this.ok=r,this.err=n}default(r){return new By(this,g(U,{defaultValue:r}))}},ju=class extends Te{constructor(){super({tag:"Product",value:{elements:[]}})}},wn=class extends Te{row;typeName;constructor(r,n){const s=Object.fromEntries(Object.entries(r).map(([c,f])=>[c,f instanceof Ee?f:new Ee(f,{})])),a=Object.keys(s).map(c=>({name:c,get algebraicType(){return s[c].typeBuilder.algebraicType}}));super(oe.Product({elements:a})),this.row=s,this.typeName=n}},Ph=class extends Te{variants;typeName;constructor(r,n){function s(a){return Object.keys(a).map(c=>({name:c,get algebraicType(){return a[c].algebraicType}}))}super(oe.Sum({variants:s(r)})),this.variants=r,this.typeName=n;for(const a of Object.keys(r)){const c=Object.getOwnPropertyDescriptor(r,a),f=!!c&&(typeof c.get=="function"||typeof c.set=="function");let p=!1;if(f||(p=r[a]instanceof ju),p){const v=this.create(a);Object.defineProperty(this,a,{value:v,writable:!1,enumerable:!0,configurable:!1})}else Object.defineProperty(this,a,{value:(y=>this.create(a,y)),writable:!1,enumerable:!0,configurable:!1})}}create(r,n){return n===void 0?{tag:r}:{tag:r,value:n}}default(r){return new xu(this,g(U,{defaultValue:r}))}name(r){return new xu(this,g(U,{name:r}))}},gu=Ph,Cy=class extends Ph{index(r="btree"){return new eh(this,g(U,{indexType:r}))}primaryKey(){return new eh(this,g(U,{isPrimaryKey:!0}))}},Ty=class extends Te{constructor(){super(Uh.getAlgebraicType())}default(r){return new th(this,g(U,{defaultValue:r}))}name(r){return new th(this,g(U,{name:r}))}},Ey=class extends Te{constructor(){super(Bs.getAlgebraicType())}index(r="btree"){return new ai(this,g(U,{indexType:r}))}unique(){return new ai(this,g(U,{isUnique:!0}))}primaryKey(){return new ai(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new ai(this,g(U,{isAutoIncrement:!0}))}default(r){return new ai(this,g(U,{defaultValue:r}))}name(r){return new ai(this,g(U,{name:r}))}},Uy=class extends Te{constructor(){super(ga.getAlgebraicType())}index(r="btree"){return new li(this,g(U,{indexType:r}))}unique(){return new li(this,g(U,{isUnique:!0}))}primaryKey(){return new li(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new li(this,g(U,{isAutoIncrement:!0}))}default(r){return new li(this,g(U,{defaultValue:r}))}name(r){return new li(this,g(U,{name:r}))}},Ry=class extends Te{constructor(){super(Ci.getAlgebraicType())}index(r="btree"){return new ui(this,g(U,{indexType:r}))}unique(){return new ui(this,g(U,{isUnique:!0}))}primaryKey(){return new ui(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new ui(this,g(U,{isAutoIncrement:!0}))}default(r){return new ui(this,g(U,{defaultValue:r}))}name(r){return new ui(this,g(U,{name:r}))}},Ny=class extends Te{constructor(){super(bi.getAlgebraicType())}index(r="btree"){return new ci(this,g(U,{indexType:r}))}unique(){return new ci(this,g(U,{isUnique:!0}))}primaryKey(){return new ci(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new ci(this,g(U,{isAutoIncrement:!0}))}default(r){return new ci(this,g(U,{defaultValue:r}))}name(r){return new ci(this,g(U,{name:r}))}},Py=class extends Te{constructor(){super(vh.getAlgebraicType())}index(r="btree"){return new di(this,g(U,{indexType:r}))}unique(){return new di(this,g(U,{isUnique:!0}))}primaryKey(){return new di(this,g(U,{isPrimaryKey:!0}))}autoInc(){return new di(this,g(U,{isAutoIncrement:!0}))}default(r){return new di(this,g(U,{defaultValue:r}))}name(r){return new di(this,g(U,{name:r}))}},U={},Ee=class{typeBuilder;columnMetadata;constructor(r,n){this.typeBuilder=r,this.columnMetadata=n}serialize(r,n){this.typeBuilder.serialize(r,n)}deserialize(r){return this.typeBuilder.deserialize(r)}},Jn=class nn extends Ee{index(n="btree"){return new nn(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new nn(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new nn(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new nn(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new nn(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new nn(this.typeBuilder,g(this.columnMetadata,{name:n}))}},Gn=class sn extends Ee{index(n="btree"){return new sn(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new sn(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new sn(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new sn(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new sn(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new sn(this.typeBuilder,g(this.columnMetadata,{name:n}))}},Xn=class on extends Ee{index(n="btree"){return new on(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new on(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new on(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new on(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new on(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new on(this.typeBuilder,g(this.columnMetadata,{name:n}))}},Yn=class an extends Ee{index(n="btree"){return new an(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new an(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new an(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new an(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new an(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new an(this.typeBuilder,g(this.columnMetadata,{name:n}))}},Zn=class ln extends Ee{index(n="btree"){return new ln(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new ln(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new ln(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new ln(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new ln(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new ln(this.typeBuilder,g(this.columnMetadata,{name:n}))}},ei=class un extends Ee{index(n="btree"){return new un(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new un(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new un(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new un(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new un(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new un(this.typeBuilder,g(this.columnMetadata,{name:n}))}},ti=class cn extends Ee{index(n="btree"){return new cn(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new cn(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new cn(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new cn(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new cn(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new cn(this.typeBuilder,g(this.columnMetadata,{name:n}))}},ri=class dn extends Ee{index(n="btree"){return new dn(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new dn(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new dn(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new dn(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new dn(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new dn(this.typeBuilder,g(this.columnMetadata,{name:n}))}},ni=class fn extends Ee{index(n="btree"){return new fn(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new fn(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new fn(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new fn(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new fn(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new fn(this.typeBuilder,g(this.columnMetadata,{name:n}))}},ii=class hn extends Ee{index(n="btree"){return new hn(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new hn(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new hn(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new hn(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new hn(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new hn(this.typeBuilder,g(this.columnMetadata,{name:n}))}},si=class pn extends Ee{index(n="btree"){return new pn(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new pn(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new pn(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new pn(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new pn(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new pn(this.typeBuilder,g(this.columnMetadata,{name:n}))}},oi=class gn extends Ee{index(n="btree"){return new gn(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new gn(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new gn(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}autoInc(){return new gn(this.typeBuilder,g(this.columnMetadata,{isAutoIncrement:!0}))}default(n){return new gn(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new gn(this.typeBuilder,g(this.columnMetadata,{name:n}))}},Qf=class mu extends Ee{default(n){return new mu(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new mu(this.typeBuilder,g(this.columnMetadata,{name:n}))}},Jf=class yu extends Ee{default(n){return new yu(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new yu(this.typeBuilder,g(this.columnMetadata,{name:n}))}},_s=class gi extends Ee{index(n="btree"){return new gi(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new gi(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new gi(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}default(n){return new gi(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new gi(this.typeBuilder,g(this.columnMetadata,{name:n}))}},Ss=class mi extends Ee{index(n="btree"){return new mi(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new mi(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new mi(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}default(n){return new mi(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new mi(this.typeBuilder,g(this.columnMetadata,{name:n}))}},Gf=class wu extends Ee{default(n){return new wu(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new wu(this.typeBuilder,g(this.columnMetadata,{name:n}))}},Xf=class vu extends Ee{constructor(n){super(new Te(oe.Array(oe.U8)),n)}default(n){return new vu(g(this.columnMetadata,{defaultValue:n}))}name(n){return new vu(g(this.columnMetadata,{name:n}))}},Yf=class _u extends Ee{default(n){return new _u(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new _u(this.typeBuilder,g(this.columnMetadata,{name:n}))}},By=class Bh extends Ee{constructor(n,s){super(n,s)}default(n){return new Bh(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}},Zf=class Su extends Ee{default(n){return new Su(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new Su(this.typeBuilder,g(this.columnMetadata,{name:n}))}},xu=class Iu extends Ee{default(n){return new Iu(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new Iu(this.typeBuilder,g(this.columnMetadata,{name:n}))}},eh=class ku extends xu{index(n="btree"){return new ku(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}primaryKey(){return new ku(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}},th=class bu extends Ee{default(n){return new bu(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new bu(this.typeBuilder,g(this.columnMetadata,{name:n}))}},ai=class yi extends Ee{index(n="btree"){return new yi(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new yi(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new yi(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}default(n){return new yi(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new yi(this.typeBuilder,g(this.columnMetadata,{name:n}))}},li=class wi extends Ee{index(n="btree"){return new wi(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new wi(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new wi(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}default(n){return new wi(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new wi(this.typeBuilder,g(this.columnMetadata,{name:n}))}},ui=class vi extends Ee{index(n="btree"){return new vi(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new vi(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new vi(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}default(n){return new vi(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new vi(this.typeBuilder,g(this.columnMetadata,{name:n}))}},ci=class _i extends Ee{index(n="btree"){return new _i(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new _i(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new _i(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}default(n){return new _i(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new _i(this.typeBuilder,g(this.columnMetadata,{name:n}))}},di=class Si extends Ee{index(n="btree"){return new Si(this.typeBuilder,g(this.columnMetadata,{indexType:n}))}unique(){return new Si(this.typeBuilder,g(this.columnMetadata,{isUnique:!0}))}primaryKey(){return new Si(this.typeBuilder,g(this.columnMetadata,{isPrimaryKey:!0}))}default(n){return new Si(this.typeBuilder,g(this.columnMetadata,{defaultValue:n}))}name(n){return new Si(this.typeBuilder,g(this.columnMetadata,{name:n}))}},Ay=class extends Te{ref;__spacetimeType;constructor(r){super(oe.Ref(r)),this.ref=r}},My=((r,n)=>{let s=r,a;if(typeof r=="string"){if(!n)throw new TypeError("When providing a name, you must also provide the variants object or array.");s=n,a=r}if(Array.isArray(s)){const c={};for(const f of s)c[f]=new ju;return new Cy(c,a)}return new gu(s,a)}),d={bool:()=>new Iy,string:()=>new ky,number:()=>new Wf,i8:()=>new my,u8:()=>new cy,i16:()=>new yy,u16:()=>new dy,i32:()=>new wy,u32:()=>new fy,i64:()=>new vy,u64:()=>new hy,i128:()=>new _y,u128:()=>new py,i256:()=>new Sy,u256:()=>new gy,f32:()=>new xy,f64:()=>new Wf,object:((r,n)=>{if(typeof r=="string"){if(!n)throw new TypeError("When providing a name, you must also provide the object.");return new ki(n,r)}return new ki(r,void 0)}),row:((r,n)=>{const[s,a]=typeof r=="string"?[n,r]:[r,void 0];return new wn(s,a)}),array(r){return new hu(r)},enum:My,unit(){return new ju},lazy(r){let n=null;const s=()=>n??=r();return new Proxy({},{get(c,f,p){const v=s(),y=Reflect.get(v,f,p);return typeof y=="function"?y.bind(v):y},set(c,f,p,v){return Reflect.set(s(),f,p,v)},has(c,f){return f in s()},ownKeys(){return Reflect.ownKeys(s())},getOwnPropertyDescriptor(c,f){return Object.getOwnPropertyDescriptor(s(),f)},getPrototypeOf(){return Object.getPrototypeOf(s())}})},scheduleAt:()=>new Ty,option(r){return new ca(r)},result(r,n){return new pu(r,n)},identity:()=>new Ey,connectionId:()=>new Uy,timestamp:()=>new Ry,timeDuration:()=>new Ny,uuid:()=>new Py,byteArray:()=>new by},da=d.object("BsatnRowList",{get sizeHint(){return Jy},rowsData:d.byteArray()}),jy=d.object("CallProcedure",{requestId:d.u32(),flags:d.u8(),procedure:d.string(),args:d.byteArray()}),Oy=d.object("CallReducer",{requestId:d.u32(),flags:d.u8(),reducer:d.string(),args:d.byteArray()}),xs=d.enum("ClientMessage",{get Subscribe(){return Yy},get Unsubscribe(){return nw},get OneOffQuery(){return Fy},get CallReducer(){return Oy},get CallProcedure(){return jy}}),Dy=d.object("EventTableRows",{get events(){return da}}),zy=d.object("InitialConnection",{identity:d.identity(),connectionId:d.connectionId(),token:d.string()}),Fy=d.object("OneOffQuery",{requestId:d.u32(),queryString:d.string()}),$y=d.object("OneOffQueryResult",{requestId:d.u32(),get result(){return d.result(Ou,d.string())}}),Ly=d.object("PersistentTableRows",{get inserts(){return da},get deletes(){return da}}),Vy=d.object("ProcedureResult",{get status(){return qy},timestamp:d.timestamp(),totalHostExecutionDuration:d.timeDuration(),requestId:d.u32()}),qy=d.enum("ProcedureStatus",{Returned:d.byteArray(),InternalError:d.string()}),Ou=d.object("QueryRows",{get tables(){return d.array(Xy)}}),Ei=d.object("QuerySetId",{id:d.u32()}),Hy=d.object("QuerySetUpdate",{get querySetId(){return Ei},get tables(){return d.array(tw)}}),Ky=d.object("ReducerOk",{retValue:d.byteArray(),get transactionUpdate(){return Ah}}),Wy=d.enum("ReducerOutcome",{get Ok(){return Ky},OkEmpty:d.unit(),Err:d.byteArray(),InternalError:d.string()}),Qy=d.object("ReducerResult",{requestId:d.u32(),timestamp:d.timestamp(),get result(){return Wy}}),Jy=d.enum("RowSizeHint",{FixedSize:d.u16(),RowOffsets:d.array(d.u64())}),Gy=d.enum("ServerMessage",{get InitialConnection(){return zy},get SubscribeApplied(){return Zy},get UnsubscribeApplied(){return iw},get SubscriptionError(){return ew},get TransactionUpdate(){return Ah},get OneOffQueryResult(){return $y},get ReducerResult(){return Qy},get ProcedureResult(){return Vy}}),Xy=d.object("SingleTableRows",{table:d.string(),get rows(){return da}}),Yy=d.object("Subscribe",{requestId:d.u32(),get querySetId(){return Ei},queryStrings:d.array(d.string())}),Zy=d.object("SubscribeApplied",{requestId:d.u32(),get querySetId(){return Ei},get rows(){return Ou}}),ew=d.object("SubscriptionError",{requestId:d.option(d.u32()),get querySetId(){return Ei},error:d.string()}),tw=d.object("TableUpdate",{tableName:d.string(),get rows(){return d.array(rw)}}),rw=d.enum("TableUpdateRows",{get PersistentTable(){return Ly},get EventTable(){return Dy}}),Ah=d.object("TransactionUpdate",{get querySets(){return d.array(Hy)}}),nw=d.object("Unsubscribe",{requestId:d.u32(),get querySetId(){return Ei},get flags(){return Mh}}),iw=d.object("UnsubscribeApplied",{requestId:d.u32(),get querySetId(){return Ei},get rows(){return d.option(Ou)}}),Mh=d.enum("UnsubscribeFlags",{Default:d.unit(),SendDroppedRows:d.unit()}),Du=class{#e=new Map;on(r,n){let s=this.#e.get(r);s||(s=new Set,this.#e.set(r,s)),s.add(n)}off(r,n){const s=this.#e.get(r);s&&s.delete(n)}emit(r,...n){const s=this.#e.get(r);if(s)for(const a of s)a(...n)}},sw={component:"📦",info:"ℹ️",warn:"⚠️",error:"❌",debug:"🐛",trace:"🔍"},ow={component:"color: #fff; background-color: #8D6FDD; padding: 2px 5px; border-radius: 3px;",info:"color: #fff; background-color: #007bff; padding: 2px 5px; border-radius: 3px;",warn:"color: #fff; background-color: #ffc107; padding: 2px 5px; border-radius: 3px;",error:"color: #fff; background-color: #dc3545; padding: 2px 5px; border-radius: 3px;",debug:"color: #fff; background-color: #28a745; padding: 2px 5px; border-radius: 3px;",trace:"color: #fff; background-color: #17a2b8; padding: 2px 5px; border-radius: 3px;"},aw={component:"color: #8D6FDD;",info:"color: #007bff;",warn:"color: #ffc107;",error:"color: #dc3545;",debug:"color: #28a745;",trace:"color: #17a2b8;"},rh={error:0,warn:1,info:2,debug:3,trace:4},lw="info",uw=r=>rh[r]<=rh[lw],nh=r=>typeof r=="function"?r():r,ih=r=>Array.from(r).map(n=>n.toString(16).padStart(2,"0")).join(""),cw=25,dw=10,fw=new Set(["token","authToken","authorization","accessToken","refreshToken"]),au=r=>Lf(r,(n,s)=>{if(fw.has(n))return"[REDACTED]";if(s&&typeof s=="object"&&"__identity__"in s&&typeof s.__identity__=="bigint")return bh(s.__identity__);if(s&&typeof s=="object"&&"__connection_id__"in s&&typeof s.__connection_id__=="bigint")return Ih(s.__connection_id__);if(s instanceof Uint8Array){if(s.length<25)return`0x${ih(s)}`;const a=s.subarray(0,10);return`Uint8Array(len=${s.length}, head=0x${ih(a)})`}if(Array.isArray(s)&&s.length>=cw){const a=Lf(s.slice(0,dw));return`Array(len=${s.length}, head=${a??"[]"})`}return s}),et=(r,n,...s)=>{if(!uw(r))return;const a=nh(n),c=s.map(nh);console.log(`%c${sw[r]} ${r.toUpperCase()}%c ${a}`,ow[r],aw[r],...c)},sh=(r,n)=>r===n?0:rs.map(y=>v[y]),c=(v,y)=>{const x=a(v),R=Array.isArray(y)?y:[y],N=Math.max(0,R.length-1);for(let q=0;q0||$===0&&Q.tag==="excluded")return!1}return!0}else return!!Is(O,j)},f=r.constraints.some(v=>v.constraint!=="unique"?!1:Is(v.columns,n.columns)),p=this;return f?{find:y=>{const x=Array.isArray(y)?y:[y];for(const R of p.iter())if(Is(a(R),x))return R;return null}}:{*filter(y){for(const x of p.iter())c(x,y)&&(yield x)}}}count(){return BigInt(this.rows.size)}iter(){function*r(n){for(const[s]of n.values())yield s}return r(this.rows)}[Symbol.iterator](){return this.iter()}applyOperations=(r,n)=>{const s=[];if(this.tableDef.isEvent){for(const c of r)c.type==="insert"&&s.push({type:"insert",table:this.tableDef.sourceName,cb:()=>{this.emitter.emit("insert",n,c.row)}});return s}if(Object.values(this.tableDef.columns).some(c=>c.columnMetadata.isPrimaryKey===!0)){const c=new Map,f=new Map;for(const p of r)if(p.type==="insert"){const[v,y]=c.get(p.rowId)||[p,0];c.set(p.rowId,[p,y+1])}else{const[v,y]=f.get(p.rowId)||[p,0];f.set(p.rowId,[p,y+1])}for(const[p,[v,y]]of c){const x=f.get(p);if(x){const[R,N]=x,j=y-N,O=this.update(n,p,v.row,j);O&&s.push(O),f.delete(p)}else{const R=this.insert(n,v,y);R&&s.push(R)}}for(const[p,v]of f.values()){const y=this.delete(n,p,v);y&&s.push(y)}}else for(const c of r)if(c.type==="insert"){const f=this.insert(n,c);f&&s.push(f)}else{const f=this.delete(n,c);f&&s.push(f)}return s};update=(r,n,s,a=0)=>{const c=this.rows.get(n);if(!c){et("error",`Updating a row that was not present in the cache. Table: ${this.tableDef.sourceName}, RowId: ${n}`);return}const[f,p]=c,v=Math.max(1,p+a);if(p+a<=0){et("error",`Negative reference count for in table ${this.tableDef.sourceName} row ${n} (${p} + ${a})`);return}return this.rows.set(n,[s,v]),p===0?(et("error",`Updating a row id in table ${this.tableDef.sourceName} which was not present in the cache (rowId: ${n})`),{type:"insert",table:this.tableDef.sourceName,cb:()=>{this.emitter.emit("insert",r,s)}}):{type:"update",table:this.tableDef.sourceName,cb:()=>{this.emitter.emit("update",r,f,s)}}};insert=(r,n,s=1)=>{const[a,c]=this.rows.get(n.rowId)||[n.row,0];if(this.rows.set(n.rowId,[n.row,c+s]),c===0)return{type:"insert",table:this.tableDef.sourceName,cb:()=>{this.emitter.emit("insert",r,n.row)}}};delete=(r,n,s=1)=>{const[a,c]=this.rows.get(n.rowId)||[n.row,0];if(c===0){et("warn","Deleting a row that was not present in the cache");return}if(c<=s)return this.rows.delete(n.rowId),{type:"delete",table:this.tableDef.sourceName,cb:()=>{this.emitter.emit("delete",r,n.row)}};this.rows.set(n.rowId,[n.row,c-s])};onInsert=r=>{this.emitter.on("insert",r)};onDelete=r=>{this.emitter.on("delete",r)};onUpdate=r=>{this.emitter.on("update",r)};removeOnInsert=r=>{this.emitter.off("insert",r)};removeOnDelete=r=>{this.emitter.off("delete",r)};removeOnUpdate=r=>{this.emitter.off("update",r)}},pw=class{map=new Map;get(r){return this.map.get(r)}set(r,n){return this.map.set(r,n),this}has(r){return this.map.has(r)}delete(r){return this.map.delete(r)}keys(){return this.map.keys()}values(){return this.map.values()}entries(){return this.map.entries()}[Symbol.iterator](){return this.entries()}},gw=class{tables=new pw;getTable(r){const n=this.tables.get(r);if(!n)throw console.error("The table has not been registered for this client. Please register the table before using it. If you have registered global tables using the SpacetimeDBClient.registerTables() or `registerTable()` method, please make sure that is executed first!"),new Error(`Table ${String(r)} does not exist`);return n}getOrCreateTable(r){const n=r.accessorName,s=this.tables.get(n);if(s)return s;const a=new hw(r);return this.tables.set(n,a),a}};function mw(r,n){const s=Math.min(r.length,n.length);for(let a=0;aisNaN(Number(x))?x:Number(x)):null,y=a[5]||null;return new Cu(c,f,p,v,y)}},Oh=new jh(1,4,0);function yw(r){if(r===void 0)throw new Error(oh(r));if(jh.parseVersionString(r).compare(Oh)<0)throw new Error(oh(r))}function oh(r){return`Module code was generated with an incompatible version of the spacetimedb cli (${r}). Update the cli version to at least ${Oh.toString()} and regenerate the bindings. You can upgrade to the latest cli version by running: spacetime version upgrade`}async function ww(r,n,s=128*1024){let a=0;const c=new ReadableStream({pull(O){if(a{const a=await this.#t(new Uint8Array(s.data));n({data:a})}}set onerror(n){this.#e.onerror=n}#e;async#t(n){const s=n[0],a=n.subarray(1);switch(s){case 0:return a;case 1:throw new Error("Brotli Compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");case 2:return await ww(a,"gzip");default:throw new Error("Unexpected Compression Algorithm. Please use `gzip` or `none`")}}send(n){this.#e.send(n)}close(){this.#e.close()}constructor(n){n.binaryType="arraybuffer",this.#e=n}static async createWebSocketFn({url:n,nameOrAddress:s,wsProtocol:a,authToken:c,compression:f,lightMode:p,confirmedReads:v}){const y=new Headers,x=await vw();let R;if(c){y.set("Authorization",`Bearer ${c}`);const O=new URL("v1/identity/websocket-token",n);O.protocol=n.protocol==="wss:"?"https:":"http:";const q=await fetch(O,{method:"POST",headers:y});if(q.ok){const{token:Q}=await q.json();R=Q}else return Promise.reject(new Error(`Failed to verify token: ${q.statusText}`))}const N=new URL(`v1/database/${s}/subscribe`,n);R&&N.searchParams.set("token",R),N.searchParams.set("compression",f==="gzip"?"Gzip":"None"),p&&N.searchParams.set("light","true"),v!==void 0&&N.searchParams.set("confirmed",v.toString());const j=new x(N.toString(),a);return new Dh(j)}},Sw=class{constructor(n,s){this.remoteModule=n,this.dbConnectionCtor=s,this.#o=_w.createWebSocketFn}#e;#t;#n;#r;#i=new Du;#a="gzip";#s=!1;#l;#o;withUri(n){return this.#e=new URL(n),this}withDatabaseName(n){return this.#t=n,this}withToken(n){return this.#r=n,this}withWSFn(n){return this.#o=n,this}withCompression(n){return this.#a=n,this}withLightMode(n){return this.#s=n,this}withConfirmedReads(n){return this.#l=n,this}onConnect(n){return this.#i.on("connect",n),this}onConnectError(n){return this.#i.on("connectError",n),this}onDisconnect(n){return this.#i.on("disconnect",n),this}getUri(){return this.#e?.toString()??""}getModuleName(){return this.#t??""}build(){if(!this.#e)throw new Error("URI is required to connect to SpacetimeDB");if(!this.#t)throw new Error("Database name or address is required to connect to SpacetimeDB");return yw(this.remoteModule.versionInfo?.cliVersion),this.dbConnectionCtor({uri:this.#e,nameOrAddress:this.#t,identity:this.#n,token:this.#r,emitter:this.#i,compression:this.#a,lightMode:this.#s,confirmedReads:this.#l,createWSFn:this.#o,remoteModule:this.remoteModule})}},zh=Symbol("INTERNAL_REMOTE_MODULE"),Fh=class{constructor(r){this.db=r}#e=void 0;#t=void 0;onApplied(r){return this.#e=r,this}onError(r){return this.#t=r,this}subscribe(r){let n;if(typeof r=="function"){const a=this.db.getTablesMap?.(),c=r(a);n=Array.isArray(c)?c:[c]}else n=Array.isArray(r)?r:[r];if(n.length===0)throw new Error("Subscriptions must have at least one query");const s=n.map(a=>{if(typeof a=="string")return a;if(Zm(a))return ey(a);throw new Error("Subscriptions must be SQL strings or typed queries")});return new Iw(this.db,s,this.#e,this.#t)}subscribeToAllTables(){const r=this.db[zh](),n=Object.values(r.tables).map(s=>`SELECT * FROM ${s.sourceName}`);this.subscribe(n)}},xw=class{subscriptions=new Map},Iw=class{constructor(r,n,s,a){this.db=r,this.#i.on("applied",c=>{this.#r=!0,s&&s(c)}),this.#i.on("error",(c,f)=>{this.#r=!1,this.#n=!0,a&&a(c,f)}),this.#e=this.db.registerSubscription(this,this.#i,n)}#e;#t=!1;#n=!1;#r=!1;#i=new Du;unsubscribe(){if(this.#t)throw new Error("Unsubscribe has already been called");this.#t=!0,this.db.unregisterSubscription(this.#e),this.#i.on("end",r=>{this.#n=!0,this.#r=!1})}unsubscribeThen(r){if(this.#n)throw new Error("Subscription has already ended");if(this.#t)throw new Error("Unsubscribe has already been called");this.#t=!0,this.db.unregisterSubscription(this.#e),this.#i.on("end",n=>{this.#n=!0,this.#r=!1,r(n)})}isEnded(){return this.#n}isActive(){return this.#r}},kw=class{isActive=!1;identity=void 0;token=void 0;[zh](){return this.#l}db;reducers;procedures;connectionId=ga.random();#e=0;#t=0;#n=0;#r;#i=Promise.resolve();#a=[];#s=new xw;#l;#o=new Map;#y=new Map;#w=new Map;#v;#f;#h;#u;clientCache;ws;wsPromise;constructor({uri:r,nameOrAddress:n,identity:s,token:a,emitter:c,remoteModule:f,createWSFn:p,compression:v,lightMode:y,confirmedReads:x}){et("info","Connecting to SpacetimeDB WS...");const R=new URL(r.toString());/^wss?:/.test(r.protocol)||(R.protocol=R.protocol==="https:"?"wss:":"ws:"),this.identity=s,this.token=a,this.#l=f,this.#r=c,this.#v=Object.create(null),this.#u=Object.create(null);for(const j of Object.values(f.tables))this.#v[j.sourceName]=pr.makeDeserializer(j.rowType),this.#u[j.sourceName]=j;this.#f=Object.create(null);for(const j of f.reducers)this.#f[j.name]={serialize:pr.makeSerializer(j.paramsType),deserialize:pr.makeDeserializer(j.paramsType)};this.#h=Object.create(null);for(const j of f.procedures)this.#h[j.name]={serializeArgs:pr.makeSerializer(new ki(j.params).algebraicType.value),deserializeReturn:oe.makeDeserializer(j.returnType.algebraicType)};const N=this.connectionId.toHexString();R.searchParams.set("connection_id",N),this.clientCache=new gw,this.db=this.#C(),this.reducers=this.#T(f),this.procedures=this.#E(f),this.wsPromise=p({url:R,nameOrAddress:n,wsProtocol:"v2.bsatn.spacetimedb",authToken:a,compression:v,lightMode:y,confirmedReads:x}).then(j=>(this.ws=j,this.ws.onclose=()=>{this.#r.emit("disconnect",this),this.isActive=!1},this.ws.onerror=O=>{this.#r.emit("connectError",this,O),this.isActive=!1},this.ws.onopen=this.#P.bind(this),this.ws.onmessage=this.#A.bind(this),j)).catch(j=>{et("error","Error connecting to SpacetimeDB WS"),this.#r.emit("connectError",this,j)})}#b=()=>{const r=this.#e;return this.#e+=1,r};#p=()=>this.#t++;#C(){const r=Object.create(null);for(const n of Object.values(this.#u)){const s=n.accessorName;Object.defineProperty(r,s,{enumerable:!0,configurable:!1,get:()=>this.clientCache.getOrCreateTable(n)})}return r}#T(r){const n={},s=new Pe(1024);for(const a of r.reducers){const c=a.name,f=a.accessorName,{serialize:p}=this.#f[c];n[f]=v=>{s.clear(),p(s,v);const y=s.getBuffer();return this.callReducer(c,y,v)}}return n}#E(r){const n={},s=new Pe(1024);for(const a of r.procedures){const c=a.name,f=a.accessorName,{serializeArgs:p,deserializeReturn:v}=this.#h[c];n[f]=y=>{s.clear(),p(s,y);const x=s.getBuffer();return this.callProcedure(c,x).then(R=>v(new ze(R)))}}return n}#c(r){return{db:this.db,reducers:this.reducers,isActive:this.isActive,subscriptionBuilder:this.subscriptionBuilder.bind(this),disconnect:this.disconnect.bind(this),event:r}}subscriptionBuilder=()=>new Fh(this);getTablesMap(){return Nh({tables:this.#l.tables})}registerSubscription(r,n,s){const a=this.#b();this.#s.subscriptions.set(a,{handle:r,emitter:n});const c=this.#p();return this.#m(xs.Subscribe({queryStrings:s,querySetId:{id:a},requestId:c})),a}unregisterSubscription(r){const n=this.#p();this.#m(xs.Unsubscribe({querySetId:{id:r},requestId:n,flags:Mh.SendDroppedRows}))}#g(r,n,s){const a=s.rowsData,c=new ze(a),f=[],p=this.#v[n],v=this.#u[n],x=Object.entries(v.columns).find(N=>N[1].columnMetadata.isPrimaryKey);let R=0;for(;c.remaining>0;){const N=p(c);let j;if(x!==void 0){const O=x[0],q=x[1].typeBuilder.algebraicType;j=oe.intoMapKey(q,N[O])}else{const O=a.subarray(R,c.offset);j=Mu.fromByteArray(O)}R=c.offset,f.push({type:r,rowId:j,row:N})}return f}#_(r){const n=new Map;for(const s of r){const a=n.get(s.tableName);if(a)for(const c of s.operations)a.push(c);else n.set(s.tableName,s.operations.slice())}return Array.from(n,([s,a])=>({tableName:s,operations:a}))}#x(r,n){const s=[];for(const a of r.tables)s.push({tableName:a.table,operations:this.#g(n,a.table,a.rows)});return this.#_(s)}#U(r,n){if(n.tag==="PersistentTable"){const s=this.#g("insert",r,n.value.inserts),a=this.#g("delete",r,n.value.deletes);return s.concat(a)}return n.tag==="EventTable"?this.#g("insert",r,n.value.events):[]}#R(r){const n=[];for(const s of r.tables){let a=[];for(const c of s.rows)a=a.concat(this.#U(s.tableName,c));n.push({tableName:s.tableName,operations:a})}return this.#_(n)}#I(r){const n=this.#a.splice(0);for(const s of n)r.send(s)}#N=new Pe(1024);#m(r){const n=this.#N;n.clear(),xs.serialize(n,r);const s=n.getBuffer();this.ws&&this.isActive?(this.#a.length&&this.#I(this.ws),et("trace",()=>`Sending message to server: ${au(r)}`),this.ws.send(s)):(et("trace",()=>`Queuing message to server: ${au(r)}`),this.#a.push(s.slice()))}#d(){return this.#n+=1,`${this.connectionId.toHexString()}:${this.#n}`}#P(){this.isActive=!0,this.ws&&this.#I(this.ws)}#S(r,n){const s=[];for(const a of r){const c=a.tableName,f=this.#u[c],v=this.clientCache.getOrCreateTable(f).applyOperations(a.operations,n);for(const y of v)s.push(y)}return s}#k(r,n){const s=[];for(const a of n.querySets){const c=this.#R(a);for(const f of c)s.push(f)}return this.#S(this.#_(s),r)}async#B(r){const n=Gy.deserialize(new ze(r));switch(et("trace",()=>`Processing server message: ${au(n)}`),n.tag){case"InitialConnection":{this.identity=n.value.identity,!this.token&&n.value.token&&(this.token=n.value.token),this.connectionId=n.value.connectionId,this.#r.emit("connect",this,this.identity,this.token);break}case"SubscribeApplied":{const s=n.value.querySetId.id,a=this.#s.subscriptions.get(s);if(!a){et("error",`Received SubscribeApplied for unknown querySetId ${s}.`);return}const c={id:this.#d(),tag:"SubscribeApplied"},f=this.#c(c),p=this.#x(n.value.rows,"insert"),v=this.#S(p,f),{event:y,...x}=f;a.emitter.emit("applied",x),et("trace",()=>`Calling ${v.length} triggered row callbacks`);for(const R of v)R.cb();break}case"UnsubscribeApplied":{const s=n.value.querySetId.id,a=this.#s.subscriptions.get(s);if(!a){et("error",`Received UnsubscribeApplied for unknown querySetId ${s}.`);return}const c={id:this.#d(),tag:"UnsubscribeApplied"},f=this.#c(c),p=n.value.rows?this.#x(n.value.rows,"delete"):[],v=this.#S(p,f),{event:y,...x}=f;a.emitter.emit("end",x),this.#s.subscriptions.delete(s),et("trace",()=>`Calling ${v.length} triggered row callbacks`);for(const R of v)R.cb();break}case"SubscriptionError":{const s=n.value.querySetId.id,a=n.value.requestId,c=Error(n.value.error),f={id:this.#d(),tag:"Error",value:c},v={...this.#c(f),event:c};if(a==null){et("error",`Disconnecting due to error for a previously applied subscription: ${n.value.error}`),this.disconnect();break}const y=this.#s.subscriptions.get(s);y?(y.emitter.emit("error",v,c),this.#s.subscriptions.delete(s)):et("error",`Received SubscriptionError for unknown querySetId ${s}:`,c);break}case"TransactionUpdate":{const s={id:this.#d(),tag:"Transaction"},a=this.#c(s),c=this.#k(a,n.value);et("trace",()=>`Calling ${c.length} triggered row callbacks`);for(const f of c)f.cb();break}case"ReducerResult":{const{requestId:s,result:a}=n.value;if(a.tag==="Ok"){const f=this.#y.get(s),p=this.#d(),v=f?{id:p,tag:"Reducer",value:{timestamp:n.value.timestamp,outcome:a,reducer:{name:f.name,args:f.args}}}:{id:p,tag:"Transaction"},y=this.#c(v),x=this.#k(y,a.value.transactionUpdate);et("trace",()=>`Calling ${x.length} triggered row callbacks`);for(const R of x)R.cb()}this.#y.delete(s);const c=this.#o.get(s);this.#o.delete(s),c?.(a);break}case"ProcedureResult":{const{status:s,requestId:a}=n.value,c=s.tag==="Returned"?{tag:"Ok",value:s.value}:{tag:"Err",value:s.value},f=this.#w.get(a);this.#w.delete(a),f?.(c);break}case"OneOffQueryResult":{et("warn","Received OneOffQueryResult but SDK does not expose one-off query APIs yet.");break}}}#A(r){this.#i=this.#i.then(()=>this.#B(r.data))}callReducer(r,n,s){const{promise:a,resolve:c,reject:f}=Promise.withResolvers(),p=this.#p(),v=xs.CallReducer({reducer:r,args:n,requestId:p,flags:0});return this.#m(v),s&&this.#y.set(p,{name:r,args:s}),this.#o.set(p,y=>{if(y.tag==="Ok"||y.tag==="OkEmpty")c();else if(y.tag==="Err"){const R=new ze(y.value).readString();f(new Km(R))}else y.tag==="InternalError"?f(new Wm(y.value)):f(new Error("Unexpected reducer result"))}),a}callReducerWithParams(r,n,s){const a=new Pe(1024);this.#f[r].serialize(a,s);const c=a.getBuffer();return this.callReducer(r,c,s)}callProcedure(r,n){const{promise:s,resolve:a,reject:c}=Promise.withResolvers(),f=this.#p(),p=xs.CallProcedure({procedure:r,args:n,requestId:f,flags:0});return this.#m(p),this.#w.set(f,v=>{v.tag==="Ok"?a(v.value):c(v.value)}),s}callProcedureWithParams(r,n,s,a){const c=new Pe(1024),{serializeArgs:f,deserializeReturn:p}=this.#h[r];f(c,s);const v=c.getBuffer();return this.callProcedure(r,v).then(y=>p(new ze(y)))}disconnect(){this.wsPromise.then(r=>r?.close())}on(r,n){this.#r.on(r,n)}off(r,n){this.#r.off(r,n)}onConnect(r){this.#r.on("connect",r)}onDisconnect(r){this.#r.on("disconnect",r)}onConnectError(r){this.#r.on("connectError",r)}removeOnConnect(r){this.#r.off("connect",r)}removeOnDisconnect(r){this.#r.off("disconnect",r)}removeOnConnectError(r){this.#r.off("connectError",r)}};function bw(r,n){const s=Object.create(null);for(const[a,c]of Object.entries(n))s[a]=Cw(a,c,c.tableDef(r,a));return{tables:s}}function Cw(r,n,s){const a=f=>n.rowType.algebraicType.value.elements[f].name,c=s.indexes.map(f=>{const p=f.accessorName;if(typeof p!="string"||p.length===0)throw new TypeError(`Index '${f.sourceName??""}' on table '${s.sourceName}' is missing accessor name`);const v=f.algorithm.tag==="Direct"?[f.algorithm.value]:f.algorithm.value,y=s.constraints.some(R=>R.data.tag==="Unique"&&R.data.value.columns.every(N=>v.includes(N))),x={BTree:"btree",Hash:"hash",Direct:"direct"}[f.algorithm.tag];return{name:p,unique:y,algorithm:x,columns:v.map(a)}});return{sourceName:n.tableName||r,accessorName:r,columns:n.rowType.row,rowType:n.rowSpacetimeType,indexes:n.idxs,constraints:s.constraints.map(f=>({name:f.sourceName,constraint:"unique",columns:f.data.value.columns.map(a)})),resolvedIndexes:c,tableDef:s,...s.isEvent?{isEvent:!0}:{}}}var Tw=class{#e=new Map;#t={typespace:{types:[]},tables:[],reducers:[],types:[],rowLevelSecurity:[],schedules:[],procedures:[],views:[],lifeCycleReducers:[],caseConversionPolicy:{tag:"SnakeCase"},explicitNames:{entries:[]}};get moduleDef(){return this.#t}rawModuleDefV10(){const r=[],n=a=>{a&&r.push(a)},s=this.#t;return n(s.typespace&&{tag:"Typespace",value:s.typespace}),n(s.types&&{tag:"Types",value:s.types}),n(s.tables&&{tag:"Tables",value:s.tables}),n(s.reducers&&{tag:"Reducers",value:s.reducers}),n(s.procedures&&{tag:"Procedures",value:s.procedures}),n(s.views&&{tag:"Views",value:s.views}),n(s.schedules&&{tag:"Schedules",value:s.schedules}),n(s.lifeCycleReducers&&{tag:"LifeCycleReducers",value:s.lifeCycleReducers}),n(s.rowLevelSecurity&&{tag:"RowLevelSecurity",value:s.rowLevelSecurity}),n(s.explicitNames&&{tag:"ExplicitNames",value:s.explicitNames}),n(s.caseConversionPolicy&&{tag:"CaseConversionPolicy",value:s.caseConversionPolicy}),{sections:r}}setCaseConversionPolicy(r){this.#t.caseConversionPolicy=r}get typespace(){return this.#t.typespace}resolveType(r){let n=r.algebraicType;for(;n.tag==="Ref";)n=this.typespace.types[n.value];return n}registerTypesRecursively(r){return r instanceof ki&&!Ew(r)||r instanceof gu||r instanceof wn?this.#n(r):r instanceof ca?new ca(this.registerTypesRecursively(r.value)):r instanceof pu?new pu(this.registerTypesRecursively(r.ok),this.registerTypesRecursively(r.err)):r instanceof hu?new hu(this.registerTypesRecursively(r.element)):r}#n(r){const n=r.algebraicType,s=r.typeName;if(s===void 0)throw new Error(`Missing type name for ${r.constructor.name??"TypeBuilder"} ${JSON.stringify(r)}`);let a=this.#e.get(n);if(a!=null)return a;const c=r instanceof wn||r instanceof ki?{tag:"Product",value:{elements:[]}}:{tag:"Sum",value:{variants:[]}};if(a=new Ay(this.#t.typespace.types.length),this.#t.typespace.types.push(c),this.#e.set(n,a),r instanceof wn)for(const[f,p]of Object.entries(r.row))c.value.elements.push({name:f,algebraicType:this.registerTypesRecursively(p.typeBuilder).algebraicType});else if(r instanceof ki)for(const[f,p]of Object.entries(r.elements))c.value.elements.push({name:f,algebraicType:this.registerTypesRecursively(p).algebraicType});else if(r instanceof gu)for(const[f,p]of Object.entries(r.variants))c.value.variants.push({name:f,algebraicType:this.registerTypesRecursively(p).algebraicType});return this.#t.types.push({sourceName:Uw(s),ty:a.ref,customOrdering:!0}),a}};function Ew(r){return r.typeName==null&&r.algebraicType.value.elements.length===0}function Uw(r){const n=r.split(".");return{sourceName:n.pop(),scope:n}}var Rw=class{constructor(r){this.schemaType=r}};function Nw(r){const n=new Tw;return new Rw(bw(n,r))}function Pw(r){return Object.fromEntries(r.map(n=>[n.accessorName,n]))}var Wt=d.enum("AlgebraicType",{Ref:d.u32(),get Sum(){return _v},get Product(){return _n},get Array(){return Wt},String:d.unit(),Bool:d.unit(),I8:d.unit(),U8:d.unit(),I16:d.unit(),U16:d.unit(),I32:d.unit(),U32:d.unit(),I64:d.unit(),U64:d.unit(),I128:d.unit(),U128:d.unit(),I256:d.unit(),U256:d.unit(),F32:d.unit(),F64:d.unit()}),Bw=d.enum("CaseConversionPolicy",{None:d.unit(),SnakeCase:d.unit()}),$h=d.enum("ExplicitNameEntry",{get Table(){return lu},get Function(){return lu},get Index(){return lu}}),Aw=d.object("ExplicitNames",{get entries(){return d.array($h)}}),Lh=d.enum("FunctionVisibility",{Private:d.unit(),ClientCallable:d.unit()}),Mw=d.object("HttpHeaderPair",{name:d.string(),value:d.byteArray()}),Vh=d.object("HttpHeaders",{get entries(){return d.array(Mw)}}),jw=d.enum("HttpMethod",{Get:d.unit(),Head:d.unit(),Post:d.unit(),Put:d.unit(),Delete:d.unit(),Connect:d.unit(),Options:d.unit(),Trace:d.unit(),Patch:d.unit(),Extension:d.string()});d.object("HttpRequest",{get method(){return jw},get headers(){return Vh},timeout:d.option(d.timeDuration()),uri:d.string(),get version(){return qh}});d.object("HttpResponse",{get headers(){return Vh},get version(){return qh},code:d.u16()});var qh=d.enum("HttpVersion",{Http09:d.unit(),Http10:d.unit(),Http11:d.unit(),Http2:d.unit(),Http3:d.unit()}),Ow=d.enum("IndexType",{BTree:d.unit(),Hash:d.unit()}),Hh=d.enum("Lifecycle",{Init:d.unit(),OnConnect:d.unit(),OnDisconnect:d.unit()}),Dw=d.enum("MiscModuleExport",{get TypeAlias(){return Iv}}),lu=d.object("NameMapping",{sourceName:d.string(),canonicalName:d.string()}),_n=d.object("ProductType",{get elements(){return d.array(Kh)}}),Kh=d.object("ProductTypeElement",{name:d.option(d.string()),get algebraicType(){return Wt}}),zw=d.object("RawColumnDefV8",{colName:d.string(),get colType(){return Wt}}),Fw=d.object("RawColumnDefaultValueV10",{colId:d.u16(),value:d.byteArray()}),$w=d.object("RawColumnDefaultValueV9",{table:d.string(),colId:d.u16(),value:d.byteArray()}),Wh=d.enum("RawConstraintDataV9",{get Unique(){return mv}}),Lw=d.object("RawConstraintDefV10",{sourceName:d.option(d.string()),get data(){return Wh}}),Vw=d.object("RawConstraintDefV8",{constraintName:d.string(),constraints:d.u8(),columns:d.array(d.u16())}),qw=d.object("RawConstraintDefV9",{name:d.option(d.string()),get data(){return Wh}}),Es=d.enum("RawIndexAlgorithm",{BTree:d.array(d.u16()),Hash:d.array(d.u16()),Direct:d.u16()}),Hw=d.object("RawIndexDefV10",{sourceName:d.option(d.string()),accessorName:d.option(d.string()),get algorithm(){return Es}}),Kw=d.object("RawIndexDefV8",{indexName:d.string(),isUnique:d.bool(),get indexType(){return Ow},columns:d.array(d.u16())}),Ww=d.object("RawIndexDefV9",{name:d.option(d.string()),accessorName:d.option(d.string()),get algorithm(){return Es}}),Qw=d.object("RawLifeCycleReducerDefV10",{get lifecycleSpec(){return Hh},functionName:d.string()}),Jw=d.enum("RawMiscModuleExportV9",{get ColumnDefaultValue(){return $w},get Procedure(){return tv},get View(){return wv}});d.enum("RawModuleDef",{get V8BackCompat(){return Yw},get V9(){return Zw},get V10(){return Gw}});var Gw=d.object("RawModuleDefV10",{get sections(){return d.array(Xw)}}),Xw=d.enum("RawModuleDefV10Section",{get Typespace(){return zu},get Types(){return d.array(pv)},get Tables(){return d.array(dv)},get Reducers(){return d.array(rv)},get Procedures(){return d.array(ev)},get Views(){return d.array(yv)},get Schedules(){return d.array(iv)},get LifeCycleReducers(){return d.array(Qw)},get RowLevelSecurity(){return d.array(Qh)},get CaseConversionPolicy(){return Bw},get ExplicitNames(){return Aw}}),Yw=d.object("RawModuleDefV8",{get typespace(){return zu},get tables(){return d.array(xv)},get reducers(){return d.array(vv)},get miscExports(){return d.array(Dw)}}),Zw=d.object("RawModuleDefV9",{get typespace(){return zu},get tables(){return d.array(hv)},get reducers(){return d.array(nv)},get types(){return d.array(gv)},get miscExports(){return d.array(Jw)},get rowLevelSecurity(){return d.array(Qh)}}),ev=d.object("RawProcedureDefV10",{sourceName:d.string(),get params(){return _n},get returnType(){return Wt},get visibility(){return Lh}}),tv=d.object("RawProcedureDefV9",{name:d.string(),get params(){return _n},get returnType(){return Wt}}),rv=d.object("RawReducerDefV10",{sourceName:d.string(),get params(){return _n},get visibility(){return Lh},get okReturnType(){return Wt},get errReturnType(){return Wt}}),nv=d.object("RawReducerDefV9",{name:d.string(),get params(){return _n},get lifecycle(){return d.option(Hh)}}),Qh=d.object("RawRowLevelSecurityDefV9",{sql:d.string()}),iv=d.object("RawScheduleDefV10",{sourceName:d.option(d.string()),tableName:d.string(),scheduleAtCol:d.u16(),functionName:d.string()}),sv=d.object("RawScheduleDefV9",{name:d.option(d.string()),reducerName:d.string(),scheduledAtColumn:d.u16()}),ov=d.object("RawScopedTypeNameV10",{scope:d.array(d.string()),sourceName:d.string()}),av=d.object("RawScopedTypeNameV9",{scope:d.array(d.string()),name:d.string()}),lv=d.object("RawSequenceDefV10",{sourceName:d.option(d.string()),column:d.u16(),start:d.option(d.i128()),minValue:d.option(d.i128()),maxValue:d.option(d.i128()),increment:d.i128()}),uv=d.object("RawSequenceDefV8",{sequenceName:d.string(),colPos:d.u16(),increment:d.i128(),start:d.option(d.i128()),minValue:d.option(d.i128()),maxValue:d.option(d.i128()),allocated:d.i128()}),cv=d.object("RawSequenceDefV9",{name:d.option(d.string()),column:d.u16(),start:d.option(d.i128()),minValue:d.option(d.i128()),maxValue:d.option(d.i128()),increment:d.i128()}),dv=d.object("RawTableDefV10",{sourceName:d.string(),productTypeRef:d.u32(),primaryKey:d.array(d.u16()),get indexes(){return d.array(Hw)},get constraints(){return d.array(Lw)},get sequences(){return d.array(lv)},get tableType(){return Gh},get tableAccess(){return Jh},get defaultValues(){return d.array(Fw)},isEvent:d.bool()}),fv=d.object("RawTableDefV8",{tableName:d.string(),get columns(){return d.array(zw)},get indexes(){return d.array(Kw)},get constraints(){return d.array(Vw)},get sequences(){return d.array(uv)},tableType:d.string(),tableAccess:d.string(),scheduled:d.option(d.string())}),hv=d.object("RawTableDefV9",{name:d.string(),productTypeRef:d.u32(),primaryKey:d.array(d.u16()),get indexes(){return d.array(Ww)},get constraints(){return d.array(qw)},get sequences(){return d.array(cv)},get schedule(){return d.option(sv)},get tableType(){return Gh},get tableAccess(){return Jh}}),pv=d.object("RawTypeDefV10",{get sourceName(){return ov},ty:d.u32(),customOrdering:d.bool()}),gv=d.object("RawTypeDefV9",{get name(){return av},ty:d.u32(),customOrdering:d.bool()}),mv=d.object("RawUniqueConstraintDataV9",{columns:d.array(d.u16())}),yv=d.object("RawViewDefV10",{sourceName:d.string(),index:d.u32(),isPublic:d.bool(),isAnonymous:d.bool(),get params(){return _n},get returnType(){return Wt}}),wv=d.object("RawViewDefV9",{name:d.string(),index:d.u32(),isPublic:d.bool(),isAnonymous:d.bool(),get params(){return _n},get returnType(){return Wt}}),vv=d.object("ReducerDef",{name:d.string(),get args(){return d.array(Kh)}}),_v=d.object("SumType",{get variants(){return d.array(Sv)}}),Sv=d.object("SumTypeVariant",{name:d.option(d.string()),get algebraicType(){return Wt}}),Jh=d.enum("TableAccess",{Public:d.unit(),Private:d.unit()}),xv=d.object("TableDesc",{get schema(){return fv},data:d.u32()}),Gh=d.enum("TableType",{System:d.unit(),User:d.unit()}),Iv=d.object("TypeAlias",{name:d.string(),ty:d.u32()}),zu=d.object("Typespace",{get types(){return d.array(Wt)}});d.enum("ViewResultHeader",{RowData:d.unit(),RawSql:d.string()});function dr(r,n,...s){const{name:a,public:c=!1,indexes:f=[],scheduled:p,event:v=!1}=r,y=new Map,x=[];n instanceof wn||(n=new wn(n)),n.algebraicType.value.elements.forEach((T,A)=>{y.set(T.name,A),x.push(T.name)});const R=[],N=[],j=[],O=[];let q;const Q=[];for(const[T,A]of Object.entries(n.row)){const L=A.columnMetadata;L.isPrimaryKey&&R.push(y.get(T));const J=L.isUnique||L.isPrimaryKey;if(L.indexType||J){const Y=L.indexType??"btree",ge=y.get(T);let me;switch(Y){case"btree":me=Es.BTree([ge]);break;case"hash":me=Es.Hash([ge]);break;case"direct":me=Es.Direct(ge);break}N.push({sourceName:void 0,accessorName:T,algorithm:me})}if(J&&j.push({sourceName:void 0,data:{tag:"Unique",value:{columns:[y.get(T)]}}}),L.isAutoIncrement&&O.push({sourceName:void 0,start:void 0,minValue:void 0,maxValue:void 0,column:y.get(T),increment:1n}),L.defaultValue){const Y=new Pe(16);A.serialize(Y,L.defaultValue),Q.push({colId:y.get(T),value:Y.getBuffer()})}if(p){const Y=A.typeBuilder.algebraicType;Uh.isScheduleAt(Y)&&(q=y.get(T))}}for(const T of f??[]){const A=T.accessor;if(typeof A!="string"||A.length===0){const J=a??"",Y=T.name??"";throw new TypeError(`Index '${Y}' on table '${J}' must define a non-empty 'accessor'`)}let L;switch(T.algorithm){case"btree":L={tag:"BTree",value:T.columns.map(J=>y.get(J))};break;case"hash":L={tag:"Hash",value:T.columns.map(J=>y.get(J))};break;case"direct":L={tag:"Direct",value:y.get(T.column)};break}N.push({sourceName:void 0,accessorName:A,algorithm:L,canonicalName:T.name})}for(const T of r.constraints??[])if(T.constraint==="unique"){const A={tag:"Unique",value:{columns:T.columns.map(L=>y.get(L))}};j.push({sourceName:T.name,data:A});continue}const $=n.algebraicType.value;return{rowType:n,tableName:a,rowSpacetimeType:$,tableDef:(T,A)=>{const L=a??A;n.typeName===void 0&&(n.typeName=Fm(L));for(const J of N){const ge=(J.algorithm.tag==="Direct"?[J.algorithm.value]:J.algorithm.value).map(Re=>x[Re]).join("_"),me=J.sourceName=`${A}_${ge}_idx_${J.algorithm.tag.toLowerCase()}`,{canonicalName:ue}=J;ue!==void 0&&T.moduleDef.explicitNames.entries.push($h.Index({sourceName:me,canonicalName:ue}))}return{sourceName:A,productTypeRef:T.registerTypesRecursively(n).ref,primaryKey:R,indexes:N,constraints:j,sequences:O,tableType:{tag:"User"},tableAccess:{tag:c?"Public":"Private"},defaultValues:Q,isEvent:v}},idxs:f,constraints:j,schedule:p&&q!==void 0?{scheduleAtCol:q,reducer:p}:void 0}}var kv=class{reducersType;constructor(r){this.reducersType=bv(r)}};function bv(r){return{reducers:r.map(a=>{const c=a.params.row;return{name:a.reducerName,accessorName:a.accessorName,params:c,paramsType:a.paramsSpacetimeType}})}}function Cv(...r){const n=r.length===1&&Array.isArray(r[0])?r[0]:r;return new kv(n)}function jt(r,n){const s={elements:Object.entries(n).map(([a,c])=>({name:a,algebraicType:"typeBuilder"in c?c.typeBuilder.algebraicType:c.algebraicType}))};return{reducerName:r,accessorName:Ch(r),params:new wn(n),paramsSpacetimeType:s,reducerDef:{name:r,params:s,lifecycle:void 0}}}function Tv(...r){return{procedures:r.length===1&&Array.isArray(r[0])?r[0]:r}}const Ev={name:d.string(),serverId:d.u64(),isVoice:d.bool()},Uv={name:d.string()},Rv={name:d.string(),channelId:d.u64(),parentMessageId:d.u64()},Nv={channelId:d.u64()},Pv={},Bv={username:d.string(),password:d.string()},Av={username:d.string(),password:d.string()},Mv={receiver:d.identity(),candidate:d.string(),channelId:d.u64()},jv={text:d.string(),channelId:d.u64(),threadId:d.option(d.u64())},Ov={receiver:d.identity(),sdp:d.string(),channelId:d.u64()},Dv={receiver:d.identity(),sdp:d.string(),channelId:d.u64()},zv={name:d.string()};d.object("Channel",{id:d.u64(),serverId:d.u64(),name:d.string(),get kind(){return Xh}});const Xh=d.enum("ChannelKind",{Text:d.unit(),Voice:d.unit()});d.object("IceCandidate",{sender:d.identity(),receiver:d.identity(),candidate:d.string(),channelId:d.u64()});d.object("Message",{id:d.u64(),sender:d.identity(),sent:d.timestamp(),text:d.string(),channelId:d.u64(),threadId:d.option(d.u64())});d.object("SdpAnswer",{sender:d.identity(),receiver:d.identity(),sdp:d.string(),channelId:d.u64()});d.object("SdpOffer",{sender:d.identity(),receiver:d.identity(),sdp:d.string(),channelId:d.u64()});d.object("Server",{id:d.u64(),name:d.string(),owner:d.option(d.identity())});d.object("Thread",{id:d.u64(),channelId:d.u64(),parentMessageId:d.u64(),name:d.string()});d.object("User",{identity:d.identity(),name:d.option(d.string()),online:d.bool(),issuer:d.option(d.string()),subject:d.option(d.string()),username:d.option(d.string()),password:d.option(d.string())});d.object("VoiceState",{identity:d.identity(),channelId:d.u64()});const Fv=d.row({id:d.u64().primaryKey(),serverId:d.u64().name("server_id"),name:d.string(),get kind(){return Xh}}),$v=d.row({sender:d.identity(),receiver:d.identity(),candidate:d.string(),channelId:d.u64().name("channel_id")}),Lv=d.row({id:d.u64().primaryKey(),sender:d.identity(),sent:d.timestamp(),text:d.string(),channelId:d.u64().name("channel_id"),threadId:d.option(d.u64()).name("thread_id")}),Vv=d.row({sender:d.identity(),receiver:d.identity(),sdp:d.string(),channelId:d.u64().name("channel_id")}),qv=d.row({sender:d.identity(),receiver:d.identity(),sdp:d.string(),channelId:d.u64().name("channel_id")}),Hv=d.row({id:d.u64().primaryKey(),name:d.string(),owner:d.option(d.identity())}),Kv=d.row({id:d.u64().primaryKey(),channelId:d.u64().name("channel_id"),parentMessageId:d.u64().name("parent_message_id"),name:d.string()}),Wv=d.row({identity:d.identity().primaryKey(),name:d.option(d.string()),online:d.bool(),issuer:d.option(d.string()),subject:d.option(d.string()),username:d.option(d.string()),password:d.option(d.string())}),Qv=d.row({identity:d.identity().primaryKey(),channelId:d.u64().name("channel_id")}),Yh=Nw({channel:dr({name:"channel",indexes:[{accessor:"id",name:"channel_id_idx_btree",algorithm:"btree",columns:["id"]},{accessor:"by_server_id",name:"channel_server_id_idx_btree",algorithm:"btree",columns:["serverId"]}],constraints:[{name:"channel_id_key",constraint:"unique",columns:["id"]}]},Fv),ice_candidate:dr({name:"ice_candidate",indexes:[{accessor:"by_receiver",name:"ice_candidate_receiver_idx_btree",algorithm:"btree",columns:["receiver"]}],constraints:[]},$v),message:dr({name:"message",indexes:[{accessor:"by_channel_id",name:"message_channel_id_idx_btree",algorithm:"btree",columns:["channelId"]},{accessor:"id",name:"message_id_idx_btree",algorithm:"btree",columns:["id"]},{accessor:"by_thread_id",name:"message_thread_id_idx_btree",algorithm:"btree",columns:["threadId"]}],constraints:[{name:"message_id_key",constraint:"unique",columns:["id"]}]},Lv),sdp_answer:dr({name:"sdp_answer",indexes:[{accessor:"by_receiver",name:"sdp_answer_receiver_idx_btree",algorithm:"btree",columns:["receiver"]}],constraints:[]},Vv),sdp_offer:dr({name:"sdp_offer",indexes:[{accessor:"by_receiver",name:"sdp_offer_receiver_idx_btree",algorithm:"btree",columns:["receiver"]}],constraints:[]},qv),server:dr({name:"server",indexes:[{accessor:"id",name:"server_id_idx_btree",algorithm:"btree",columns:["id"]}],constraints:[{name:"server_id_key",constraint:"unique",columns:["id"]}]},Hv),thread:dr({name:"thread",indexes:[{accessor:"by_channel_id",name:"thread_channel_id_idx_btree",algorithm:"btree",columns:["channelId"]},{accessor:"id",name:"thread_id_idx_btree",algorithm:"btree",columns:["id"]},{accessor:"parent_message_id",name:"thread_parent_message_id_idx_btree",algorithm:"btree",columns:["parentMessageId"]}],constraints:[{name:"thread_id_key",constraint:"unique",columns:["id"]},{name:"thread_parent_message_id_key",constraint:"unique",columns:["parentMessageId"]}]},Kv),user:dr({name:"user",indexes:[{accessor:"identity",name:"user_identity_idx_btree",algorithm:"btree",columns:["identity"]}],constraints:[{name:"user_identity_key",constraint:"unique",columns:["identity"]}]},Wv),voice_state:dr({name:"voice_state",indexes:[{accessor:"by_channel_id",name:"voice_state_channel_id_idx_btree",algorithm:"btree",columns:["channelId"]},{accessor:"identity",name:"voice_state_identity_idx_btree",algorithm:"btree",columns:["identity"]}],constraints:[{name:"voice_state_identity_key",constraint:"unique",columns:["identity"]}]},Qv)}),Zh=Cv(jt("create_channel",Ev),jt("create_server",Uv),jt("create_thread",Rv),jt("join_voice",Nv),jt("leave_voice",Pv),jt("login",Bv),jt("register",Av),jt("send_ice_candidate",Mv),jt("send_message",jv),jt("send_sdp_answer",Ov),jt("send_sdp_offer",Dv),jt("set_name",zv)),Jv=Tv(),Gv={versionInfo:{cliVersion:"2.1.0"},tables:Yh.schemaType.tables,reducers:Zh.reducersType.reducers,...Jv},fi=Nh(Yh.schemaType),fr=Pw(Zh.reducersType.reducers);class Xv extends Fh{}class Yv extends Sw{}class Fu extends kw{static builder=()=>new Yv(Gv,n=>new Fu(n));subscriptionBuilder=()=>new Xv(this)}var ep=class ia{__time_duration_micros__;static MICROS_PER_MILLIS=1000n;static getAlgebraicType(){return Be.Product({elements:[{name:"__time_duration_micros__",algebraicType:Be.I64}]})}static isTimeDuration(n){if(n.tag!=="Product")return!1;const s=n.value.elements;if(s.length!==1)return!1;const a=s[0];return a.name==="__time_duration_micros__"&&a.algebraicType.tag==="I64"}get micros(){return this.__time_duration_micros__}get millis(){return Number(this.micros/ia.MICROS_PER_MILLIS)}constructor(n){this.__time_duration_micros__=n}static fromMillis(n){return new ia(BigInt(n)*ia.MICROS_PER_MILLIS)}toString(){const n=this.micros,s=n<0?"-":"+",a=n<0?-n:n,c=a/1000000n,f=a%1000000n;return`${s}${c}.${String(f).padStart(6,"0")}`}},tp=class mn{__timestamp_micros_since_unix_epoch__;static MICROS_PER_MILLIS=1000n;get microsSinceUnixEpoch(){return this.__timestamp_micros_since_unix_epoch__}constructor(n){this.__timestamp_micros_since_unix_epoch__=n}static getAlgebraicType(){return Be.Product({elements:[{name:"__timestamp_micros_since_unix_epoch__",algebraicType:Be.I64}]})}static isTimestamp(n){if(n.tag!=="Product")return!1;const s=n.value.elements;if(s.length!==1)return!1;const a=s[0];return a.name==="__timestamp_micros_since_unix_epoch__"&&a.algebraicType.tag==="I64"}static UNIX_EPOCH=new mn(0n);static now(){return mn.fromDate(new Date)}toMillis(){return this.microsSinceUnixEpoch/1000n}static fromDate(n){const s=n.getTime(),a=BigInt(s)*mn.MICROS_PER_MILLIS;return new mn(a)}toDate(){const s=this.__timestamp_micros_since_unix_epoch__/mn.MICROS_PER_MILLIS;if(s>BigInt(Number.MAX_SAFE_INTEGER)||sBigInt(Number.MAX_SAFE_INTEGER)||s_t.MAX_UUID_BIGINT)throw new Error("Invalid UUID: must be between 0 and `MAX_UUID_BIGINT`");this.__uuid__=n}static fromRandomBytesV4(n){if(n.length!==16)throw new Error("UUID v4 requires 16 bytes");const s=new Uint8Array(n);return s[6]=s[6]&15|64,s[8]=s[8]&63|128,new _t(_t.bytesToBigInt(s))}static fromCounterV7(n,s,a){if(a.length!==4)throw new Error("`fromCounterV7` requires `randomBytes.length == 4`");if(n.value<0)throw new Error("`fromCounterV7` uuid `counter` must be non-negative");if(s.__timestamp_micros_since_unix_epoch__<0)throw new Error("`fromCounterV7` `timestamp` before unix epoch");const c=n.value;n.value=c+1&2147483647;const f=s.toMillis()&0xffffffffffffn,p=new Uint8Array(16);return p[0]=Number(f>>40n&0xffn),p[1]=Number(f>>32n&0xffn),p[2]=Number(f>>24n&0xffn),p[3]=Number(f>>16n&0xffn),p[4]=Number(f>>8n&0xffn),p[5]=Number(f&0xffn),p[7]=c>>>23&255,p[9]=c>>>15&255,p[10]=c>>>7&255,p[11]=(c&127)<<1&255,p[12]|=a[0]&127,p[13]=a[1],p[14]=a[2],p[15]=a[3],p[6]=p[6]&15|112,p[8]=p[8]&63|128,new _t(_t.bytesToBigInt(p))}static parse(n){const s=n.replace(/-/g,"");if(s.length!==32)throw new Error("Invalid hex UUID");let a=0n;for(let c=0;c<32;c+=2)a=a<<8n|BigInt(parseInt(s.slice(c,c+2),16));return new _t(a)}toString(){const s=[..._t.bigIntToBytes(this.__uuid__)].map(a=>a.toString(16).padStart(2,"0")).join("");return s.slice(0,8)+"-"+s.slice(8,12)+"-"+s.slice(12,16)+"-"+s.slice(16,20)+"-"+s.slice(20)}asBigInt(){return this.__uuid__}toBytes(){return _t.bigIntToBytes(this.__uuid__)}static bytesToBigInt(n){let s=0n;for(const a of n)s=s<<8n|BigInt(a);return s}static bigIntToBytes(n){const s=new Uint8Array(16);for(let a=15;a>=0;a--)s[a]=Number(n&0xffn),n>>=8n;return s}getVersion(){const n=this.toBytes()[6]>>4&15;switch(n){case 4:return"V4";case 7:return"V7";default:if(this==_t.NIL)return"Nil";if(this==_t.MAX)return"Max";throw new Error(`Unsupported UUID version: ${n}`)}}getCounter(){const n=this.toBytes(),s=n[7],a=n[9],c=n[10],f=n[11]>>>1;return s<<23|a<<15|c<<7|f|0}compareTo(n){return this.__uuid__n.__uuid__?1:0}static getAlgebraicType(){return Be.Product({elements:[{name:"__uuid__",algebraicType:Be.U128}]})}},Ze=class{view;offset=0;constructor(r){this.view=r instanceof DataView?r:new DataView(r.buffer,r.byteOffset,r.byteLength),this.offset=0}reset(r){this.view=r,this.offset=0}get remaining(){return this.view.byteLength-this.offset}#e(r){if(this.offset+r>this.view.byteLength)throw new RangeError(`Tried to read ${r} byte(s) at relative offset ${this.offset}, but only ${this.remaining} byte(s) remain`)}readUInt8Array(){const r=this.readU32();return this.#e(r),this.readBytes(r)}readBool(){const r=this.view.getUint8(this.offset);return this.offset+=1,r!==0}readByte(){const r=this.view.getUint8(this.offset);return this.offset+=1,r}readBytes(r){const n=new Uint8Array(this.view.buffer,this.view.byteOffset+this.offset,r);return this.offset+=r,n}readI8(){const r=this.view.getInt8(this.offset);return this.offset+=1,r}readU8(){return this.readByte()}readI16(){const r=this.view.getInt16(this.offset,!0);return this.offset+=2,r}readU16(){const r=this.view.getUint16(this.offset,!0);return this.offset+=2,r}readI32(){const r=this.view.getInt32(this.offset,!0);return this.offset+=4,r}readU32(){const r=this.view.getUint32(this.offset,!0);return this.offset+=4,r}readI64(){const r=this.view.getBigInt64(this.offset,!0);return this.offset+=8,r}readU64(){const r=this.view.getBigUint64(this.offset,!0);return this.offset+=8,r}readU128(){const r=this.view.getBigUint64(this.offset,!0),n=this.view.getBigUint64(this.offset+8,!0);return this.offset+=16,(n<>BigInt(64);this.view.setBigUint64(this.offset,n,!0),this.view.setBigUint64(this.offset+8,s,!0),this.offset+=16}writeI128(r){this.expandBuffer(16);const n=r&BigInt("0xFFFFFFFFFFFFFFFF"),s=r>>BigInt(64);this.view.setBigInt64(this.offset,n,!0),this.view.setBigInt64(this.offset+8,s,!0),this.offset+=16}writeU256(r){this.expandBuffer(32);const n=BigInt("0xFFFFFFFFFFFFFFFF"),s=r&n,a=r>>BigInt(64)&n,c=r>>BigInt(128)&n,f=r>>BigInt(192);this.view.setBigUint64(this.offset+0,s,!0),this.view.setBigUint64(this.offset+8,a,!0),this.view.setBigUint64(this.offset+16,c,!0),this.view.setBigUint64(this.offset+24,f,!0),this.offset+=32}writeI256(r){this.expandBuffer(32);const n=BigInt("0xFFFFFFFFFFFFFFFF"),s=r&n,a=r>>BigInt(64)&n,c=r>>BigInt(128)&n,f=r>>BigInt(192);this.view.setBigUint64(this.offset+0,s,!0),this.view.setBigUint64(this.offset+8,a,!0),this.view.setBigUint64(this.offset+16,c,!0),this.view.setBigInt64(this.offset+24,f,!0),this.offset+=32}writeF32(r){this.expandBuffer(4),this.view.setFloat32(this.offset,r,!0),this.offset+=4}writeF64(r){this.expandBuffer(8),this.view.setFloat64(this.offset,r,!0),this.offset+=8}writeString(r){const s=new TextEncoder().encode(r);this.writeUInt8Array(s)}};function rp(r){return Array.prototype.map.call(r.reverse(),n=>("00"+n.toString(16)).slice(-2)).join("")}function r_(r){if(r.length!=16)throw new Error(`Uint8Array is not 16 bytes long: ${r}`);return new Ze(r).readU128()}function n_(r){if(r.length!=32)throw new Error(`Uint8Array is not 32 bytes long: [${r}]`);return new Ze(r).readU256()}function np(r){r.startsWith("0x")&&(r=r.slice(2));const n=r.match(/.{1,2}/g)||[];return Uint8Array.from(n.map(a=>parseInt(a,16))).reverse()}function i_(r){return r_(np(r))}function s_(r){return n_(np(r))}function ip(r){const n=new Ke(16);return n.writeU128(r),n.getBuffer()}function o_(r){return rp(ip(r))}function sp(r){const n=new Ke(32);return n.writeU256(r),n.getBuffer()}function a_(r){return rp(sp(r))}var ah=Object.hasOwn,l_=class Tu{__identity__;constructor(n){this.__identity__=typeof n=="string"?s_(n):n}static getAlgebraicType(){return Be.Product({elements:[{name:"__identity__",algebraicType:Be.U256}]})}isEqual(n){return this.toHexString()===n.toHexString()}equals(n){return this.isEqual(n)}toHexString(){return a_(this.__identity__)}toUint8Array(){return sp(this.__identity__)}static fromString(n){return new Tu(n)}static zero(){return new Tu(0n)}toString(){return this.toHexString()}},Us=new Map,Rs=new Map,Be={Ref:r=>({tag:"Ref",value:r}),Sum:r=>({tag:"Sum",value:r}),Product:r=>({tag:"Product",value:r}),Array:r=>({tag:"Array",value:r}),String:{tag:"String"},Bool:{tag:"Bool"},I8:{tag:"I8"},U8:{tag:"U8"},I16:{tag:"I16"},U16:{tag:"U16"},I32:{tag:"I32"},U32:{tag:"U32"},I64:{tag:"I64"},U64:{tag:"U64"},I128:{tag:"I128"},U128:{tag:"U128"},I256:{tag:"I256"},U256:{tag:"U256"},F32:{tag:"F32"},F64:{tag:"F64"},makeSerializer(r,n){if(r.tag==="Ref"){if(!n)throw new Error("cannot serialize refs without a typespace");for(;r.tag==="Ref";)r=n.types[r.value]}switch(r.tag){case"Product":return Ns.makeSerializer(r.value,n);case"Sum":return fa.makeSerializer(r.value,n);case"Array":if(r.value.tag==="U8")return u_;{const s=Be.makeSerializer(r.value,n);return(a,c)=>{a.writeU32(c.length);for(const f of c)s(a,f)}}default:return op[r.tag]}},serializeValue(r,n,s,a){Be.makeSerializer(n,a)(r,s)},makeDeserializer(r,n){if(r.tag==="Ref"){if(!n)throw new Error("cannot deserialize refs without a typespace");for(;r.tag==="Ref";)r=n.types[r.value]}switch(r.tag){case"Product":return Ns.makeDeserializer(r.value,n);case"Sum":return fa.makeDeserializer(r.value,n);case"Array":if(r.value.tag==="U8")return c_;{const s=Be.makeDeserializer(r.value,n);return a=>{const c=a.readU32(),f=Array(c);for(let p=0;pr.elements.every(({algebraicType:n})=>d_.has(n.tag)),f_=r=>r.elements.reduce((n,{algebraicType:s})=>n+Ii[s.tag],0),Xo={Bool:"Uint8",I8:"Int8",U8:"Uint8",I16:"Int16",U16:"Uint16",I32:"Int32",U32:"Uint32",I64:"BigInt64",U64:"BigUint64",F32:"Float32",F64:"Float64"},sa={__time_duration_micros__:r=>new ep(r.readI64()),__timestamp_micros_since_unix_epoch__:r=>new tp(r.readI64()),__identity__:r=>new l_(r.readU256()),__connection_id__:r=>new $u(r.readU128()),__uuid__:r=>new Zv(r.readU128())};Object.freeze(sa);var h_=()=>({}),uh=r=>{let n;switch(r.algebraicType.tag){case"String":n="''";break;case"Bool":n="false";break;case"I8":case"U8":case"I16":case"U16":case"I32":case"U32":n="0";break;case"I64":case"U64":case"I128":case"U128":case"I256":case"U256":n="0n";break;case"F32":case"F64":n="0.0";break;default:n="undefined"}return`${r.name}: ${n}`},Ns={makeSerializer(r,n){let s=Us.get(r);if(s!=null)return s;if(lh(r)){const p=`"use strict"; writer.expandBuffer(${f_(r)}); const view = writer.view; ${r.elements.map(({name:v,algebraicType:{tag:y}})=>y in Xo?`view.set${Xo[y]}(writer.offset, value.${v}, ${Ii[y]>1?"true":""}); writer.offset += ${Ii[y]};`:`writer.write${y}(value.${v});`).join(` `)}`;return s=Function("writer","value",p),Us.set(r,s),s}const a={},c=`"use strict"; `+r.elements.map(f=>`this.${f.name}(writer, value.${f.name});`).join(` `);s=Function("writer","value",c).bind(a),Us.set(r,s);for(const{name:f,algebraicType:p}of r.elements)a[f]=Be.makeSerializer(p,n);return Object.freeze(a),s},serializeValue(r,n,s,a){Ns.makeSerializer(n,a)(r,s)},makeDeserializer(r,n){switch(r.elements.length){case 0:return h_;case 1:{const c=r.elements[0].name;if(ah(sa,c))return sa[c]}}let s=Rs.get(r);if(s!=null)return s;if(lh(r)){const c=`"use strict"; const result = { ${r.elements.map(uh).join(", ")} }; const view = reader.view; ${r.elements.map(({name:f,algebraicType:{tag:p}})=>p in Xo?p==="Bool"?`result.${f} = view.getUint8(reader.offset) !== 0; reader.offset += 1;`:`result.${f} = view.get${Xo[p]}(reader.offset, ${Ii[p]>1?"true":""}); reader.offset += ${Ii[p]};`:`result.${f} = reader.read${p}();`).join(` `)} return result;`;return s=Function("reader",c),Rs.set(r,s),s}const a={};s=Function("reader",`"use strict"; const result = { ${r.elements.map(uh).join(", ")} }; ${r.elements.map(({name:c})=>`result.${c} = this.${c}(reader);`).join(` `)} return result;`).bind(a),Rs.set(r,s);for(const{name:c,algebraicType:f}of r.elements)a[c]=Be.makeDeserializer(f,n);return Object.freeze(a),s},deserializeValue(r,n,s){return Ns.makeDeserializer(n,s)(r)},intoMapKey(r,n){if(r.elements.length===1){const a=r.elements[0].name;if(ah(sa,a))return n[a]}const s=new Ke(10);return Be.serializeValue(s,Be.Product(r),n),s.toBase64()}},fa={makeSerializer(r,n){if(r.variants.length==2&&r.variants[0].name==="some"&&r.variants[1].name==="none"){const s=Be.makeSerializer(r.variants[0].algebraicType,n);return(a,c)=>{c!=null?(a.writeByte(0),s(a,c)):a.writeByte(1)}}else if(r.variants.length==2&&r.variants[0].name==="ok"&&r.variants[1].name==="err"){const s=Be.makeSerializer(r.variants[0].algebraicType,n),a=Be.makeSerializer(r.variants[0].algebraicType,n);return(c,f)=>{if("ok"in f)c.writeU8(0),s(c,f.ok);else if("err"in f)c.writeU8(1),a(c,f.err);else throw new TypeError("could not serialize result: object had neither a `ok` nor an `err` field")}}else{let s=Us.get(r);if(s!=null)return s;const a={},c=`switch (value.tag) { ${r.variants.map(({name:f},p)=>` case ${JSON.stringify(f)}: writer.writeByte(${p}); return this.${f}(writer, value.value);`).join(` `)} default: throw new TypeError( \`Could not serialize sum type; unknown tag \${value.tag}\` ) } `;s=Function("writer","value",c).bind(a),Us.set(r,s);for(const{name:f,algebraicType:p}of r.variants)a[f]=Be.makeSerializer(p,n);return Object.freeze(a),s}},serializeValue(r,n,s,a){fa.makeSerializer(n,a)(r,s)},makeDeserializer(r,n){if(r.variants.length==2&&r.variants[0].name==="some"&&r.variants[1].name==="none"){const s=Be.makeDeserializer(r.variants[0].algebraicType,n);return a=>{const c=a.readU8();if(c===0)return s(a);if(c===1)return;throw`Can't deserialize an option type, couldn't find ${c} tag`}}else if(r.variants.length==2&&r.variants[0].name==="ok"&&r.variants[1].name==="err"){const s=Be.makeDeserializer(r.variants[0].algebraicType,n),a=Be.makeDeserializer(r.variants[1].algebraicType,n);return c=>{const f=c.readByte();if(f===0)return{ok:s(c)};if(f===1)return{err:a(c)};throw`Can't deserialize a result type, couldn't find ${f} tag`}}else{let s=Rs.get(r);if(s!=null)return s;const a={};s=Function("reader",`switch (reader.readU8()) { ${r.variants.map(({name:c},f)=>`case ${f}: return { tag: ${JSON.stringify(c)}, value: this.${c}(reader) };`).join(` `)} }`).bind(a),Rs.set(r,s);for(const{name:c,algebraicType:f}of r.variants)a[c]=Be.makeDeserializer(f,n);return Object.freeze(a),s}},deserializeValue(r,n,s){return fa.makeDeserializer(n,s)(r)}},$u=class oa{__connection_id__;constructor(n){this.__connection_id__=n}static getAlgebraicType(){return Be.Product({elements:[{name:"__connection_id__",algebraicType:Be.U128}]})}isZero(){return this.__connection_id__===BigInt(0)}static nullIfZero(n){return n.isZero()?null:n}static random(){function n(){return Math.floor(Math.random()*255)}let s=BigInt(0);for(let a=0;a<16;a++)s=s<Ot(r.right,n);case"gte":return Ot(r.left,n)>=Ot(r.right,n);case"lt":return Ot(r.left,n)aa(s,n));case"or":return r.clauses.some(s=>aa(s,n));case"not":return!aa(r.clause,n)}}function Ot(r,n){return g_(r)?ch(r.value):ch(n[r.column])}function m_(r){return!!r&&typeof r=="object"&&typeof r.toHexString=="function"}function y_(r){return!r||typeof r!="object"?!1:r instanceof tp?!0:typeof r.__timestamp_micros_since_unix_epoch__=="bigint"}function ch(r){return m_(r)?r.toHexString():y_(r)?r.__timestamp_micros_since_unix_epoch__:r}function w_(r){if(r.table)return r.table.accessorName;if(r.accessorName)return r.accessorName;if(r.sourceQuery)return r.sourceQuery.table.accessorName;throw new Error("Cannot extract accessor name from query")}function v_(r){if(r.whereClause)return r.whereClause}var lp=ae.createContext(void 0);function Lu(){const r=ae.useContext(lp);if(!r)throw new Error("useSpacetimeDB must be used within a SpacetimeDBProvider component. Did you forget to add a `SpacetimeDBProvider` to your component tree?");return r}function __(){return{isActive:!1,identity:void 0,token:void 0,connectionId:$u.random(),connectionError:void 0}}var S_=class up{#e=new Map;static getKey(n,s){return`${n}::${s}`}getKey(n,s){return up.getKey(n,s)}#t(n){const s=this.#e.get(n);if(s)return s;const a={connection:void 0,refCount:0,state:__(),listeners:new Set,pendingRelease:null};return this.#e.set(n,a),a}#n(n){for(const s of n.listeners)s()}retain(n,s){const a=this.#t(n);if(a.pendingRelease&&(clearTimeout(a.pendingRelease),a.pendingRelease=null),a.refCount+=1,a.connection)return a.connection;const c=s.build();a.connection=c;const f=p=>{a.state={...a.state,...p},this.#n(a)};return f({isActive:c.isActive,identity:c.identity,token:c.token,connectionId:c.connectionId,connectionError:void 0}),a.onConnect=p=>{f({isActive:p.isActive,identity:p.identity,token:p.token,connectionId:p.connectionId,connectionError:void 0})},a.onDisconnect=(p,v)=>{f({isActive:p.isActive,connectionError:v??void 0})},a.onConnectError=(p,v)=>{f({isActive:p.isActive,connectionError:v})},s.onConnect(a.onConnect),s.onDisconnect(a.onDisconnect),s.onConnectError(a.onConnectError),c}release(n){const s=this.#e.get(n);s&&(s.refCount-=1,!(s.refCount>0||s.pendingRelease)&&(s.pendingRelease=setTimeout(()=>{s.pendingRelease=null,!(s.refCount>0)&&(s.connection&&(s.onConnect&&s.connection.removeOnConnect(s.onConnect),s.onDisconnect&&s.connection.removeOnDisconnect(s.onDisconnect),s.onConnectError&&s.connection.removeOnConnectError(s.onConnectError),s.connection.disconnect()),this.#e.delete(n))},0)))}subscribe(n,s){const a=this.#t(n);return a.listeners.add(s),()=>{a.listeners.delete(s),a.refCount<=0&&a.listeners.size===0&&!a.connection&&this.#e.delete(n)}}getSnapshot(n){return this.#e.get(n)?.state}getConnection(n){return this.#e.get(n)?.connection??null}},hi=new S_;function x_({connectionBuilder:r,children:n}){const s=r.getUri(),a=r.getModuleName(),c=ae.useMemo(()=>hi.getKey(s,a),[s,a]),f=ae.useRef({isActive:!1,identity:void 0,token:void 0,connectionId:$u.random(),connectionError:void 0}),p=ae.useCallback(j=>hi.subscribe(c,j),[c]),v=ae.useCallback(()=>hi.getSnapshot(c)??f.current,[c]),y=ae.useCallback(()=>f.current,[]),x=ae.useSyncExternalStore(p,v,y),R=ae.useCallback(()=>hi.getConnection(c),[c]),N=ae.useMemo(()=>({...x,getConnection:R}),[x,R]);return ae.useEffect(()=>(hi.retain(c,r),()=>{hi.release(c)}),[c,r]),ae.createElement(lp.Provider,{value:N},n)}function I_(r,n,s){if(!r)return"stayIn";const a=Ps(r,n),c=Ps(r,s);return a&&!c?"leave":!a&&c?"enter":a&&c?"stayIn":"stayOut"}function pi(r,n){const s=w_(r),a=v_(r),[c,f]=ae.useState(!1);let p;try{p=Lu()}catch{throw new Error("Could not find SpacetimeDB client! Did you forget to add a `SpacetimeDBProvider`? `useTable` must be used in the React component tree under a `SpacetimeDBProvider` component.")}const v=p_(r),y=ae.useRef(null),x=ae.useRef(null),R=ae.useCallback(()=>{const O=p.getConnection();if(!O)return[[],!1];const q=O.db[s];return[a?Array.from(q.iter()).filter($=>Ps(a,$)):Array.from(q.iter()),c]},[p,s,v,c]);ae.useEffect(()=>{x.current=null},[R]),ae.useEffect(()=>{const O=p.getConnection();if(p.isActive&&O){const q=O.subscriptionBuilder().onApplied(()=>{f(!0)}).subscribe(v);return()=>{q.unsubscribe()}}},[v,p.isActive,p]);const N=ae.useCallback(O=>{const q=(A,L)=>{a&&!Ps(a,L)||A.event.id!==y.current&&(y.current=A.event.id,x.current=R(),O())},Q=(A,L)=>{a&&!Ps(a,L)||A.event.id!==y.current&&(y.current=A.event.id,x.current=R(),O())},$=(A,L,J)=>{switch(I_(a,L,J)){case"leave":break;case"enter":break;case"stayIn":break;case"stayOut":return}A.event.id!==y.current&&(y.current=A.event.id,x.current=R(),O())},fe=p.getConnection();if(!fe)return()=>{};const T=fe.db[s];return T.onInsert(q),T.onDelete(Q),T.onUpdate?.($),()=>{T.removeOnInsert(q),T.removeOnDelete(Q),T.removeOnUpdate?.($)}},[p,s,v,R,n?.onDelete,n?.onInsert,n?.onUpdate]),j=ae.useCallback(()=>(x.current||(x.current=R()),x.current),[R]);return ae.useSyncExternalStore(N,j,j)}function hr(r){const{getConnection:n,isActive:s}=Lu(),a=r.accessorName,c=ae.useRef([]);return ae.useEffect(()=>{const f=n();if(!f)return;const p=f.reducers[a];if(c.current.length){const v=c.current.splice(0);for(const y of v)p(...y.params).then(y.resolve,y.reject)}},[n,a,s]),ae.useCallback((...f)=>{const p=n();if(!p)return new Promise((y,x)=>{c.current.push({params:f,resolve:y,reject:x})});const v=p.reducers[a];return v(...f)},[n,a])}class ks extends Error{}ks.prototype.name="InvalidTokenError";function k_(r){return decodeURIComponent(atob(r).replace(/(.)/g,(n,s)=>{let a=s.charCodeAt(0).toString(16).toUpperCase();return a.length<2&&(a="0"+a),"%"+a}))}function b_(r){let n=r.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return k_(n)}catch{return atob(n)}}function C_(r,n){if(typeof r!="string")throw new ks("Invalid token specified: must be a string");n||(n={});const s=n.header===!0?0:1,a=r.split(".")[s];if(typeof a!="string")throw new ks(`Invalid token specified: missing part #${s+1}`);let c;try{c=b_(a)}catch(f){throw new ks(`Invalid token specified: invalid base64 for part #${s+1} (${f.message})`)}try{return JSON.parse(c)}catch(f){throw new ks(`Invalid token specified: invalid json for part #${s+1} (${f.message})`)}}var T_={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},er,tr,ha=(r=>(r[r.NONE=0]="NONE",r[r.ERROR=1]="ERROR",r[r.WARN=2]="WARN",r[r.INFO=3]="INFO",r[r.DEBUG=4]="DEBUG",r))(ha||{});(r=>{function n(){er=3,tr=T_}r.reset=n;function s(c){if(!(0<=c&&c<=4))throw new Error("Invalid log level");er=c}r.setLevel=s;function a(c){tr=c}r.setLogger=a})(ha||(ha={}));var Se=class Zt{constructor(n){this._name=n}debug(...n){er>=4&&tr.debug(Zt._format(this._name,this._method),...n)}info(...n){er>=3&&tr.info(Zt._format(this._name,this._method),...n)}warn(...n){er>=2&&tr.warn(Zt._format(this._name,this._method),...n)}error(...n){er>=1&&tr.error(Zt._format(this._name,this._method),...n)}throw(n){throw this.error(n),n}create(n){const s=Object.create(this);return s._method=n,s.debug("begin"),s}static createStatic(n,s){const a=new Zt(`${n}.${s}`);return a.debug("begin"),a}static _format(n,s){const a=`[${n}]`;return s?`${a} ${s}:`:a}static debug(n,...s){er>=4&&tr.debug(Zt._format(n),...s)}static info(n,...s){er>=3&&tr.info(Zt._format(n),...s)}static warn(n,...s){er>=2&&tr.warn(Zt._format(n),...s)}static error(n,...s){er>=1&&tr.error(Zt._format(n),...s)}};ha.reset();var Ms=class{static decode(r){try{return C_(r)}catch(n){throw Se.error("JwtUtils.decode",n),n}}static async generateSignedJwt(r,n,s){const a=Je.encodeBase64Url(new TextEncoder().encode(JSON.stringify(r))),c=Je.encodeBase64Url(new TextEncoder().encode(JSON.stringify(n))),f=`${a}.${c}`,p=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},s,new TextEncoder().encode(f)),v=Je.encodeBase64Url(new Uint8Array(p));return`${f}.${v}`}static async generateSignedJwtWithHmac(r,n,s){const a=Je.encodeBase64Url(new TextEncoder().encode(JSON.stringify(r))),c=Je.encodeBase64Url(new TextEncoder().encode(JSON.stringify(n))),f=`${a}.${c}`,p=await window.crypto.subtle.sign("HMAC",s,new TextEncoder().encode(f)),v=Je.encodeBase64Url(new Uint8Array(p));return`${f}.${v}`}},E_="10000000-1000-4000-8000-100000000000",Eu=r=>btoa([...new Uint8Array(r)].map(n=>String.fromCharCode(n)).join("")),cp=class Kt{static _randomWord(){const n=new Uint32Array(1);return crypto.getRandomValues(n),n[0]}static generateUUIDv4(){return E_.replace(/[018]/g,s=>(+s^Kt._randomWord()&15>>+s/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return Kt.generateUUIDv4()+Kt.generateUUIDv4()+Kt.generateUUIDv4()}static async generateCodeChallenge(n){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const a=new TextEncoder().encode(n),c=await crypto.subtle.digest("SHA-256",a);return Eu(c).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(s){throw Se.error("CryptoUtils.generateCodeChallenge",s),s}}static generateBasicAuth(n,s){const c=new TextEncoder().encode([n,s].join(":"));return Eu(c)}static async hash(n,s){const a=new TextEncoder().encode(s),c=await crypto.subtle.digest(n,a);return new Uint8Array(c)}static async customCalculateJwkThumbprint(n){let s;switch(n.kty){case"RSA":s={e:n.e,kty:n.kty,n:n.n};break;case"EC":s={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case"OKP":s={crv:n.crv,kty:n.kty,x:n.x};break;case"oct":s={crv:n.k,kty:n.kty};break;default:throw new Error("Unknown jwk type")}const a=await Kt.hash("SHA-256",JSON.stringify(s));return Kt.encodeBase64Url(a)}static async generateDPoPProof({url:n,accessToken:s,httpMethod:a,keyPair:c,nonce:f}){let p,v;const y={jti:window.crypto.randomUUID(),htm:a??"GET",htu:n,iat:Math.floor(Date.now()/1e3)};s&&(p=await Kt.hash("SHA-256",s),v=Kt.encodeBase64Url(p),y.ath=v),f&&(y.nonce=f);try{const x=await crypto.subtle.exportKey("jwk",c.publicKey),R={alg:"ES256",typ:"dpop+jwt",jwk:{crv:x.crv,kty:x.kty,x:x.x,y:x.y}};return await Ms.generateSignedJwt(R,y,c.privateKey)}catch(x){throw x instanceof TypeError?new Error(`Error exporting dpop public key: ${x.message}`):x}}static async generateDPoPJkt(n){try{const s=await crypto.subtle.exportKey("jwk",n.publicKey);return await Kt.customCalculateJwkThumbprint(s)}catch(s){throw s instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${s.message}`):s}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(n,s,a,c="HS256"){const f=Math.floor(Date.now()/1e3),p={alg:c,typ:"JWT"},v={iss:n,sub:n,aud:a,jti:Kt.generateUUIDv4(),exp:f+300,iat:f},x={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[c];if(!x)throw new Error(`Unsupported algorithm: ${c}. Supported algorithms are: HS256, HS384, HS512`);const R=new TextEncoder,N=await crypto.subtle.importKey("raw",R.encode(s),{name:"HMAC",hash:x},!1,["sign"]);return await Ms.generateSignedJwtWithHmac(p,v,N)}};cp.encodeBase64Url=r=>Eu(r).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var Je=cp,Or=class{constructor(r){this._name=r,this._callbacks=[],this._logger=new Se(`Event('${this._name}')`)}addHandler(r){return this._callbacks.push(r),()=>this.removeHandler(r)}removeHandler(r){const n=this._callbacks.lastIndexOf(r);n>=0&&this._callbacks.splice(n,1)}async raise(...r){this._logger.debug("raise:",...r);for(const n of this._callbacks)await n(...r)}},dh=class{static center({...r}){var n,s,a;return r.width==null&&(r.width=(n=[800,720,600,480].find(c=>c<=window.outerWidth/1.618))!=null?n:360),(s=r.left)!=null||(r.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-r.width)/2))),r.height!=null&&((a=r.top)!=null||(r.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-r.height)/2)))),r}static serialize(r){return Object.entries(r).filter(([,n])=>n!=null).map(([n,s])=>`${n}=${typeof s!="boolean"?s:s?"yes":"no"}`).join(",")}},gr=class la extends Or{constructor(){super(...arguments),this._logger=new Se(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const n=this._expiration-la.getEpochTime();this._logger.debug("timer completes in",n),this._expiration<=la.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(n){const s=this._logger.create("init");n=Math.max(Math.floor(n),1);const a=la.getEpochTime()+n;if(this.expiration===a&&this._timerHandle){s.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),s.debug("using duration",n),this._expiration=a;const c=Math.min(n,5);this._timerHandle=setInterval(this._callback,c*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},Uu=class{static readParams(r,n="query"){if(!r)throw new TypeError("Invalid URL");const a=new URL(r,"http://127.0.0.1")[n==="fragment"?"hash":"search"];return new URLSearchParams(a.slice(1))}},Ti=";",vn=class extends Error{constructor(r,n){var s,a,c;if(super(r.error_description||r.error||""),this.form=n,this.name="ErrorResponse",!r.error)throw Se.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=r.error,this.error_description=(s=r.error_description)!=null?s:null,this.error_uri=(a=r.error_uri)!=null?a:null,this.state=r.userState,this.session_state=(c=r.session_state)!=null?c:null,this.url_state=r.url_state}},Vu=class extends Error{constructor(r){super(r),this.name="ErrorTimeout"}},U_=class{constructor(r){this._logger=new Se("AccessTokenEvents"),this._expiringTimer=new gr("Access token expiring"),this._expiredTimer=new gr("Access token expired"),this._expiringNotificationTimeInSeconds=r.expiringNotificationTimeInSeconds}async load(r){const n=this._logger.create("load");if(r.access_token&&r.expires_in!==void 0){const s=r.expires_in;if(n.debug("access token present, remaining duration:",s),s>0){let c=s-this._expiringNotificationTimeInSeconds;c<=0&&(c=1),n.debug("registering expiring timer, raising in",c,"seconds"),this._expiringTimer.init(c)}else n.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const a=s+1;n.debug("registering expired timer, raising in",a,"seconds"),this._expiredTimer.init(a)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(r){return this._expiringTimer.addHandler(r)}removeAccessTokenExpiring(r){this._expiringTimer.removeHandler(r)}addAccessTokenExpired(r){return this._expiredTimer.addHandler(r)}removeAccessTokenExpired(r){this._expiredTimer.removeHandler(r)}},R_=class{constructor(r,n,s,a,c){this._callback=r,this._client_id=n,this._intervalInSeconds=a,this._stopOnError=c,this._logger=new Se("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=p=>{p.origin===this._frame_origin&&p.source===this._frame.contentWindow&&(p.data==="error"?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):p.data==="changed"?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(p.data+" message from check session op iframe"))};const f=new URL(s);this._frame_origin=f.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=f.href}load(){return new Promise(r=>{this._frame.onload=()=>{r()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(r){if(this._session_state===r)return;this._logger.create("start"),this.stop(),this._session_state=r;const n=()=>{!this._frame.contentWindow||!this._session_state||this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};n(),this._timer=setInterval(n,this._intervalInSeconds*1e3)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},dp=class{constructor(){this._logger=new Se("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(r){return this._logger.create(`getItem('${r}')`),this._data[r]}setItem(r,n){this._logger.create(`setItem('${r}')`),this._data[r]=n}removeItem(r){this._logger.create(`removeItem('${r}')`),delete this._data[r]}get length(){return Object.getOwnPropertyNames(this._data).length}key(r){return Object.getOwnPropertyNames(this._data)[r]}},Ru=class extends Error{constructor(r,n){super(n),this.name="ErrorDPoPNonce",this.nonce=r}},qu=class{constructor(r=[],n=null,s={}){this._jwtHandler=n,this._extraHeaders=s,this._logger=new Se("JsonService"),this._contentTypes=[],this._contentTypes.push(...r,"application/json"),n&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(r,n={}){const{timeoutInSeconds:s,...a}=n;if(!s)return await fetch(r,a);const c=new AbortController,f=setTimeout(()=>c.abort(),s*1e3);try{return await fetch(r,{...n,signal:c.signal})}catch(p){throw p instanceof DOMException&&p.name==="AbortError"?new Vu("Network timed out"):p}finally{clearTimeout(f)}}async getJson(r,{token:n,credentials:s,timeoutInSeconds:a}={}){const c=this._logger.create("getJson"),f={Accept:this._contentTypes.join(", ")};n&&(c.debug("token passed, setting Authorization header"),f.Authorization="Bearer "+n),this._appendExtraHeaders(f);let p;try{c.debug("url:",r),p=await this.fetchWithTimeout(r,{method:"GET",headers:f,timeoutInSeconds:a,credentials:s})}catch(x){throw c.error("Network Error"),x}c.debug("HTTP response received, status",p.status);const v=p.headers.get("Content-Type");if(v&&!this._contentTypes.find(x=>v.startsWith(x))&&c.throw(new Error(`Invalid response Content-Type: ${v??"undefined"}, from URL: ${r}`)),p.ok&&this._jwtHandler&&v?.startsWith("application/jwt"))return await this._jwtHandler(await p.text());let y;try{y=await p.json()}catch(x){throw c.error("Error parsing JSON response",x),p.ok?x:new Error(`${p.statusText} (${p.status})`)}if(!p.ok)throw c.error("Error from server:",y),y.error?new vn(y):new Error(`${p.statusText} (${p.status}): ${JSON.stringify(y)}`);return y}async postForm(r,{body:n,basicAuth:s,timeoutInSeconds:a,initCredentials:c,extraHeaders:f}){const p=this._logger.create("postForm"),v={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...f};s!==void 0&&(v.Authorization="Basic "+s),this._appendExtraHeaders(v);let y;try{p.debug("url:",r),y=await this.fetchWithTimeout(r,{method:"POST",headers:v,body:n,timeoutInSeconds:a,credentials:c})}catch(j){throw p.error("Network error"),j}p.debug("HTTP response received, status",y.status);const x=y.headers.get("Content-Type");if(x&&!this._contentTypes.find(j=>x.startsWith(j)))throw new Error(`Invalid response Content-Type: ${x??"undefined"}, from URL: ${r}`);const R=await y.text();let N={};if(R)try{N=JSON.parse(R)}catch(j){throw p.error("Error parsing JSON response",j),y.ok?j:new Error(`${y.statusText} (${y.status})`)}if(!y.ok){if(p.error("Error from server:",N),y.headers.has("dpop-nonce")){const j=y.headers.get("dpop-nonce");throw new Ru(j,`${JSON.stringify(N)}`)}throw N.error?new vn(N,n):new Error(`${y.statusText} (${y.status}): ${JSON.stringify(N)}`)}return N}_appendExtraHeaders(r){const n=this._logger.create("appendExtraHeaders"),s=Object.keys(this._extraHeaders),a=["accept","content-type"],c=["authorization"];s.length!==0&&s.forEach(f=>{if(a.includes(f.toLocaleLowerCase())){n.warn("Protected header could not be set",f,a);return}if(c.includes(f.toLocaleLowerCase())&&Object.keys(r).includes(f)){n.warn("Header could not be overridden",f,c);return}const p=typeof this._extraHeaders[f]=="function"?this._extraHeaders[f]():this._extraHeaders[f];p&&p!==""&&(r[f]=p)})}},N_=class{constructor(r){this._settings=r,this._logger=new Se("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new qu(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const r=this._logger.create("getMetadata");if(this._metadata)return r.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw r.throw(new Error("No authority or metadataUrl configured on settings")),null;r.debug("getting metadata from",this._metadataUrl);const n=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return r.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},n,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(r=!0){return this._getMetadataProperty("token_endpoint",r)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(r=!0){return this._getMetadataProperty("revocation_endpoint",r)}getKeysEndpoint(r=!0){return this._getMetadataProperty("jwks_uri",r)}async _getMetadataProperty(r,n=!1){const s=this._logger.create(`_getMetadataProperty('${r}')`),a=await this.getMetadata();if(s.debug("resolved"),a[r]===void 0){if(n===!0){s.warn("Metadata does not contain optional property");return}s.throw(new Error("Metadata does not contain property "+r))}return a[r]}async getSigningKeys(){const r=this._logger.create("getSigningKeys");if(this._signingKeys)return r.debug("returning signingKeys from cache"),this._signingKeys;const n=await this.getKeysEndpoint(!1);r.debug("got jwks_uri",n);const s=await this._jsonService.getJson(n,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(r.debug("got key set",s),!Array.isArray(s.keys))throw r.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=s.keys,this._signingKeys}},fp=class{constructor({prefix:r="oidc.",store:n=localStorage}={}){this._logger=new Se("WebStorageStateStore"),this._store=n,this._prefix=r}async set(r,n){this._logger.create(`set('${r}')`),r=this._prefix+r,await this._store.setItem(r,n)}async get(r){return this._logger.create(`get('${r}')`),r=this._prefix+r,await this._store.getItem(r)}async remove(r){this._logger.create(`remove('${r}')`),r=this._prefix+r;const n=await this._store.getItem(r);return await this._store.removeItem(r),n}async getAllKeys(){this._logger.create("getAllKeys");const r=await this._store.length,n=[];for(let s=0;s{const a=this._logger.create("_getClaimsFromJwt");try{const c=Ms.decode(s);return a.debug("JWT decoding successful"),c}catch(c){throw a.error("Error parsing JWT response"),c}},this._jsonService=new qu(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(r){const n=this._logger.create("getClaims");r||this._logger.throw(new Error("No token passed"));const s=await this._metadataService.getUserInfoEndpoint();n.debug("got userinfo url",s);const a=await this._jsonService.getJson(s,{token:r,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return n.debug("got claims",a),a}},hp=class{constructor(r,n){this._settings=r,this._metadataService=n,this._logger=new Se("TokenClient"),this._jsonService=new qu(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:r="authorization_code",redirect_uri:n=this._settings.redirect_uri,client_id:s=this._settings.client_id,client_secret:a=this._settings.client_secret,extraHeaders:c,...f}){const p=this._logger.create("exchangeCode");s||p.throw(new Error("A client_id is required")),n||p.throw(new Error("A redirect_uri is required")),f.code||p.throw(new Error("A code is required"));const v=new URLSearchParams({grant_type:r,redirect_uri:n});for(const[N,j]of Object.entries(f))j!=null&&v.set(N,j);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&a==null)throw p.throw(new Error("A client_secret is required")),null;let y;const x=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":y=Je.generateBasicAuth(s,a);break;case"client_secret_post":v.append("client_id",s),a&&v.append("client_secret",a);break;case"client_secret_jwt":{const N=await Je.generateClientAssertionJwt(s,a,x,this._settings.token_endpoint_auth_signing_alg);v.append("client_id",s),v.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),v.append("client_assertion",N);break}}p.debug("got token endpoint");const R=await this._jsonService.postForm(x,{body:v,basicAuth:y,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:c});return p.debug("got response"),R}async exchangeCredentials({grant_type:r="password",client_id:n=this._settings.client_id,client_secret:s=this._settings.client_secret,scope:a=this._settings.scope,...c}){const f=this._logger.create("exchangeCredentials");n||f.throw(new Error("A client_id is required"));const p=new URLSearchParams({grant_type:r});this._settings.omitScopeWhenRequesting||p.set("scope",a);for(const[R,N]of Object.entries(c))N!=null&&p.set(R,N);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&s==null)throw f.throw(new Error("A client_secret is required")),null;let v;const y=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":v=Je.generateBasicAuth(n,s);break;case"client_secret_post":p.append("client_id",n),s&&p.append("client_secret",s);break;case"client_secret_jwt":{const R=await Je.generateClientAssertionJwt(n,s,y,this._settings.token_endpoint_auth_signing_alg);p.append("client_id",n),p.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),p.append("client_assertion",R);break}}f.debug("got token endpoint");const x=await this._jsonService.postForm(y,{body:p,basicAuth:v,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return f.debug("got response"),x}async exchangeRefreshToken({grant_type:r="refresh_token",client_id:n=this._settings.client_id,client_secret:s=this._settings.client_secret,timeoutInSeconds:a,extraHeaders:c,...f}){const p=this._logger.create("exchangeRefreshToken");n||p.throw(new Error("A client_id is required")),f.refresh_token||p.throw(new Error("A refresh_token is required"));const v=new URLSearchParams({grant_type:r});for(const[N,j]of Object.entries(f))Array.isArray(j)?j.forEach(O=>v.append(N,O)):j!=null&&v.set(N,j);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&s==null)throw p.throw(new Error("A client_secret is required")),null;let y;const x=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":y=Je.generateBasicAuth(n,s);break;case"client_secret_post":v.append("client_id",n),s&&v.append("client_secret",s);break;case"client_secret_jwt":{const N=await Je.generateClientAssertionJwt(n,s,x,this._settings.token_endpoint_auth_signing_alg);v.append("client_id",n),v.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),v.append("client_assertion",N);break}}p.debug("got token endpoint");const R=await this._jsonService.postForm(x,{body:v,basicAuth:y,timeoutInSeconds:a,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:c});return p.debug("got response"),R}async revoke(r){var n;const s=this._logger.create("revoke");r.token||s.throw(new Error("A token is required"));const a=await this._metadataService.getRevocationEndpoint(!1);s.debug(`got revocation endpoint, revoking ${(n=r.token_type_hint)!=null?n:"default token type"}`);const c=new URLSearchParams;for(const[f,p]of Object.entries(r))p!=null&&c.set(f,p);c.set("client_id",this._settings.client_id),this._settings.client_secret&&c.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(a,{body:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),s.debug("got response")}},O_=class{constructor(r,n,s){this._settings=r,this._metadataService=n,this._claimsService=s,this._logger=new Se("ResponseValidator"),this._userInfoService=new j_(this._settings,this._metadataService),this._tokenClient=new hp(this._settings,this._metadataService)}async validateSigninResponse(r,n,s){const a=this._logger.create("validateSigninResponse");this._processSigninState(r,n),a.debug("state processed"),await this._processCode(r,n,s),a.debug("code processed"),r.isOpenId&&this._validateIdTokenAttributes(r,"",n.nonce),a.debug("tokens validated"),await this._processClaims(r,n?.skipUserInfo,r.isOpenId),a.debug("claims processed")}async validateCredentialsResponse(r,n){const s=this._logger.create("validateCredentialsResponse"),a=r.isOpenId&&!!r.id_token;a&&this._validateIdTokenAttributes(r),s.debug("tokens validated"),await this._processClaims(r,n,a),s.debug("claims processed")}async validateRefreshResponse(r,n){var s,a;const c=this._logger.create("validateRefreshResponse");r.userState=n.data,(s=r.session_state)!=null||(r.session_state=n.session_state),(a=r.scope)!=null||(r.scope=n.scope),r.isOpenId&&r.id_token&&(this._validateIdTokenAttributes(r,n.id_token),c.debug("ID Token validated")),r.id_token||(r.id_token=n.id_token,r.profile=n.profile);const f=r.isOpenId&&!!r.id_token;await this._processClaims(r,!1,f),c.debug("claims processed")}validateSignoutResponse(r,n){const s=this._logger.create("validateSignoutResponse");if(n.id!==r.state&&s.throw(new Error("State does not match")),s.debug("state validated"),r.userState=n.data,r.error)throw s.warn("Response was error",r.error),new vn(r)}_processSigninState(r,n){var s;const a=this._logger.create("_processSigninState");if(n.id!==r.state&&a.throw(new Error("State does not match")),n.client_id||a.throw(new Error("No client_id on state")),n.authority||a.throw(new Error("No authority on state")),this._settings.authority!==n.authority&&a.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==n.client_id&&a.throw(new Error("client_id mismatch on settings vs. signin state")),a.debug("state validated"),r.userState=n.data,r.url_state=n.url_state,(s=r.scope)!=null||(r.scope=n.scope),r.error)throw a.warn("Response was error",r.error),new vn(r);n.code_verifier&&!r.code&&a.throw(new Error("Expected code in response"))}async _processClaims(r,n=!1,s=!0){const a=this._logger.create("_processClaims");if(r.profile=this._claimsService.filterProtocolClaims(r.profile),n||!this._settings.loadUserInfo||!r.access_token){a.debug("not loading user info");return}a.debug("loading user info");const c=await this._userInfoService.getClaims(r.access_token);a.debug("user info claims received from user info endpoint"),s&&c.sub!==r.profile.sub&&a.throw(new Error("subject from UserInfo response does not match subject in ID Token")),r.profile=this._claimsService.mergeClaims(r.profile,this._claimsService.filterProtocolClaims(c)),a.debug("user info claims received, updated profile:",r.profile)}async _processCode(r,n,s){const a=this._logger.create("_processCode");if(r.code){a.debug("Validating code");const c=await this._tokenClient.exchangeCode({client_id:n.client_id,client_secret:n.client_secret,code:r.code,redirect_uri:n.redirect_uri,code_verifier:n.code_verifier,extraHeaders:s,...n.extraTokenParams});Object.assign(r,c)}else a.debug("No code to process")}_validateIdTokenAttributes(r,n,s){var a;const c=this._logger.create("_validateIdTokenAttributes");c.debug("decoding ID Token JWT");const f=Ms.decode((a=r.id_token)!=null?a:"");if(f.sub||c.throw(new Error("ID Token is missing a subject claim")),s&&f.nonce!==s&&c.throw(new Error("nonce in id_token does not match nonce in client storage")),n){const p=Ms.decode(n);f.sub!==p.sub&&c.throw(new Error("sub in id_token does not match current sub")),f.auth_time&&f.auth_time!==p.auth_time&&c.throw(new Error("auth_time in id_token does not match original auth_time")),f.azp&&f.azp!==p.azp&&c.throw(new Error("azp in id_token does not match original azp")),!f.azp&&p.azp&&c.throw(new Error("azp not in id_token, but present in original id_token"))}r.profile=f}},pa=class Pu{constructor(n){this.id=n.id||Je.generateUUIDv4(),this.data=n.data,n.created&&n.created>0?this.created=n.created:this.created=gr.getEpochTime(),this.request_type=n.request_type,this.url_state=n.url_state}toStorageString(){return new Se("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(n){return Se.createStatic("State","fromStorageString"),Promise.resolve(new Pu(JSON.parse(n)))}static async clearStaleState(n,s){const a=Se.createStatic("State","clearStaleState"),c=gr.getEpochTime()-s,f=await n.getAllKeys();a.debug("got keys",f);for(let p=0;pY.searchParams.append("resource",ue));for(const[me,ue]of Object.entries({response_mode:y,...L,...Q}))ue!=null&&Y.searchParams.append(me,ue.toString());return new mp({url:Y.href,state:J})}};gp._logger=new Se("SigninRequest");var D_=gp,z_="openid",uu=class{constructor(r){if(this.access_token="",this.token_type="",this.profile={},this.state=r.get("state"),this.session_state=r.get("session_state"),this.state){const n=decodeURIComponent(this.state).split(Ti);this.state=n[0],n.length>1&&(this.url_state=n.slice(1).join(Ti))}this.error=r.get("error"),this.error_description=r.get("error_description"),this.error_uri=r.get("error_uri"),this.code=r.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-gr.getEpochTime()}set expires_in(r){typeof r=="string"&&(r=Number(r)),r!==void 0&&r>=0&&(this.expires_at=Math.floor(r)+gr.getEpochTime())}get isOpenId(){var r;return((r=this.scope)==null?void 0:r.split(" ").includes(z_))||!!this.id_token}},F_=class{constructor({url:r,state_data:n,id_token_hint:s,post_logout_redirect_uri:a,extraQueryParams:c,request_type:f,client_id:p,url_state:v}){if(this._logger=new Se("SignoutRequest"),!r)throw this._logger.error("ctor: No url passed"),new Error("url");const y=new URL(r);if(s&&y.searchParams.append("id_token_hint",s),p&&y.searchParams.append("client_id",p),a&&(y.searchParams.append("post_logout_redirect_uri",a),n||v)){this.state=new pa({data:n,request_type:f,url_state:v});let x=this.state.id;v&&(x=`${x}${Ti}${v}`),y.searchParams.append("state",x)}for(const[x,R]of Object.entries({...c}))R!=null&&y.searchParams.append(x,R.toString());this.url=y.href}},$_=class{constructor(r){if(this.state=r.get("state"),this.state){const n=decodeURIComponent(this.state).split(Ti);this.state=n[0],n.length>1&&(this.url_state=n.slice(1).join(Ti))}this.error=r.get("error"),this.error_description=r.get("error_description"),this.error_uri=r.get("error_uri")}},L_=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],V_=["sub","iss","aud","exp","iat"],q_=class{constructor(r){this._settings=r,this._logger=new Se("ClaimsService")}filterProtocolClaims(r){const n={...r};if(this._settings.filterProtocolClaims){let s;Array.isArray(this._settings.filterProtocolClaims)?s=this._settings.filterProtocolClaims:s=L_;for(const a of s)V_.includes(a)||delete n[a]}return n}mergeClaims(r,n){const s={...r};for(const[a,c]of Object.entries(n))if(s[a]!==c)if(Array.isArray(s[a])||Array.isArray(c))if(this._settings.mergeClaimsStrategy.array=="replace")s[a]=c;else{const f=Array.isArray(s[a])?s[a]:[s[a]];for(const p of Array.isArray(c)?c:[c])f.includes(p)||f.push(p);s[a]=f}else typeof s[a]=="object"&&typeof c=="object"?s[a]=this.mergeClaims(s[a],c):s[a]=c;return s}},yp=class{constructor(r,n){this.keys=r,this.nonce=n}},H_=class{constructor(r,n){this._logger=new Se("OidcClient"),this.settings=r instanceof Nu?r:new Nu(r),this.metadataService=n??new N_(this.settings),this._claimsService=new q_(this.settings),this._validator=new O_(this.settings,this.metadataService,this._claimsService),this._tokenClient=new hp(this.settings,this.metadataService)}async createSigninRequest({state:r,request:n,request_uri:s,request_type:a,id_token_hint:c,login_hint:f,skipUserInfo:p,nonce:v,url_state:y,response_type:x=this.settings.response_type,scope:R=this.settings.scope,redirect_uri:N=this.settings.redirect_uri,prompt:j=this.settings.prompt,display:O=this.settings.display,max_age:q=this.settings.max_age,ui_locales:Q=this.settings.ui_locales,acr_values:$=this.settings.acr_values,resource:fe=this.settings.resource,response_mode:T=this.settings.response_mode,extraQueryParams:A=this.settings.extraQueryParams,extraTokenParams:L=this.settings.extraTokenParams,dpopJkt:J,omitScopeWhenRequesting:Y=this.settings.omitScopeWhenRequesting}){const ge=this._logger.create("createSigninRequest");if(x!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");const me=await this.metadataService.getAuthorizationEndpoint();ge.debug("Received authorization endpoint",me);const ue=await D_.create({url:me,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:N,response_type:x,scope:R,state_data:r,url_state:y,prompt:j,display:O,max_age:q,ui_locales:Q,id_token_hint:c,login_hint:f,acr_values:$,dpopJkt:J,resource:fe,request:n,request_uri:s,extraQueryParams:A,extraTokenParams:L,request_type:a,response_mode:T,client_secret:this.settings.client_secret,skipUserInfo:p,nonce:v,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:Y});await this.clearStaleState();const Re=ue.state;return await this.settings.stateStore.set(Re.id,Re.toStorageString()),ue}async readSigninResponseState(r,n=!1){const s=this._logger.create("readSigninResponseState"),a=new uu(Uu.readParams(r,this.settings.response_mode));if(!a.state)throw s.throw(new Error("No state in response")),null;const c=await this.settings.stateStore[n?"remove":"get"](a.state);if(!c)throw s.throw(new Error("No matching state found in storage")),null;return{state:await pp.fromStorageString(c),response:a}}async processSigninResponse(r,n,s=!0){const a=this._logger.create("processSigninResponse"),{state:c,response:f}=await this.readSigninResponseState(r,s);if(a.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const p=await this.getDpopProof(this.settings.dpop.store);n={...n,DPoP:p}}try{await this._validator.validateSigninResponse(f,c,n)}catch(p){if(p instanceof Ru&&this.settings.dpop){const v=await this.getDpopProof(this.settings.dpop.store,p.nonce);n.DPoP=v,await this._validator.validateSigninResponse(f,c,n)}else throw p}return f}async getDpopProof(r,n){let s,a;return(await r.getAllKeys()).includes(this.settings.client_id)?(a=await r.get(this.settings.client_id),a.nonce!==n&&n&&(a.nonce=n,await r.set(this.settings.client_id,a))):(s=await Je.generateDPoPKeys(),a=new yp(s,n),await r.set(this.settings.client_id,a)),await Je.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:a.keys,nonce:a.nonce})}async processResourceOwnerPasswordCredentials({username:r,password:n,skipUserInfo:s=!1,extraTokenParams:a={}}){const c=await this._tokenClient.exchangeCredentials({username:r,password:n,...a}),f=new uu(new URLSearchParams);return Object.assign(f,c),await this._validator.validateCredentialsResponse(f,s),f}async useRefreshToken({state:r,redirect_uri:n,resource:s,timeoutInSeconds:a,extraHeaders:c,extraTokenParams:f}){var p;const v=this._logger.create("useRefreshToken");let y;if(this.settings.refreshTokenAllowedScope===void 0)y=r.scope;else{const N=this.settings.refreshTokenAllowedScope.split(" ");y=(((p=r.scope)==null?void 0:p.split(" "))||[]).filter(O=>N.includes(O)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const N=await this.getDpopProof(this.settings.dpop.store);c={...c,DPoP:N}}let x;try{x=await this._tokenClient.exchangeRefreshToken({refresh_token:r.refresh_token,scope:y,redirect_uri:n,resource:s,timeoutInSeconds:a,extraHeaders:c,...f})}catch(N){if(N instanceof Ru&&this.settings.dpop)c.DPoP=await this.getDpopProof(this.settings.dpop.store,N.nonce),x=await this._tokenClient.exchangeRefreshToken({refresh_token:r.refresh_token,scope:y,redirect_uri:n,resource:s,timeoutInSeconds:a,extraHeaders:c,...f});else throw N}const R=new uu(new URLSearchParams);return Object.assign(R,x),v.debug("validating response",R),await this._validator.validateRefreshResponse(R,{...r,scope:y}),R}async createSignoutRequest({state:r,id_token_hint:n,client_id:s,request_type:a,url_state:c,post_logout_redirect_uri:f=this.settings.post_logout_redirect_uri,extraQueryParams:p=this.settings.extraQueryParams}={}){const v=this._logger.create("createSignoutRequest"),y=await this.metadataService.getEndSessionEndpoint();if(!y)throw v.throw(new Error("No end session endpoint")),null;v.debug("Received end session endpoint",y),!s&&f&&!n&&(s=this.settings.client_id);const x=new F_({url:y,id_token_hint:n,client_id:s,post_logout_redirect_uri:f,state_data:r,extraQueryParams:p,request_type:a,url_state:c});await this.clearStaleState();const R=x.state;return R&&(v.debug("Signout request has state to persist"),await this.settings.stateStore.set(R.id,R.toStorageString())),x}async readSignoutResponseState(r,n=!1){const s=this._logger.create("readSignoutResponseState"),a=new $_(Uu.readParams(r,this.settings.response_mode));if(!a.state){if(s.debug("No state in response"),a.error)throw s.warn("Response was error:",a.error),new vn(a);return{state:void 0,response:a}}const c=await this.settings.stateStore[n?"remove":"get"](a.state);if(!c)throw s.throw(new Error("No matching state found in storage")),null;return{state:await pa.fromStorageString(c),response:a}}async processSignoutResponse(r){const n=this._logger.create("processSignoutResponse"),{state:s,response:a}=await this.readSignoutResponseState(r,!0);return s?(n.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(a,s)):n.debug("No state from storage; skipping response validation"),a}clearStaleState(){return this._logger.create("clearStaleState"),pa.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(r,n){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:r,token_type_hint:n})}},K_=class{constructor(r){this._userManager=r,this._logger=new Se("SessionMonitor"),this._start=async n=>{const s=n.session_state;if(!s)return;const a=this._logger.create("_start");if(n.profile?(this._sub=n.profile.sub,a.debug("session_state",s,", sub",this._sub)):(this._sub=void 0,a.debug("session_state",s,", anonymous user")),this._checkSessionIFrame){this._checkSessionIFrame.start(s);return}try{const c=await this._userManager.metadataService.getCheckSessionIframe();if(c){a.debug("initializing check session iframe");const f=this._userManager.settings.client_id,p=this._userManager.settings.checkSessionIntervalInSeconds,v=this._userManager.settings.stopCheckSessionOnError,y=new R_(this._callback,f,c,p,v);await y.load(),this._checkSessionIFrame=y,y.start(s)}else a.warn("no check session iframe found in the metadata")}catch(c){a.error("Error from getCheckSessionIframe:",c instanceof Error?c.message:c)}},this._stop=()=>{const n=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const s=setInterval(async()=>{clearInterval(s);try{const a=await this._userManager.querySessionStatus();if(a){const c={session_state:a.session_state,profile:a.sub?{sub:a.sub}:null};this._start(c)}}catch(a){n.error("error from querySessionStatus",a instanceof Error?a.message:a)}},1e3)}},this._callback=async()=>{const n=this._logger.create("_callback");try{const s=await this._userManager.querySessionStatus();let a=!0;s&&this._checkSessionIFrame?s.sub===this._sub?(a=!1,this._checkSessionIFrame.start(s.session_state),n.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",s.session_state),await this._userManager.events._raiseUserSessionChanged()):n.debug("different subject signed into OP",s.sub):n.debug("subject no longer signed into OP"),a?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():n.debug("no change in session detected, no event to raise")}catch(s){this._sub&&(n.debug("Error calling queryCurrentSigninSession; raising signed out event",s),await this._userManager.events._raiseUserSignedOut())}},r||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(n=>{this._logger.error(n)})}async _init(){this._logger.create("_init");const r=await this._userManager.getUser();if(r)this._start(r);else if(this._userManager.settings.monitorAnonymousSession){const n=await this._userManager.querySessionStatus();if(n){const s={session_state:n.session_state,profile:n.sub?{sub:n.sub}:null};this._start(s)}}}},cu=class wp{constructor(n){var s;this.id_token=n.id_token,this.session_state=(s=n.session_state)!=null?s:null,this.access_token=n.access_token,this.refresh_token=n.refresh_token,this.token_type=n.token_type,this.scope=n.scope,this.profile=n.profile,this.expires_at=n.expires_at,this.state=n.userState,this.url_state=n.url_state}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-gr.getEpochTime()}set expires_in(n){n!==void 0&&(this.expires_at=Math.floor(n)+gr.getEpochTime())}get expired(){const n=this.expires_in;if(n!==void 0)return n<=0}get scopes(){var n,s;return(s=(n=this.scope)==null?void 0:n.split(" "))!=null?s:[]}toStorageString(){return new Se("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(n){return Se.createStatic("User","fromStorageString"),new wp(JSON.parse(n))}},fh="oidc-client",vp=class{constructor(){this._abort=new Or("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(r){const n=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");n.debug("setting URL in window"),this._window.location.replace(r.url);const{url:s,keepOpen:a}=await new Promise((c,f)=>{const p=y=>{var x;const R=y.data,N=(x=r.scriptOrigin)!=null?x:window.location.origin;if(!(y.origin!==N||R?.source!==fh)){try{const j=Uu.readParams(R.url,r.response_mode).get("state");if(j||n.warn("no state found in response url"),y.source!==this._window&&j!==r.state)return}catch{this._dispose(),f(new Error("Invalid response from window"))}c(R)}};window.addEventListener("message",p,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",p,!1));const v=new BroadcastChannel(`oidc-client-popup-${r.state}`);v.addEventListener("message",p,!1),this._disposeHandlers.add(()=>v.close()),this._disposeHandlers.add(this._abort.addHandler(y=>{this._dispose(),f(y)}))});return n.debug("got response from window"),this._dispose(),a||this.close(),{url:s}}_dispose(){this._logger.create("_dispose");for(const r of this._disposeHandlers)r();this._disposeHandlers.clear()}static _notifyParent(r,n,s=!1,a=window.location.origin){const c={source:fh,url:n,keepOpen:s},f=new Se("_notifyParent");if(r)f.debug("With parent. Using parent.postMessage."),r.postMessage(c,a);else{f.debug("No parent. Using BroadcastChannel.");const p=new URL(n).searchParams.get("state");if(!p)throw new Error("No parent and no state in URL. Can't complete notification.");const v=new BroadcastChannel(`oidc-client-popup-${p}`);v.postMessage(c),v.close()}}},_p={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Sp="_blank",W_=60,Q_=2,xp=10,J_=class extends Nu{constructor(r){const{popup_redirect_uri:n=r.redirect_uri,popup_post_logout_redirect_uri:s=r.post_logout_redirect_uri,popupWindowFeatures:a=_p,popupWindowTarget:c=Sp,redirectMethod:f="assign",redirectTarget:p="self",iframeNotifyParentOrigin:v=r.iframeNotifyParentOrigin,iframeScriptOrigin:y=r.iframeScriptOrigin,requestTimeoutInSeconds:x,silent_redirect_uri:R=r.redirect_uri,silentRequestTimeoutInSeconds:N,automaticSilentRenew:j=!0,validateSubOnSilentRenew:O=!0,includeIdTokenInSilentRenew:q=!1,monitorSession:Q=!1,monitorAnonymousSession:$=!1,checkSessionIntervalInSeconds:fe=Q_,query_status_response_type:T="code",stopCheckSessionOnError:A=!0,revokeTokenTypes:L=["access_token","refresh_token"],revokeTokensOnSignout:J=!1,includeIdTokenInSilentSignout:Y=!1,accessTokenExpiringNotificationTimeInSeconds:ge=W_,maxSilentRenewTimeoutRetries:me,userStore:ue}=r;if(super(r),this.popup_redirect_uri=n,this.popup_post_logout_redirect_uri=s,this.popupWindowFeatures=a,this.popupWindowTarget=c,this.redirectMethod=f,this.redirectTarget=p,this.iframeNotifyParentOrigin=v,this.iframeScriptOrigin=y,this.silent_redirect_uri=R,this.silentRequestTimeoutInSeconds=N||x||xp,this.automaticSilentRenew=j,this.validateSubOnSilentRenew=O,this.includeIdTokenInSilentRenew=q,this.monitorSession=Q,this.monitorAnonymousSession=$,this.checkSessionIntervalInSeconds=fe,this.stopCheckSessionOnError=A,this.query_status_response_type=T,this.revokeTokenTypes=L,this.revokeTokensOnSignout=J,this.includeIdTokenInSilentSignout=Y,this.accessTokenExpiringNotificationTimeInSeconds=ge,this.maxSilentRenewTimeoutRetries=me,ue)this.userStore=ue;else{const Re=typeof window<"u"?window.sessionStorage:new dp;this.userStore=new fp({store:Re})}}},hh=class Ip extends vp{constructor({silentRequestTimeoutInSeconds:n=xp}){super(),this._logger=new Se("IFrameWindow"),this._timeoutInSeconds=n,this._frame=Ip.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const n=window.document.createElement("iframe");return n.style.visibility="hidden",n.style.position="fixed",n.style.left="-1000px",n.style.top="0",n.width="0",n.height="0",window.document.body.appendChild(n),n}async navigate(n){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const s=setTimeout(()=>{this._abort.raise(new Vu("IFrame timed out without a response"))},this._timeoutInSeconds*1e3);return this._disposeHandlers.add(()=>clearTimeout(s)),await super.navigate(n)}close(){var n;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",s=>{var a;const c=s.target;(a=c.parentNode)==null||a.removeChild(c),this._abort.raise(new Error("IFrame removed from DOM"))},!0),(n=this._frame.contentWindow)==null||n.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(n,s){return super._notifyParent(window.parent,n,!1,s)}},G_=class{constructor(r){this._settings=r,this._logger=new Se("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:r=this._settings.silentRequestTimeoutInSeconds}){return new hh({silentRequestTimeoutInSeconds:r})}async callback(r){this._logger.create("callback"),hh.notifyParent(r,this._settings.iframeNotifyParentOrigin)}},X_=500,Y_=1e3,ph=class extends vp{constructor({popupWindowTarget:r=Sp,popupWindowFeatures:n={},popupSignal:s,popupAbortOnClose:a}){super(),this._logger=new Se("PopupWindow");const c=dh.center({..._p,...n});this._window=window.open(void 0,r,dh.serialize(c)),this.abortOnClose=!!a,s&&s.addEventListener("abort",()=>{var f;this._abort.raise(new Error((f=s.reason)!=null?f:"Popup aborted"))}),n.closePopupWindowAfterInSeconds&&n.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{if(!this._window||typeof this._window.closed!="boolean"||this._window.closed){this._abort.raise(new Error("Popup blocked by user"));return}this.close()},n.closePopupWindowAfterInSeconds*Y_)}async navigate(r){var n;(n=this._window)==null||n.focus();const s=setInterval(()=>{(!this._window||this._window.closed)&&(this._logger.debug("Popup closed by user or isolated by redirect"),a(),this._disposeHandlers.delete(a),this.abortOnClose&&this._abort.raise(new Error("Popup closed by user")))},X_),a=()=>clearInterval(s);return this._disposeHandlers.add(a),await super.navigate(r)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(r,n){super._notifyParent(window.opener,r,n),!n&&!window.opener&&window.close()}},Z_=class{constructor(r){this._settings=r,this._logger=new Se("PopupNavigator")}async prepare({popupWindowFeatures:r=this._settings.popupWindowFeatures,popupWindowTarget:n=this._settings.popupWindowTarget,popupSignal:s,popupAbortOnClose:a}){return new ph({popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s,popupAbortOnClose:a})}async callback(r,{keepOpen:n=!1}){this._logger.create("callback"),ph.notifyOpener(r,n)}},eS=class{constructor(r){this._settings=r,this._logger=new Se("RedirectNavigator")}async prepare({redirectMethod:r=this._settings.redirectMethod,redirectTarget:n=this._settings.redirectTarget}){var s;this._logger.create("prepare");let a=window.self;n==="top"&&(a=(s=window.top)!=null?s:window.self);const c=a.location[r].bind(a.location);let f;return{navigate:async p=>(this._logger.create("navigate"),await new Promise((y,x)=>{f=x,window.addEventListener("pageshow",()=>y(window.location.href)),c(p.url)})),close:()=>{this._logger.create("close"),f?.(new Error("Redirect aborted")),a.stop()}}}async callback(){}},tS=class extends U_{constructor(r){super({expiringNotificationTimeInSeconds:r.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new Se("UserManagerEvents"),this._userLoaded=new Or("User loaded"),this._userUnloaded=new Or("User unloaded"),this._silentRenewError=new Or("Silent renew error"),this._userSignedIn=new Or("User signed in"),this._userSignedOut=new Or("User signed out"),this._userSessionChanged=new Or("User session changed")}async load(r,n=!0){await super.load(r),n&&await this._userLoaded.raise(r)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(r){return this._userLoaded.addHandler(r)}removeUserLoaded(r){return this._userLoaded.removeHandler(r)}addUserUnloaded(r){return this._userUnloaded.addHandler(r)}removeUserUnloaded(r){return this._userUnloaded.removeHandler(r)}addSilentRenewError(r){return this._silentRenewError.addHandler(r)}removeSilentRenewError(r){return this._silentRenewError.removeHandler(r)}async _raiseSilentRenewError(r){await this._silentRenewError.raise(r)}addUserSignedIn(r){return this._userSignedIn.addHandler(r)}removeUserSignedIn(r){this._userSignedIn.removeHandler(r)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(r){return this._userSignedOut.addHandler(r)}removeUserSignedOut(r){this._userSignedOut.removeHandler(r)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(r){return this._userSessionChanged.addHandler(r)}removeUserSessionChanged(r){this._userSessionChanged.removeHandler(r)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},rS=class{constructor(r){this._userManager=r,this._logger=new Se("SilentRenewService"),this._isStarted=!1,this._retryTimer=new gr("Retry Silent Renew"),this._timeoutRetryCount=0,this._tokenExpiring=async()=>{const n=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),this._timeoutRetryCount=0,n.debug("silent token renewal successful")}catch(s){if(s instanceof Vu){this._timeoutRetryCount++;const a=this._userManager.settings.maxSilentRenewTimeoutRetries;if(a!==void 0&&this._timeoutRetryCount>a){n.error(`Timeout retry limit reached (${this._timeoutRetryCount} > ${a}), raising silentRenewError:`,s),this._timeoutRetryCount=0,await this._userManager.events._raiseSilentRenewError(s);return}n.warn(`ErrorTimeout from signinSilent (attempt ${this._timeoutRetryCount}), retry in 5s:`,s),this._retryTimer.init(5);return}n.error("Error from signinSilent:",s),this._timeoutRetryCount=0,await this._userManager.events._raiseSilentRenewError(s)}}}async start(){const r=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(n){r.error("getUser error",n)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},nS=class{constructor(r){this.refresh_token=r.refresh_token,this.id_token=r.id_token,this.session_state=r.session_state,this.scope=r.scope,this.profile=r.profile,this.data=r.state}},iS=class{constructor(r,n,s,a){this._logger=new Se("UserManager"),this.settings=new J_(r),this._client=new H_(r),this._redirectNavigator=n??new eS(this.settings),this._popupNavigator=s??new Z_(this.settings),this._iframeNavigator=a??new G_(this.settings),this._events=new tS(this.settings),this._silentRenewService=new rS(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new K_(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(r=!1){const n=this._logger.create("getUser"),s=await this._loadUser();return s?(n.info("user loaded"),await this._events.load(s,r),s):(n.info("user not found in storage"),null)}async removeUser(){const r=this._logger.create("removeUser");await this.storeUser(null),r.info("user removed from storage"),await this._events.unload()}async signinRedirect(r={}){var n;this._logger.create("signinRedirect");const{redirectMethod:s,...a}=r;let c;(n=this.settings.dpop)!=null&&n.bind_authorization_code&&(c=await this.generateDPoPJkt(this.settings.dpop));const f=await this._redirectNavigator.prepare({redirectMethod:s});await this._signinStart({request_type:"si:r",dpopJkt:c,...a},f)}async signinRedirectCallback(r=window.location.href){const n=this._logger.create("signinRedirectCallback"),s=await this._signinEnd(r);return s.profile&&s.profile.sub?n.info("success, signed in subject",s.profile.sub):n.info("no subject"),s}async signinResourceOwnerCredentials({username:r,password:n,skipUserInfo:s=!1}){const a=this._logger.create("signinResourceOwnerCredential"),c=await this._client.processResourceOwnerPasswordCredentials({username:r,password:n,skipUserInfo:s,extraTokenParams:this.settings.extraTokenParams});a.debug("got signin response");const f=await this._buildUser(c);return f.profile&&f.profile.sub?a.info("success, signed in subject",f.profile.sub):a.info("no subject"),f}async signinPopup(r={}){var n;const s=this._logger.create("signinPopup");let a;(n=this.settings.dpop)!=null&&n.bind_authorization_code&&(a=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:c,popupWindowTarget:f,popupSignal:p,popupAbortOnClose:v,...y}=r,x=this.settings.popup_redirect_uri;x||s.throw(new Error("No popup_redirect_uri configured"));const R=await this._popupNavigator.prepare({popupWindowFeatures:c,popupWindowTarget:f,popupSignal:p,popupAbortOnClose:v}),N=await this._signin({request_type:"si:p",redirect_uri:x,display:"popup",dpopJkt:a,...y},R);return N&&(N.profile&&N.profile.sub?s.info("success, signed in subject",N.profile.sub):s.info("no subject")),N}async signinPopupCallback(r=window.location.href,n=!1){const s=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(r,{keepOpen:n}),s.info("success")}async signinSilent(r={}){var n,s;const a=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:c,...f}=r;let p=await this._loadUser();if(!r.forceIframeAuth&&p?.refresh_token){a.debug("using refresh token");const N=new nS(p);return await this._useRefreshToken({state:N,redirect_uri:f.redirect_uri,resource:f.resource,extraTokenParams:f.extraTokenParams,timeoutInSeconds:c})}let v;(n=this.settings.dpop)!=null&&n.bind_authorization_code&&(v=await this.generateDPoPJkt(this.settings.dpop));const y=this.settings.silent_redirect_uri;y||a.throw(new Error("No silent_redirect_uri configured"));let x;p&&this.settings.validateSubOnSilentRenew&&(a.debug("subject prior to silent renew:",p.profile.sub),x=p.profile.sub);const R=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:c});return p=await this._signin({request_type:"si:s",redirect_uri:y,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?p?.id_token:void 0,dpopJkt:v,...f},R,x),p&&((s=p.profile)!=null&&s.sub?a.info("success, signed in subject",p.profile.sub):a.info("no subject")),p}async _useRefreshToken(r){const n=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...r}),s=new cu({...r.state,...n});return await this.storeUser(s),await this._events.load(s),s}async signinSilentCallback(r=window.location.href){const n=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(r),n.info("success")}async signinCallback(r=window.location.href){const{state:n}=await this._client.readSigninResponseState(r);switch(n.request_type){case"si:r":return await this.signinRedirectCallback(r);case"si:p":await this.signinPopupCallback(r);break;case"si:s":await this.signinSilentCallback(r);break;default:throw new Error("invalid request_type in state")}}async signoutCallback(r=window.location.href,n=!1){const{state:s}=await this._client.readSignoutResponseState(r);if(s)switch(s.request_type){case"so:r":return await this.signoutRedirectCallback(r);case"so:p":await this.signoutPopupCallback(r,n);break;case"so:s":await this.signoutSilentCallback(r);break;default:throw new Error("invalid request_type in state")}}async querySessionStatus(r={}){const n=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:s,...a}=r,c=this.settings.silent_redirect_uri;c||n.throw(new Error("No silent_redirect_uri configured"));const f=await this._loadUser(),p=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s}),v=await this._signinStart({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?f?.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...a},p);try{const y={},x=await this._client.processSigninResponse(v.url,y);return n.debug("got signin response"),x.session_state&&x.profile.sub?(n.info("success for subject",x.profile.sub),{session_state:x.session_state,sub:x.profile.sub}):(n.info("success, user not authenticated"),null)}catch(y){if(this.settings.monitorAnonymousSession&&y instanceof vn)switch(y.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return n.info("success for anonymous user"),{session_state:y.session_state}}throw y}}async _signin(r,n,s){const a=await this._signinStart(r,n);return await this._signinEnd(a.url,s)}async _signinStart(r,n){const s=this._logger.create("_signinStart");try{const a=await this._client.createSigninRequest(r);return s.debug("got signin request"),await n.navigate({url:a.url,state:a.state.id,response_mode:a.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(a){throw s.debug("error after preparing navigator, closing navigator window"),n.close(),a}}async _signinEnd(r,n){const s=this._logger.create("_signinEnd"),a={},c=await this._client.processSigninResponse(r,a);return s.debug("got signin response"),await this._buildUser(c,n)}async _buildUser(r,n){const s=this._logger.create("_buildUser"),a=new cu(r);if(n){if(n!==a.profile.sub)throw s.debug("current user does not match user returned from signin. sub from signin:",a.profile.sub),new vn({...r,error:"login_required"});s.debug("current user matches user returned from signin")}return await this.storeUser(a),s.debug("user stored"),await this._events.load(a),a}async signoutRedirect(r={}){const n=this._logger.create("signoutRedirect"),{redirectMethod:s,...a}=r,c=await this._redirectNavigator.prepare({redirectMethod:s});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...a},c),n.info("success")}async signoutRedirectCallback(r=window.location.href){const n=this._logger.create("signoutRedirectCallback"),s=await this._signoutEnd(r);return n.info("success"),s}async signoutPopup(r={}){const n=this._logger.create("signoutPopup"),{popupWindowFeatures:s,popupWindowTarget:a,popupSignal:c,...f}=r,p=this.settings.popup_post_logout_redirect_uri,v=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:a,popupSignal:c});await this._signout({request_type:"so:p",post_logout_redirect_uri:p,state:p==null?void 0:{},...f},v),n.info("success")}async signoutPopupCallback(r=window.location.href,n=!1){const s=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(r,{keepOpen:n}),s.info("success")}async _signout(r,n){const s=await this._signoutStart(r,n);return await this._signoutEnd(s.url)}async _signoutStart(r={},n){var s;const a=this._logger.create("_signoutStart");try{const c=await this._loadUser();a.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(c);const f=r.id_token_hint||c&&c.id_token;f&&(a.debug("setting id_token_hint in signout request"),r.id_token_hint=f),await this.removeUser(),a.debug("user removed, creating signout request");const p=await this._client.createSignoutRequest(r);return a.debug("got signout request"),await n.navigate({url:p.url,state:(s=p.state)==null?void 0:s.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(c){throw a.debug("error after preparing navigator, closing navigator window"),n.close(),c}}async _signoutEnd(r){const n=this._logger.create("_signoutEnd"),s=await this._client.processSignoutResponse(r);return n.debug("got signout response"),s}async signoutSilent(r={}){var n;const s=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:a,...c}=r,f=this.settings.includeIdTokenInSilentSignout?(n=await this._loadUser())==null?void 0:n.id_token:void 0,p=this.settings.popup_post_logout_redirect_uri,v=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:a});await this._signout({request_type:"so:s",post_logout_redirect_uri:p,id_token_hint:f,...c},v),s.info("success")}async signoutSilentCallback(r=window.location.href){const n=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(r),n.info("success")}async revokeTokens(r){const n=await this._loadUser();await this._revokeInternal(n,r)}async _revokeInternal(r,n=this.settings.revokeTokenTypes){const s=this._logger.create("_revokeInternal");if(!r)return;const a=n.filter(c=>typeof r[c]=="string");if(!a.length){s.debug("no need to revoke due to no token(s)");return}for(const c of a)await this._client.revokeToken(r[c],c),s.info(`${c} revoked successfully`),c!=="access_token"&&(r[c]=null);await this.storeUser(r),s.debug("user stored"),await this._events.load(r)}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const r=this._logger.create("_loadUser"),n=await this.settings.userStore.get(this._userStoreKey);return n?(r.debug("user storageString loaded"),cu.fromStorageString(n)):(r.debug("no user storageString"),null)}async storeUser(r){const n=this._logger.create("storeUser");if(r){n.debug("storing user");const s=r.toStorageString();await this.settings.userStore.set(this._userStoreKey,s)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(r,n,s,a){var c,f;const p=await((f=(c=this.settings.dpop)==null?void 0:c.store)==null?void 0:f.get(this.settings.client_id));if(p)return await Je.generateDPoPProof({url:r,accessToken:n?.access_token,httpMethod:s,keyPair:p.keys,nonce:a})}async generateDPoPJkt(r){let n=await r.store.get(this.settings.client_id);if(!n){const s=await Je.generateDPoPKeys();n=new yp(s),await r.store.set(this.settings.client_id,n)}return await Je.generateDPoPJkt(n.keys)}},Hu=Tt.createContext(void 0);Hu.displayName="AuthContext";var sS={isLoading:!0,isAuthenticated:!1},oS=(r,n)=>{switch(n.type){case"INITIALISED":case"USER_LOADED":return{...r,user:n.user,isLoading:!1,isAuthenticated:n.user?!n.user.expired:!1,error:void 0};case"USER_SIGNED_OUT":case"USER_UNLOADED":return{...r,user:void 0,isAuthenticated:!1};case"NAVIGATOR_INIT":return{...r,isLoading:!0,activeNavigator:n.method};case"NAVIGATOR_CLOSE":return{...r,isLoading:!1,activeNavigator:void 0};case"ERROR":{const s=n.error;return s.toString=()=>`${s.name}: ${s.message}`,{...r,isLoading:!1,error:s}}default:{const s=new TypeError(`unknown type ${n.type}`),a={name:s.name,message:s.message,innerError:s,stack:s.stack,source:"unknown"};return a.toString=()=>`${a.name}: ${a.message}`,{...r,isLoading:!1,error:a}}}},aS=(r=window.location)=>{let n=new URLSearchParams(r.search);return!!((n.get("code")||n.get("error"))&&n.get("state")||(n=new URLSearchParams(r.hash.replace("#","?")),(n.get("code")||n.get("error"))&&n.get("state")))},lS=Ku("signinCallback","Sign-in failed"),uS=Ku("signoutCallback","Sign-out failed"),cS=Ku("renewSilent","Renew silent failed");function kp(r,n){return{name:du(r,"name",()=>"Error"),message:du(r,"message",()=>n),stack:du(r,"stack",()=>new Error().stack),innerError:r}}function Ku(r,n){return s=>({...kp(s,n),source:r})}function du(r,n,s){if(r&&typeof r=="object"){const a=r[n];if(typeof a=="string")return a}return s()}var dS=["clearStaleState","querySessionStatus","revokeTokens","startSilentRenew","stopSilentRenew"],fS=["signinPopup","signinSilent","signinRedirect","signinResourceOwnerCredentials","signoutPopup","signoutRedirect","signoutSilent"],gh=r=>()=>{throw new Error(`UserManager#${r} was called from an unsupported context. If this is a server-rendered page, defer this call with useEffect() or pass a custom UserManager implementation.`)},mh=typeof window>"u"?null:iS,hS=r=>{const{children:n,onSigninCallback:s,skipSigninCallback:a,matchSignoutCallback:c,onSignoutCallback:f,onRemoveUser:p,userManager:v=null,...y}=r,[x]=Tt.useState(()=>v??(mh?new mh(y):{settings:y})),[R,N]=Tt.useReducer(oS,sS),j=Tt.useMemo(()=>Object.assign({settings:x.settings,events:x.events},Object.fromEntries(dS.map($=>{var fe,T;return[$,(T=(fe=x[$])==null?void 0:fe.bind(x))!=null?T:gh($)]})),Object.fromEntries(fS.map($=>[$,x[$]?async fe=>{N({type:"NAVIGATOR_INIT",method:$});try{return await x[$](fe)}catch(T){return N({type:"ERROR",error:{...kp(T,`Unknown error while executing ${$}(...).`),source:$,args:fe}}),null}finally{N({type:"NAVIGATOR_CLOSE"})}}:gh($)]))),[x]),O=Tt.useRef(!1);Tt.useEffect(()=>{!x||O.current||(O.current=!0,(async()=>{try{let $=null;aS()&&!a&&($=await x.signinCallback(),s&&await s($)),$=$||await x.getUser(),N({type:"INITIALISED",user:$})}catch($){N({type:"ERROR",error:lS($)})}try{if(c&&c(x.settings)){const $=await x.signoutCallback();f&&await f($)}}catch($){N({type:"ERROR",error:uS($)})}})())},[x,a,s,f,c]),Tt.useEffect(()=>{if(!x)return;const $=L=>{N({type:"USER_LOADED",user:L})};x.events.addUserLoaded($);const fe=()=>{N({type:"USER_UNLOADED"})};x.events.addUserUnloaded(fe);const T=()=>{N({type:"USER_SIGNED_OUT"})};x.events.addUserSignedOut(T);const A=L=>{N({type:"ERROR",error:cS(L)})};return x.events.addSilentRenewError(A),()=>{x.events.removeUserLoaded($),x.events.removeUserUnloaded(fe),x.events.removeUserSignedOut(T),x.events.removeSilentRenewError(A)}},[x]);const q=Tt.useCallback(async()=>{await x.removeUser(),p&&await p()},[x,p]),Q=Tt.useMemo(()=>({...R,...j,removeUser:q}),[R,j,q]);return Tt.createElement(Hu.Provider,{value:Q},n)},bp=()=>{const r=Tt.useContext(Hu);return r||console.warn("AuthProvider context is undefined, please verify you are calling useAuth() as child of a component."),r};function pS(){const{identity:r,isActive:n}=Lu(),s=bp(),[a,c]=ae.useState(null),[f,p]=ae.useState(null),[v,y]=ae.useState(null),[x,R]=ae.useState(""),[N,j]=ae.useState(""),[O,q]=ae.useState(!1),[Q,$]=ae.useState(""),[fe,T]=ae.useState(!1),[A,L]=ae.useState(""),[J,Y]=ae.useState(!1),[ge,me]=ae.useState(!1),[ue,Re]=ae.useState(""),[We,Le]=ae.useState("oidc"),[Me,it]=ae.useState(""),[ke,P]=ae.useState(""),[W,M]=ae.useState(""),H=Tt.useRef(null),z=Tt.useRef(null),w=hr(fr.setName),E=hr(fr.createServer),ee=hr(fr.createChannel),ne=hr(fr.createThread),te=hr(fr.sendMessage),le=hr(fr.register),ie=hr(fr.login),he=hr(fr.joinVoice),we=hr(fr.leaveVoice),[_e]=pi(fi.server),[Ne]=pi(fi.channel),[Ge,Dt]=pi(fi.user),[mr]=pi(fi.message),[Dr]=pi(fi.thread),[Sn]=pi(fi.voice_state);ae.useEffect(()=>{!a&&_e.length>0&&c(_e[0].id)},[_e,a]),ae.useEffect(()=>{if(a){const B=Ne.filter(ye=>ye.serverId===a&&ye.kind.tag==="Text");B.length>0&&(!f||!Ne.some(ye=>ye.id===f&&ye.serverId===a))&&p(B[0].id)}},[a,Ne]);const zr=ae.useMemo(()=>_e.find(B=>B.id===a),[_e,a]),Ui=ae.useMemo(()=>Ne.find(B=>B.id===f),[Ne,f]),Ri=ae.useMemo(()=>Dr.find(B=>B.id===v),[Dr,v]),Fr=ae.useMemo(()=>a?Ne.filter(B=>B.serverId===a&&B.kind.tag==="Text"):[],[Ne,a]),yr=ae.useMemo(()=>a?Ne.filter(B=>B.serverId===a&&B.kind.tag==="Voice"):[],[Ne,a]),xn=ae.useMemo(()=>f?mr.filter(B=>B.channelId===f&&B.threadId===void 0).sort((B,ye)=>B.sent.microsSinceUnixEpochv?mr.filter(B=>B.threadId===v).sort((B,ye)=>B.sent.microsSinceUnixEpochGe.find(B=>B.identity.isEqual(r||Bs.zero())),[Ge,r]),In=ae.useMemo(()=>Sn.find(B=>B.identity.isEqual(r||Bs.zero())),[Sn,r]),Pi=ae.useMemo(()=>Ne.find(B=>B.id===In?.channelId),[Ne,In]),kn=ae.useMemo(()=>Ge.filter(B=>B.online),[Ge]),xt=ae.useMemo(()=>{if(!St)return!1;const B=!!(St.issuer&&St.subject),ye=!!(St.username&&St.password);return B||ye},[St]);ae.useEffect(()=>{H.current?.scrollIntoView({behavior:"smooth"})},[xn]),ae.useEffect(()=>{z.current?.scrollIntoView({behavior:"smooth"})},[Ni]);const js=B=>{B.preventDefault(),!(!x.trim()||!f)&&(te({text:x,channelId:f,threadId:void 0}),R(""))},$r=B=>{B.preventDefault(),!(!N.trim()||!v||!f)&&(te({text:N,channelId:f,threadId:v}),j(""))},Lr=B=>{B.preventDefault(),Q.trim()&&(E({name:Q}),$(""),q(!1))},ya=B=>{B.preventDefault(),!(!A.trim()||!a)&&(ee({name:A,serverId:a,isVoice:J}),L(""),Y(!1),T(!1))},Os=B=>{B.preventDefault(),ue.trim()&&(w({name:ue}),me(!1))},Ds=B=>{const ye=`Thread on: ${B.text.substring(0,20)}...`;ne({name:ye,channelId:B.channelId,parentMessageId:B.id})},wa=B=>{B.preventDefault(),M(""),ie({username:Me,password:ke}).catch(ye=>M(ye.message||"Login failed"))},Bi=B=>{B.preventDefault(),M(""),le({username:Me,password:ke}).then(()=>{Le("login"),M("Registration successful! Please log in.")}).catch(ye=>M(ye.message||"Registration failed"))},Ai=B=>{he({channelId:B})};if(s.isLoading)return b.jsx("div",{className:"login-screen",children:b.jsxs("div",{className:"login-card",children:[b.jsx("h1",{children:"Loading Authentication..."}),b.jsx("p",{children:"Please wait while we prepare your session."})]})});if(!n||!r)return b.jsx("div",{className:"login-screen",children:b.jsxs("div",{className:"login-card",children:[b.jsx("h1",{children:"Connecting..."}),b.jsx("p",{children:"Establishing connection to SpacetimeDB server."}),b.jsx("div",{className:"avatar",style:{width:"48px",height:"48px",fontSize:"1.2rem"},children:"..."})]})});if(!Dt)return b.jsx("div",{className:"login-screen",children:b.jsxs("div",{className:"login-card",children:[b.jsx("h1",{children:"Loading User Data..."}),b.jsx("p",{children:"Fetching your profile from the server."}),b.jsx("div",{className:"avatar",style:{width:"48px",height:"48px",fontSize:"1.2rem"},children:"..."})]})});if(!(s.isAuthenticated||xt))return b.jsx("div",{className:"login-screen",children:b.jsxs("div",{className:"login-card",children:[b.jsx("h1",{children:"Welcome to Spacetime Discord"}),b.jsx("p",{style:{marginBottom:"10px"},children:"Authentication is required to enter the community."}),b.jsxs("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:"20px"},children:[b.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[b.jsx("h3",{style:{margin:0,fontSize:"0.9rem",color:"var(--text-muted)"},children:"FAST TRACK"}),b.jsxs("button",{className:"btn-primary",style:{width:"100%",display:"flex",alignItems:"center",justifyContent:"center",gap:"10px"},onClick:()=>s.signinRedirect(),children:[b.jsx("span",{style:{fontSize:"1.2rem"},children:"🌐"})," Log In with OIDC"]})]}),b.jsxs("div",{style:{display:"flex",alignItems:"center",width:"100%",gap:"10px"},children:[b.jsx("div",{style:{flex:1,height:"1px",backgroundColor:"var(--background-accent)"}}),b.jsx("span",{style:{fontSize:"0.8rem",color:"var(--text-muted)"},children:"OR USE CREDENTIALS"}),b.jsx("div",{style:{flex:1,height:"1px",backgroundColor:"var(--background-accent)"}})]}),b.jsxs("form",{onSubmit:We==="register"?Bi:wa,style:{width:"100%",display:"flex",flexDirection:"column",gap:"16px"},children:[b.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[b.jsx("label",{style:{fontSize:"0.8rem",fontWeight:"bold",color:"var(--text-muted)"},children:"USERNAME"}),b.jsx("input",{autoFocus:!0,className:"chat-input",style:{backgroundColor:"var(--background-tertiary)",borderRadius:"4px",padding:"10px"},value:Me,onChange:B=>it(B.target.value)})]}),b.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[b.jsx("label",{style:{fontSize:"0.8rem",fontWeight:"bold",color:"var(--text-muted)"},children:"PASSWORD"}),b.jsx("input",{type:"password",className:"chat-input",style:{backgroundColor:"var(--background-tertiary)",borderRadius:"4px",padding:"10px"},value:ke,onChange:B=>P(B.target.value)})]}),W&&b.jsx("div",{style:{color:"#da373c",fontSize:"0.85rem",textAlign:"center"},children:W}),b.jsx("button",{type:"submit",className:"btn-secondary",style:{width:"100%",backgroundColor:"var(--background-accent)"},children:We==="register"?"Create Account":"Log In"}),b.jsxs("div",{style:{fontSize:"0.9rem",color:"var(--text-muted)",textAlign:"center"},children:[We==="login"?"Need an account? ":"Already have an account? ",b.jsx("span",{style:{color:"var(--brand)",cursor:"pointer",fontWeight:"bold"},onClick:()=>{Le(We==="login"?"register":"login"),M("")},children:We==="login"?"Register":"Log In"})]})]})]})]})});const Et=B=>Ge.find(bn=>bn.identity.isEqual(B))?.name||B.toHexString().substring(0,8),Mi=B=>new Date(Number(B.microsSinceUnixEpoch/1000n)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return b.jsxs("div",{className:"app-container",children:[b.jsxs("div",{className:"server-sidebar",children:[_e.map(B=>b.jsx("div",{className:`server-icon ${a===B.id?"active":""}`,onClick:()=>{c(B.id),y(null)},title:B.name,children:B.name.substring(0,2).toUpperCase()},B.id.toString())),b.jsx("div",{className:"server-icon",onClick:()=>q(!0),children:"+"})]}),b.jsxs("div",{className:"channel-sidebar",children:[b.jsxs("div",{className:"channel-header",style:{justifyContent:"space-between"},children:[b.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:zr?.name||"No Server Selected"}),zr&&b.jsx("button",{className:"add-btn",onClick:()=>T(!0),children:"+"})]}),b.jsxs("div",{className:"channel-list",children:[b.jsx("div",{style:{fontSize:"0.7rem",fontWeight:"bold",color:"var(--text-muted)",padding:"8px 8px 4px 8px"},children:"TEXT CHANNELS"}),Fr.map(B=>b.jsxs("div",{className:`channel-item ${f===B.id?"active":""}`,onClick:()=>{p(B.id),y(null)},children:[b.jsx("span",{className:"channel-item-hash",children:"#"}),B.name]},B.id.toString())),b.jsx("div",{style:{fontSize:"0.7rem",fontWeight:"bold",color:"var(--text-muted)",padding:"16px 8px 4px 8px"},children:"VOICE CHANNELS"}),yr.map(B=>b.jsxs("div",{children:[b.jsxs("div",{className:`channel-item ${In?.channelId===B.id?"active":""}`,onClick:()=>Ai(B.id),children:[b.jsx("span",{className:"channel-item-hash",children:"🔊"}),B.name]}),b.jsx("div",{style:{marginLeft:"24px",display:"flex",flexDirection:"column",gap:"4px",marginBottom:"8px"},children:Sn.filter(ye=>ye.channelId===B.id).map(ye=>b.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontSize:"0.85rem",color:"var(--text-muted)"},children:[b.jsx("div",{className:"avatar",style:{width:"18px",height:"18px",fontSize:"0.5rem"},children:Et(ye.identity).substring(0,2).toUpperCase()}),Et(ye.identity)]},ye.identity.toHexString()))})]},B.id.toString()))]}),Pi&&b.jsxs("div",{style:{backgroundColor:"#232428",borderBottom:"1px solid rgba(255,255,255,0.05)",padding:"10px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[b.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[b.jsx("span",{style:{color:"#23a559",fontSize:"0.8rem",fontWeight:"bold"},children:"Voice Connected"}),b.jsxs("span",{style:{color:"var(--text-muted)",fontSize:"0.75rem"},children:[Pi.name," / ",zr?.name]})]}),b.jsx("button",{className:"add-btn",style:{color:"#da373c"},onClick:()=>we(),children:"📞"})]}),b.jsxs("div",{className:"user-profile",children:[b.jsx("div",{className:"avatar",children:Et(r).substring(0,2).toUpperCase()}),b.jsxs("div",{className:"user-info",children:[b.jsx("div",{className:"username",children:Et(r)}),b.jsx("div",{className:"user-status",children:xt?"Online":"Unlinked Account"})]}),b.jsx("button",{className:"add-btn",onClick:()=>{Re(St?.name||""),me(!0)},children:"⚙️"})]})]}),b.jsxs("div",{className:"main-content",children:[b.jsxs("div",{className:"chat-header",children:[b.jsx("span",{style:{color:"var(--text-muted)",marginRight:"8px"},children:"#"}),Ui?.name||"Select a channel"]}),b.jsxs("div",{className:"messages-container",children:[xn.map(B=>b.jsxs("div",{className:"message",children:[b.jsx("div",{className:"message-avatar",children:Et(B.sender).substring(0,2).toUpperCase()}),b.jsxs("div",{className:"message-content",children:[b.jsxs("div",{className:"message-meta",children:[b.jsx("span",{className:"message-sender",children:Et(B.sender)}),b.jsx("span",{className:"message-timestamp",children:Mi(B.sent)})]}),b.jsx("div",{className:"message-text",children:B.text}),(()=>{const ye=Dr.find(bn=>bn.parentMessageId===B.id);return ye?b.jsx("button",{className:"message-thread-btn",onClick:()=>y(ye.id),children:"View Thread"}):b.jsx("button",{className:"message-thread-btn",onClick:()=>Ds(B),children:"Start Thread"})})(),Dr.filter(ye=>ye.parentMessageId===B.id).map(ye=>b.jsxs("div",{style:{marginLeft:"12px",marginTop:"4px",cursor:"pointer",color:"var(--brand)"},onClick:()=>y(ye.id),children:["↳ ",ye.name]},ye.id.toString()))]})]},B.id.toString())),b.jsx("div",{ref:H})]}),b.jsx("div",{className:"chat-input-container",children:b.jsx("form",{className:"chat-input-wrapper",onSubmit:js,children:b.jsx("input",{className:"chat-input",placeholder:xt?`Message #${Ui?.name||""}`:"Log in to chat",disabled:!xt,value:x,onChange:B=>R(B.target.value)})})})]}),b.jsx("div",{className:"right-sidebar",children:v?b.jsxs("div",{className:"thread-view",children:[b.jsxs("div",{className:"thread-header",children:[b.jsx("span",{children:"Thread"}),b.jsx("button",{className:"close-btn",onClick:()=>y(null),children:"×"})]}),b.jsxs("div",{className:"thread-messages",children:[b.jsx("div",{style:{padding:"8px",borderBottom:"1px solid var(--background-accent)",marginBottom:"8px"},children:b.jsx("div",{style:{fontWeight:"bold"},children:Ri?.name})}),Ni.map(B=>b.jsxs("div",{className:"message",style:{gap:"8px",marginBottom:"8px"},children:[b.jsx("div",{className:"message-avatar",style:{width:"32px",height:"32px"},children:Et(B.sender).substring(0,2).toUpperCase()}),b.jsxs("div",{className:"message-content",children:[b.jsx("div",{className:"message-meta",children:b.jsx("span",{className:"message-sender",style:{fontSize:"0.9rem"},children:Et(B.sender)})}),b.jsx("div",{className:"message-text",style:{fontSize:"0.9rem"},children:B.text})]})]},B.id.toString())),b.jsx("div",{ref:z})]}),b.jsx("div",{className:"chat-input-container",style:{padding:"8px"},children:b.jsx("form",{className:"chat-input-wrapper",onSubmit:$r,children:b.jsx("input",{className:"chat-input",style:{fontSize:"0.85rem"},placeholder:xt?"Reply in thread...":"Log in to chat",disabled:!xt,value:N,onChange:B=>j(B.target.value)})})})]}):b.jsxs("div",{className:"member-list",children:[b.jsxs("div",{style:{padding:"0 8px 8px 8px",fontSize:"0.75rem",fontWeight:"bold",color:"var(--text-muted)"},children:["ONLINE — ",kn.length]}),kn.map(B=>b.jsxs("div",{className:"member-item",children:[b.jsx("div",{className:"member-avatar",style:{width:"24px",height:"24px",display:"flex",alignItems:"center",justifyContent:"center",color:"white",fontSize:"0.7rem"},children:(B.name||B.identity.toHexString()).substring(0,2).toUpperCase()}),b.jsx("span",{className:"member-name",children:B.name||B.identity.toHexString().substring(0,8)})]},B.identity.toHexString()))]})}),O&&b.jsx("div",{className:"modal-overlay",children:b.jsxs("form",{className:"modal-content",onSubmit:Lr,children:[b.jsx("h2",{children:"Create Server"}),b.jsx("input",{autoFocus:!0,placeholder:"server-name",value:Q,onChange:B=>$(B.target.value)}),b.jsxs("div",{className:"modal-buttons",children:[b.jsx("button",{type:"button",className:"btn-secondary",onClick:()=>q(!1),children:"Cancel"}),b.jsx("button",{type:"submit",className:"btn-primary",disabled:!xt,children:"Create"})]})]})}),fe&&b.jsx("div",{className:"modal-overlay",children:b.jsxs("form",{className:"modal-content",onSubmit:ya,children:[b.jsx("h2",{children:"Create Channel"}),b.jsx("input",{autoFocus:!0,placeholder:"channel-name",value:A,onChange:B=>L(B.target.value)}),b.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",color:"var(--text-normal)"},children:[b.jsx("input",{type:"checkbox",checked:J,onChange:B=>Y(B.target.checked)}),b.jsx("label",{children:"Voice Channel"})]}),b.jsxs("div",{className:"modal-buttons",children:[b.jsx("button",{type:"button",className:"btn-secondary",onClick:()=>T(!1),children:"Cancel"}),b.jsx("button",{type:"submit",className:"btn-primary",disabled:!xt,children:"Create"})]})]})}),ge&&b.jsx("div",{className:"modal-overlay",children:b.jsxs("form",{className:"modal-content",onSubmit:Os,children:[b.jsx("h2",{children:"Account Settings"}),b.jsx("input",{autoFocus:!0,placeholder:"Display Name",value:ue,onChange:B=>Re(B.target.value)}),b.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-muted)",marginTop:"8px"},children:St?.issuer?b.jsxs(b.Fragment,{children:["Signed in via OIDC as: ",b.jsx("b",{children:s.user?.profile.name||s.user?.profile.sub})]}):St?.username?b.jsxs(b.Fragment,{children:["Logged in as: ",b.jsx("b",{children:St.username})]}):b.jsx(b.Fragment,{children:"Unlinked Anonymous Account"})}),b.jsxs("div",{className:"modal-buttons",style:{marginTop:"16px",justifyContent:"space-between"},children:[b.jsx("button",{type:"button",className:"btn-danger",onClick:()=>{s.isAuthenticated&&s.signoutRedirect(),localStorage.removeItem(Wu),window.location.reload()},children:"Sign Out / Reset"}),b.jsxs("div",{style:{display:"flex",gap:"8px"},children:[b.jsx("button",{type:"button",className:"btn-secondary",onClick:()=>me(!1),children:"Cancel"}),b.jsx("button",{type:"submit",className:"btn-primary",children:"Save"})]})]})]})})]})}const Cp="https://maincloud.spacetimedb.com",Tp="my-spacetime-app-jdhdg",Wu=`${Cp}/${Tp}/auth_token`,gS={authority:"https://accounts.google.com",client_id:"REPLACE_ME",redirect_uri:window.location.origin,scope:"openid profile email",response_type:"code",onSigninCallback:()=>{window.history.replaceState({},document.title,window.location.pathname)}},mS=(r,n,s)=>{localStorage.setItem(Wu,s),console.log("Connected to SpacetimeDB with identity:",n.toHexString())},yS=()=>{console.log("Disconnected from SpacetimeDB")},wS=(r,n)=>{console.log("Error connecting to SpacetimeDB:",n)};function vS(){const r=bp(),n=ae.useMemo(()=>{const s=Fu.builder().withUri(Cp).withDatabaseName(Tp).onConnect(mS).onDisconnect(yS).onConnectError(wS);if(r.isAuthenticated&&r.user?.id_token)return console.log("Connecting with OIDC token"),s.withToken(r.user.id_token);{const a=localStorage.getItem(Wu);if(a)return console.log("Connecting with stored SpacetimeDB token"),s.withToken(a)}return s},[r.isAuthenticated,r.user?.id_token]);return b.jsx(x_,{connectionBuilder:n,children:b.jsx(pS,{})})}Rm.createRoot(document.getElementById("root")).render(b.jsx(ae.StrictMode,{children:b.jsx(hS,{...gS,children:b.jsx(vS,{})})}));