@nhost/nhost-js 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,10 +11,10 @@
11
11
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
12
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
13
  PERFORMANCE OF THIS SOFTWARE.
14
- ***************************************************************************** */var m=function(){return m=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},m.apply(this,arguments)};function Ot(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function M(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function D(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){s={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}function F(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,o;n<i;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))}var $;(function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"})($||($={}));var ie;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(ie||(ie={}));var Ye=$.Start,We=$.Stop,me=$.Raise,ge=$.Send,kt=$.Cancel,sr=$.NullEvent,Je=$.Assign,Fn=$.After,qn=$.DoneState,Qe=$.Log,ar=$.Init,Xe=$.Invoke,Gn=$.ErrorExecution,xt=$.ErrorPlatform,It=$.ErrorCustom,Ze=$.Update,cr=$.Choose,ur=$.Pure;const Vn=Object.freeze(Object.defineProperty({__proto__:null,after:Fn,assign:Je,cancel:kt,choose:cr,doneState:qn,error:It,errorExecution:Gn,errorPlatform:xt,init:ar,invoke:Xe,log:Qe,nullEvent:sr,pure:ur,raise:me,send:ge,start:Ye,stop:We,update:Ze},Symbol.toStringTag,{value:"Module"}));var lr=".",dr={},Rt="xstate.guard",Hn="",G=process.env.NODE_ENV==="production",et;function Pt(t,e,r){r===void 0&&(r=lr);var n=De(t,r),i=De(e,r);return L(i)?L(n)?i===n:!1:L(n)?n in i:Object.keys(n).every(function(o){return o in i?Pt(n[o],i[o]):!1})}function hr(t){try{return L(t)||typeof t=="number"?"".concat(t):t.type}catch{throw new Error("Events must be strings or objects with a string event.type property.")}}function _t(t,e){try{return Te(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function Kn(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function De(t,e){if(Kn(t))return t.value;if(Te(t))return tt(t);if(typeof t!="string")return t;var r=_t(t,e);return tt(r)}function tt(t){if(t.length===1)return t[0];for(var e={},r=e,n=0;n<t.length-1;n++)n===t.length-2?r[t[n]]=t[n+1]:(r[t[n]]={},r=r[t[n]]);return e}function Ne(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var o=n[i];r[o]=e(t[o],o,t,i)}return r}function fr(t,e,r){var n,i,o={};try{for(var s=M(Object.keys(t)),u=s.next();!u.done;u=s.next()){var d=u.value,f=t[d];r(f)&&(o[d]=e(f,d,t))}}catch(c){n={error:c}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}var zn=function(t){return function(e){var r,n,i=e;try{for(var o=M(t),s=o.next();!s.done;s=o.next()){var u=s.value;i=i[u]}}catch(d){r={error:d}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i}};function Yn(t,e){return function(r){var n,i,o=r;try{for(var s=M(t),u=s.next();!u.done;u=s.next()){var d=u.value;o=o[e][d]}}catch(f){n={error:f}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}}function rt(t){if(!t)return[[]];if(L(t))return[[t]];var e=V(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:rt(t[r]).map(function(i){return[r].concat(i)})}));return e}function V(t){var e;return(e=[]).concat.apply(e,F([],D(t),!1))}function pr(t){return Te(t)?t:[t]}function te(t){return t===void 0?[]:pr(t)}function nt(t,e,r){var n,i;if(B(t))return t(e,r.data);var o={};try{for(var s=M(Object.keys(t)),u=s.next();!u.done;u=s.next()){var d=u.value,f=t[d];B(f)?o[d]=f(e,r.data):o[d]=f}}catch(c){n={error:c}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}function Wn(t){return/^(done|error)\./.test(t)}function vr(t){return!!(t instanceof Promise||t!==null&&(B(t)||typeof t=="object")&&B(t.then))}function Jn(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function Qn(t,e){var r,n,i=D([[],[]],2),o=i[0],s=i[1];try{for(var u=M(t),d=u.next();!d.done;d=u.next()){var f=d.value;e(f)?o.push(f):s.push(f)}}catch(c){r={error:c}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}return[o,s]}function yr(t,e){return Ne(t.states,function(r,n){if(r){var i=(L(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:yr(r,i)}}})}function Xn(t,e){return{current:e,states:yr(t,e)}}function mr(t,e,r,n){G||z(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(o,s){var u,d,f=s.assignment,c={state:n,action:s,_event:e},l={};if(B(f))l=f(o,e.data,c);else try{for(var h=M(Object.keys(f)),y=h.next();!y.done;y=h.next()){var v=y.value,w=f[v];l[v]=B(w)?w(o,e.data,c):w}}catch(T){u={error:T}}finally{try{y&&!y.done&&(d=h.return)&&d.call(h)}finally{if(u)throw u.error}}return Object.assign({},o,l)},t);return i}var z=function(){};G||(z=function(t,e){var r=t instanceof Error?t:void 0;if(!(!r&&t)&&console!==void 0){var n=["Warning: ".concat(e)];r&&n.push(r),console.warn.apply(console,n)}});function Te(t){return Array.isArray(t)}function B(t){return typeof t=="function"}function L(t){return typeof t=="string"}function gr(t,e){if(t)return L(t)?{type:Rt,name:t,predicate:e?e[t]:void 0}:B(t)?{type:Rt,name:t.name,predicate:t}:t}function Zn(t){try{return"subscribe"in t&&B(t.subscribe)}catch{return!1}}var fe=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();et={},et[fe]=function(){return this},et[Symbol.observable]=function(){return this};function ae(t){return!!t&&"__xstatenode"in t}function ei(t){return!!t&&typeof t.send=="function"}var ti=function(){var t=0;return function(){return t++,t.toString(16)}}();function Ut(t,e){return L(t)||typeof t=="number"?m({type:t},e):t}function Q(t,e){if(!L(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=Ut(t);return m({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function be(t,e){var r=pr(e).map(function(n){return typeof n>"u"||typeof n=="string"||ae(n)?{target:n,event:t}:m(m({},n),{event:t})});return r}function ri(t){if(!(t===void 0||t===Hn))return te(t)}function ni(t,e,r){if(!G){var n=t.stack?" Stacktrace was '".concat(t.stack,"'"):"";if(t===e)console.error("Missing onError handler for invocation '".concat(r,"', error was '").concat(t,"'.").concat(n));else{var i=e.stack?" Stacktrace was '".concat(e.stack,"'"):"";console.error("Missing onError handler and/or unhandled exception/promise rejection for invocation '".concat(r,"'. ")+"Original error: '".concat(t,"'. ").concat(n," Current error is '").concat(e,"'.").concat(i))}}}function wr(t,e,r,n,i){var o=t.options.guards,s={state:i,cond:e,_event:n};if(e.type===Rt)return((o==null?void 0:o[e.name])||e.predicate)(r,n.data,s);var u=o==null?void 0:o[e.type];if(!u)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return u(r,n.data,s)}function Er(t){return typeof t=="string"?{type:t}:t}function it(t,e,r){var n=function(){},i=typeof t=="object",o=i?t:null;return{next:((i?t.next:t)||n).bind(o),error:((i?t.error:e)||n).bind(o),complete:((i?t.complete:r)||n).bind(o)}}function ot(t,e){return"".concat(t,":invocation[").concat(e,"]")}var we=Q({type:ar});function st(t,e){return e&&e[t]||void 0}function Ae(t,e){var r;if(L(t)||typeof t=="number"){var n=st(t,e);B(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(B(t))r={type:t.name||t.toString(),exec:t};else{var n=st(t.type,e);if(B(n))r=m(m({},t),{exec:n});else if(n){var i=n.type||t.type;r=m(m(m({},n),t),{type:i})}else r=t}return r}var ce=function(t,e){if(!t)return[];var r=Te(t)?t:[t];return r.map(function(n){return Ae(n,e)})};function at(t){var e=Ae(t);return m(m({id:L(t)?t:e.id},e),{type:e.type})}function Sr(t){return L(t)?{type:me,event:t}:pe(t,{to:ie.Internal})}function Tr(t){return{type:me,_event:Q(t.event)}}function pe(t,e){return{to:e?e.to:void 0,type:ge,event:B(t)?t:Ut(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:B(t)?t.name:hr(t)}}function br(t,e,r,n){var i={_event:r},o=Q(B(t.event)?t.event(e,r.data,i):t.event),s;if(L(t.delay)){var u=n&&n[t.delay];s=B(u)?u(e,r.data,i):u}else s=B(t.delay)?t.delay(e,r.data,i):t.delay;var d=B(t.to)?t.to(e,r.data,i):t.to;return m(m({},t),{to:d,_event:o,event:o.data,delay:s})}function Dt(t,e){return pe(t,m(m({},e),{to:ie.Parent}))}function ii(t,e,r){return pe(e,m(m({},r),{to:t}))}function oi(){return Dt(Ze)}function si(t,e){return pe(t,m(m({},e),{to:function(r,n,i){var o=i._event;return o.origin}}))}var ai=function(t,e){return{context:t,event:e}};function ci(t,e){return t===void 0&&(t=ai),{type:Qe,label:e,expr:t}}var Ar=function(t,e,r){return m(m({},t),{value:L(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Or=function(t){return{type:kt,sendId:t}};function kr(t){var e=at(t);return{type:$.Start,activity:e,exec:void 0}}function xr(t){var e=B(t)?t:at(t);return{type:$.Stop,activity:e,exec:void 0}}function Ir(t,e,r){var n=B(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,o={type:$.Stop,activity:i};return o}var Rr=function(t){return{type:Je,assignment:t}};function ui(t){return typeof t=="object"&&"type"in t}function Pr(t,e){var r=e?"#".concat(e):"";return"".concat($.After,"(").concat(t,")").concat(r)}function Ce(t,e){var r="".concat($.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Me(t,e){var r="".concat($.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Oe(t,e){var r="".concat($.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function li(t){return{type:$.Pure,get:t}}function di(t,e){if(!G&&(!t||typeof t=="function")){var r=t;t=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var o=typeof r=="function"?r.apply(void 0,F([],D(n),!1)):r;if(!o)throw new Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");return o}}return pe(function(n,i){return i},m(m({},e),{to:t}))}function hi(t,e){return Dt(function(r,n,i){return{type:It,data:B(t)?t(r,n,i):t}},m(m({},e),{to:ie.Parent}))}function fi(t){return{type:$.Choose,conds:t}}var pi=function(t){var e,r,n=[];try{for(var i=M(t),o=i.next();!o.done;o=i.next())for(var s=o.value,u=0;u<s.length;){if(s[u].type===Je){n.push(s[u]),s.splice(u,1);continue}u++}}catch(d){e={error:d}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function Le(t,e,r,n,i,o,s){s===void 0&&(s=!1);var u=s?[]:pi(i),d=u.length?mr(r,n,u,e):r,f=s?[r]:void 0,c=[];function l(v){var w;switch(v.type){case me:return Tr(v);case ge:var T=br(v,d,n,t.options.delays);return G||z(!L(v.delay)||typeof T.delay=="number","No delay reference for delay expression '".concat(v.delay,"' was found on machine '").concat(t.id,"'")),o&&T.to!==ie.Internal&&c.push(T),T;case Qe:{var O=Ar(v,d,n);return o==null||o(O,d,n),O}case cr:{var S=v,A=(w=S.conds.find(function(K){var a=gr(K.cond,t.options.guards);return!a||wr(t,a,d,n,o?void 0:e)}))===null||w===void 0?void 0:w.actions;if(!A)return[];var N=D(Le(t,e,d,n,[ce(te(A),t.options.actions)],o,s),2),R=N[0],q=N[1];return d=q,f==null||f.push(d),R}case ur:{var A=v.get(d,n.data);if(!A)return[];var P=D(Le(t,e,d,n,[ce(te(A),t.options.actions)],o,s),2),I=P[0],j=P[1];return d=j,f==null||f.push(d),I}case We:{var O=Ir(v,d,n);return o==null||o(O,r,n),O}case Je:{d=mr(d,n,[v],o?void 0:e),f==null||f.push(d);break}default:var k=Ae(v,t.options.actions),x=k.exec;if(o)o(k,d,n);else if(x&&f){var J=f.length-1;k=m(m({},k),{exec:function(K){for(var a=[],p=1;p<arguments.length;p++)a[p-1]=arguments[p];x.apply(void 0,F([f[J]],D(a),!1))}})}return k}}function h(v){var w,T,O=[];try{for(var S=M(v),A=S.next();!A.done;A=S.next()){var N=A.value,R=l(N);R&&(O=O.concat(R))}}catch(q){w={error:q}}finally{try{A&&!A.done&&(T=S.return)&&T.call(S)}finally{if(w)throw w.error}}return c.forEach(function(q){o(q,d,n)}),c.length=0,O}var y=V(i.map(h));return[y,d]}const vi=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:Vn,after:Pr,assign:Rr,cancel:Or,choose:fi,done:Ce,doneInvoke:Me,error:Oe,escalate:hi,forwardTo:di,getActionFunction:st,initEvent:we,isActionObject:ui,log:ci,pure:li,raise:Sr,resolveActions:Le,resolveLog:Ar,resolveRaise:Tr,resolveSend:br,resolveStop:Ir,respond:si,send:pe,sendParent:Dt,sendTo:ii,sendUpdate:oi,start:kr,stop:xr,toActionObject:Ae,toActionObjects:ce,toActivityDefinition:at},Symbol.toStringTag,{value:"Module"}));var ct=[],ke=function(t,e){ct.push(t);var r=e(t);return ct.pop(),r},yi=function(t){return t(ct[ct.length-1])};function _r(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[fe]=function(){return this},e}function mi(t,e,r,n){var i,o=Er(t.src),s=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[o.type],u=t.data?nt(t.data,r,n):void 0,d=s?Nt(s,t.id,u):_r(t.id);return d.meta=t,d}function Nt(t,e,r){var n=_r(e);if(n.deferred=!0,ae(t)){var i=n.state=ke(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function gi(t){try{return typeof t.send=="function"}catch{return!1}}function wi(t){return gi(t)&&"id"in t}function Ei(t){var e;return m((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[fe]=function(){return this},e),t)}var ut=function(t){return t.type==="atomic"||t.type==="final"};function Ur(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function je(t){return Ur(t).filter(function(e){return e.type!=="history"})}function Dr(t){var e=[t];return ut(t)?e:e.concat(V(je(t).map(Dr)))}function $e(t,e){var r,n,i,o,s,u,d,f,c=new Set(t),l=Ct(c),h=new Set(e);try{for(var y=M(h),v=y.next();!v.done;v=y.next())for(var w=v.value,T=w.parent;T&&!h.has(T);)h.add(T),T=T.parent}catch(j){r={error:j}}finally{try{v&&!v.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}var O=Ct(h);try{for(var S=M(h),A=S.next();!A.done;A=S.next()){var w=A.value;if(w.type==="compound"&&(!O.get(w)||!O.get(w).length))l.get(w)?l.get(w).forEach(function(k){return h.add(k)}):w.initialStateNodes.forEach(function(k){return h.add(k)});else if(w.type==="parallel")try{for(var N=(s=void 0,M(je(w))),R=N.next();!R.done;R=N.next()){var q=R.value;h.has(q)||(h.add(q),l.get(q)?l.get(q).forEach(function(k){return h.add(k)}):q.initialStateNodes.forEach(function(k){return h.add(k)}))}}catch(k){s={error:k}}finally{try{R&&!R.done&&(u=N.return)&&u.call(N)}finally{if(s)throw s.error}}}}catch(j){i={error:j}}finally{try{A&&!A.done&&(o=S.return)&&o.call(S)}finally{if(i)throw i.error}}try{for(var P=M(h),I=P.next();!I.done;I=P.next())for(var w=I.value,T=w.parent;T&&!h.has(T);)h.add(T),T=T.parent}catch(j){d={error:j}}finally{try{I&&!I.done&&(f=P.return)&&f.call(P)}finally{if(d)throw d.error}}return h}function Nr(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(ut(n))return n.key}else return{}}var i={};return r.forEach(function(o){i[o.key]=Nr(o,e)}),i}function Ct(t){var e,r,n=new Map;try{for(var i=M(t),o=i.next();!o.done;o=i.next()){var s=o.value;n.has(s)||n.set(s,[]),s.parent&&(n.has(s.parent)||n.set(s.parent,[]),n.get(s.parent).push(s))}}catch(u){e={error:u}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function Si(t,e){var r=$e([t],e);return Nr(t,Ct(r))}function Be(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Ti(t){return F([],D(new Set(V(F([],D(t.map(function(e){return e.ownEvents})),!1)))),!1)}function lt(t,e){return e.type==="compound"?je(e).some(function(r){return r.type==="final"&&Be(t,r)}):e.type==="parallel"?je(e).every(function(r){return lt(t,r)}):!1}function bi(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Cr(t){return new Set(V(t.map(function(e){return e.tags})))}function Mr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(L(t)||L(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Mr(t[i],e[i])})}function Ai(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function Oi(t,e){var r=t.exec,n=m(m({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var oe=function(){function t(e){var r=this,n;this.actions=[],this.activities=dr,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||dr,this.meta=bi(e.configuration),this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,this.tags=(n=Array.isArray(e.tags)?new Set(e.tags):e.tags)!==null&&n!==void 0?n:new Set,this.machine=e.machine,Object.defineProperty(this,"nextEvents",{get:function(){return Ti(r.configuration)}})}return t.from=function(e,r){if(e instanceof t)return e.context!==r?new t({value:e.value,context:r,_event:e._event,_sessionid:null,historyValue:e.historyValue,history:e.history,actions:[],activities:e.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):e;var n=we;return new t({value:e,context:r,_event:n,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})},t.create=function(e){return new t(e)},t.inert=function(e,r){if(e instanceof t){if(!e.actions.length)return e;var n=we;return new t({value:e.value,context:r,_event:n,_sessionid:null,historyValue:e.historyValue,history:e.history,activities:e.activities,configuration:e.configuration,transitions:[],children:{}})}return t.from(e,r)},t.prototype.toStrings=function(e,r){var n=this;if(e===void 0&&(e=this.value),r===void 0&&(r="."),L(e))return[e];var i=Object.keys(e);return i.concat.apply(i,F([],D(i.map(function(o){return n.toStrings(e[o],r).map(function(s){return o+r+s})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=Ot(e,["configuration","transitions","tags","machine"]);return m(m({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Pt(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;G&&z(!!this.machine,"state.can(...) used outside of a machine-created State object; this will always return false.");var n=(r=this.machine)===null||r===void 0?void 0:r.getTransitionData(this,e);return!!(n!=null&&n.transitions.length)&&n.transitions.some(function(i){return i.target!==void 0||i.actions.length})},t}(),ki={deferEvents:!1},Lr=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=m(m({},ki),e)}return t.prototype.initialize=function(e){if(this.initialized=!0,e){if(!this.options.deferEvents){this.schedule(e);return}this.process(e)}this.flushEvents()},t.prototype.schedule=function(e){if(!this.initialized||this.processingEvent){this.queue.push(e);return}if(this.queue.length!==0)throw new Error("Event queue should be empty when it is not processing events");this.process(e),this.flushEvents()},t.prototype.clear=function(){this.queue=[]},t.prototype.flushEvents=function(){for(var e=this.queue.shift();e;)this.process(e),e=this.queue.shift()},t.prototype.process=function(e){this.processingEvent=!0;try{e()}catch(r){throw this.clear(),r}finally{this.processingEvent=!1}},t}(),Mt=new Map,xi=0,dt={bookId:function(){return"x:".concat(xi++)},register:function(t,e){return Mt.set(t,e),t},get:function(t){return Mt.get(t)},free:function(t){Mt.delete(t)}};function Lt(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;G||console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function Ii(){var t=Lt();if(t&&"__xstate__"in t)return t.__xstate__}function Ri(t){if(Lt()){var e=Ii();e&&e.register(t)}}function Pi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],o=!1,s=function(){if(!o){for(o=!0;i.length>0;){var f=i.shift();r=t.transition(r,f,d),n.forEach(function(c){return c.next(r)})}o=!1}},u=Ei({id:e.id,send:function(f){i.push(f),s()},getSnapshot:function(){return r},subscribe:function(f,c,l){var h=it(f,c,l);return n.add(h),h.next(r),{unsubscribe:function(){n.delete(h)}}}}),d={parent:e.parent,self:u,id:e.id||"anonymous",observers:n};return r=t.start?t.start(d):r,u}var jt={sync:!1,autoForward:!1},Y;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(Y||(Y={}));var _i=function(){function t(e,r){r===void 0&&(r=t.defaultOptions);var n=this;this.machine=e,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this.status=Y.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(c,l){if(Te(c))return n.batch(c),n.state;var h=Q(Ut(c,l));if(n.status===Y.Stopped)return G||z(!1,'Event "'.concat(h.name,'" was sent to stopped service "').concat(n.machine.id,`". This service has already reached its final state, and will not transition.
14
+ ***************************************************************************** */var m=function(){return m=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},m.apply(this,arguments)};function Ot(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function M(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function D(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(c){s={error:c}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}function F(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,o;n<i;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))}var $;(function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"})($||($={}));var ie;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(ie||(ie={}));var Ye=$.Start,We=$.Stop,me=$.Raise,ge=$.Send,kt=$.Cancel,sr=$.NullEvent,Je=$.Assign,Fn=$.After,qn=$.DoneState,Qe=$.Log,ar=$.Init,Xe=$.Invoke,Gn=$.ErrorExecution,xt=$.ErrorPlatform,It=$.ErrorCustom,Ze=$.Update,cr=$.Choose,ur=$.Pure;const Vn=Object.freeze(Object.defineProperty({__proto__:null,after:Fn,assign:Je,cancel:kt,choose:cr,doneState:qn,error:It,errorExecution:Gn,errorPlatform:xt,init:ar,invoke:Xe,log:Qe,nullEvent:sr,pure:ur,raise:me,send:ge,start:Ye,stop:We,update:Ze},Symbol.toStringTag,{value:"Module"}));var lr=".",dr={},Rt="xstate.guard",Hn="",G=process.env.NODE_ENV==="production",et;function Pt(t,e,r){r===void 0&&(r=lr);var n=De(t,r),i=De(e,r);return L(i)?L(n)?i===n:!1:L(n)?n in i:Object.keys(n).every(function(o){return o in i?Pt(n[o],i[o]):!1})}function hr(t){try{return L(t)||typeof t=="number"?"".concat(t):t.type}catch{throw new Error("Events must be strings or objects with a string event.type property.")}}function _t(t,e){try{return Te(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function Kn(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function De(t,e){if(Kn(t))return t.value;if(Te(t))return tt(t);if(typeof t!="string")return t;var r=_t(t,e);return tt(r)}function tt(t){if(t.length===1)return t[0];for(var e={},r=e,n=0;n<t.length-1;n++)n===t.length-2?r[t[n]]=t[n+1]:(r[t[n]]={},r=r[t[n]]);return e}function Ne(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var o=n[i];r[o]=e(t[o],o,t,i)}return r}function fr(t,e,r){var n,i,o={};try{for(var s=M(Object.keys(t)),c=s.next();!c.done;c=s.next()){var d=c.value,f=t[d];r(f)&&(o[d]=e(f,d,t))}}catch(u){n={error:u}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}var zn=function(t){return function(e){var r,n,i=e;try{for(var o=M(t),s=o.next();!s.done;s=o.next()){var c=s.value;i=i[c]}}catch(d){r={error:d}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i}};function Yn(t,e){return function(r){var n,i,o=r;try{for(var s=M(t),c=s.next();!c.done;c=s.next()){var d=c.value;o=o[e][d]}}catch(f){n={error:f}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}}function rt(t){if(!t)return[[]];if(L(t))return[[t]];var e=V(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:rt(t[r]).map(function(i){return[r].concat(i)})}));return e}function V(t){var e;return(e=[]).concat.apply(e,F([],D(t),!1))}function pr(t){return Te(t)?t:[t]}function te(t){return t===void 0?[]:pr(t)}function nt(t,e,r){var n,i;if(B(t))return t(e,r.data);var o={};try{for(var s=M(Object.keys(t)),c=s.next();!c.done;c=s.next()){var d=c.value,f=t[d];B(f)?o[d]=f(e,r.data):o[d]=f}}catch(u){n={error:u}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}function Wn(t){return/^(done|error)\./.test(t)}function vr(t){return!!(t instanceof Promise||t!==null&&(B(t)||typeof t=="object")&&B(t.then))}function Jn(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function Qn(t,e){var r,n,i=D([[],[]],2),o=i[0],s=i[1];try{for(var c=M(t),d=c.next();!d.done;d=c.next()){var f=d.value;e(f)?o.push(f):s.push(f)}}catch(u){r={error:u}}finally{try{d&&!d.done&&(n=c.return)&&n.call(c)}finally{if(r)throw r.error}}return[o,s]}function yr(t,e){return Ne(t.states,function(r,n){if(r){var i=(L(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:yr(r,i)}}})}function Xn(t,e){return{current:e,states:yr(t,e)}}function mr(t,e,r,n){G||z(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(o,s){var c,d,f=s.assignment,u={state:n,action:s,_event:e},l={};if(B(f))l=f(o,e.data,u);else try{for(var h=M(Object.keys(f)),y=h.next();!y.done;y=h.next()){var v=y.value,w=f[v];l[v]=B(w)?w(o,e.data,u):w}}catch(T){c={error:T}}finally{try{y&&!y.done&&(d=h.return)&&d.call(h)}finally{if(c)throw c.error}}return Object.assign({},o,l)},t);return i}var z=function(){};G||(z=function(t,e){var r=t instanceof Error?t:void 0;if(!(!r&&t)&&console!==void 0){var n=["Warning: ".concat(e)];r&&n.push(r),console.warn.apply(console,n)}});function Te(t){return Array.isArray(t)}function B(t){return typeof t=="function"}function L(t){return typeof t=="string"}function gr(t,e){if(t)return L(t)?{type:Rt,name:t,predicate:e?e[t]:void 0}:B(t)?{type:Rt,name:t.name,predicate:t}:t}function Zn(t){try{return"subscribe"in t&&B(t.subscribe)}catch{return!1}}var fe=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();et={},et[fe]=function(){return this},et[Symbol.observable]=function(){return this};function ae(t){return!!t&&"__xstatenode"in t}function ei(t){return!!t&&typeof t.send=="function"}var ti=function(){var t=0;return function(){return t++,t.toString(16)}}();function Ut(t,e){return L(t)||typeof t=="number"?m({type:t},e):t}function Q(t,e){if(!L(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=Ut(t);return m({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function be(t,e){var r=pr(e).map(function(n){return typeof n>"u"||typeof n=="string"||ae(n)?{target:n,event:t}:m(m({},n),{event:t})});return r}function ri(t){if(!(t===void 0||t===Hn))return te(t)}function ni(t,e,r){if(!G){var n=t.stack?" Stacktrace was '".concat(t.stack,"'"):"";if(t===e)console.error("Missing onError handler for invocation '".concat(r,"', error was '").concat(t,"'.").concat(n));else{var i=e.stack?" Stacktrace was '".concat(e.stack,"'"):"";console.error("Missing onError handler and/or unhandled exception/promise rejection for invocation '".concat(r,"'. ")+"Original error: '".concat(t,"'. ").concat(n," Current error is '").concat(e,"'.").concat(i))}}}function wr(t,e,r,n,i){var o=t.options.guards,s={state:i,cond:e,_event:n};if(e.type===Rt)return((o==null?void 0:o[e.name])||e.predicate)(r,n.data,s);var c=o==null?void 0:o[e.type];if(!c)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return c(r,n.data,s)}function Er(t){return typeof t=="string"?{type:t}:t}function it(t,e,r){var n=function(){},i=typeof t=="object",o=i?t:null;return{next:((i?t.next:t)||n).bind(o),error:((i?t.error:e)||n).bind(o),complete:((i?t.complete:r)||n).bind(o)}}function ot(t,e){return"".concat(t,":invocation[").concat(e,"]")}var we=Q({type:ar});function st(t,e){return e&&e[t]||void 0}function Ae(t,e){var r;if(L(t)||typeof t=="number"){var n=st(t,e);B(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(B(t))r={type:t.name||t.toString(),exec:t};else{var n=st(t.type,e);if(B(n))r=m(m({},t),{exec:n});else if(n){var i=n.type||t.type;r=m(m(m({},n),t),{type:i})}else r=t}return r}var ce=function(t,e){if(!t)return[];var r=Te(t)?t:[t];return r.map(function(n){return Ae(n,e)})};function at(t){var e=Ae(t);return m(m({id:L(t)?t:e.id},e),{type:e.type})}function Sr(t){return L(t)?{type:me,event:t}:pe(t,{to:ie.Internal})}function Tr(t){return{type:me,_event:Q(t.event)}}function pe(t,e){return{to:e?e.to:void 0,type:ge,event:B(t)?t:Ut(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:B(t)?t.name:hr(t)}}function br(t,e,r,n){var i={_event:r},o=Q(B(t.event)?t.event(e,r.data,i):t.event),s;if(L(t.delay)){var c=n&&n[t.delay];s=B(c)?c(e,r.data,i):c}else s=B(t.delay)?t.delay(e,r.data,i):t.delay;var d=B(t.to)?t.to(e,r.data,i):t.to;return m(m({},t),{to:d,_event:o,event:o.data,delay:s})}function Dt(t,e){return pe(t,m(m({},e),{to:ie.Parent}))}function ii(t,e,r){return pe(e,m(m({},r),{to:t}))}function oi(){return Dt(Ze)}function si(t,e){return pe(t,m(m({},e),{to:function(r,n,i){var o=i._event;return o.origin}}))}var ai=function(t,e){return{context:t,event:e}};function ci(t,e){return t===void 0&&(t=ai),{type:Qe,label:e,expr:t}}var Ar=function(t,e,r){return m(m({},t),{value:L(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Or=function(t){return{type:kt,sendId:t}};function kr(t){var e=at(t);return{type:$.Start,activity:e,exec:void 0}}function xr(t){var e=B(t)?t:at(t);return{type:$.Stop,activity:e,exec:void 0}}function Ir(t,e,r){var n=B(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,o={type:$.Stop,activity:i};return o}var Rr=function(t){return{type:Je,assignment:t}};function ui(t){return typeof t=="object"&&"type"in t}function Pr(t,e){var r=e?"#".concat(e):"";return"".concat($.After,"(").concat(t,")").concat(r)}function Ce(t,e){var r="".concat($.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Me(t,e){var r="".concat($.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Oe(t,e){var r="".concat($.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function li(t){return{type:$.Pure,get:t}}function di(t,e){if(!G&&(!t||typeof t=="function")){var r=t;t=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var o=typeof r=="function"?r.apply(void 0,F([],D(n),!1)):r;if(!o)throw new Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");return o}}return pe(function(n,i){return i},m(m({},e),{to:t}))}function hi(t,e){return Dt(function(r,n,i){return{type:It,data:B(t)?t(r,n,i):t}},m(m({},e),{to:ie.Parent}))}function fi(t){return{type:$.Choose,conds:t}}var pi=function(t){var e,r,n=[];try{for(var i=M(t),o=i.next();!o.done;o=i.next())for(var s=o.value,c=0;c<s.length;){if(s[c].type===Je){n.push(s[c]),s.splice(c,1);continue}c++}}catch(d){e={error:d}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function Le(t,e,r,n,i,o,s){s===void 0&&(s=!1);var c=s?[]:pi(i),d=c.length?mr(r,n,c,e):r,f=s?[r]:void 0,u=[];function l(v){var w;switch(v.type){case me:return Tr(v);case ge:var T=br(v,d,n,t.options.delays);return G||z(!L(v.delay)||typeof T.delay=="number","No delay reference for delay expression '".concat(v.delay,"' was found on machine '").concat(t.id,"'")),o&&T.to!==ie.Internal&&u.push(T),T;case Qe:{var O=Ar(v,d,n);return o==null||o(O,d,n),O}case cr:{var S=v,A=(w=S.conds.find(function(K){var a=gr(K.cond,t.options.guards);return!a||wr(t,a,d,n,o?void 0:e)}))===null||w===void 0?void 0:w.actions;if(!A)return[];var N=D(Le(t,e,d,n,[ce(te(A),t.options.actions)],o,s),2),R=N[0],q=N[1];return d=q,f==null||f.push(d),R}case ur:{var A=v.get(d,n.data);if(!A)return[];var P=D(Le(t,e,d,n,[ce(te(A),t.options.actions)],o,s),2),I=P[0],j=P[1];return d=j,f==null||f.push(d),I}case We:{var O=Ir(v,d,n);return o==null||o(O,r,n),O}case Je:{d=mr(d,n,[v],o?void 0:e),f==null||f.push(d);break}default:var k=Ae(v,t.options.actions),x=k.exec;if(o)o(k,d,n);else if(x&&f){var J=f.length-1;k=m(m({},k),{exec:function(K){for(var a=[],p=1;p<arguments.length;p++)a[p-1]=arguments[p];x.apply(void 0,F([f[J]],D(a),!1))}})}return k}}function h(v){var w,T,O=[];try{for(var S=M(v),A=S.next();!A.done;A=S.next()){var N=A.value,R=l(N);R&&(O=O.concat(R))}}catch(q){w={error:q}}finally{try{A&&!A.done&&(T=S.return)&&T.call(S)}finally{if(w)throw w.error}}return u.forEach(function(q){o(q,d,n)}),u.length=0,O}var y=V(i.map(h));return[y,d]}const vi=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:Vn,after:Pr,assign:Rr,cancel:Or,choose:fi,done:Ce,doneInvoke:Me,error:Oe,escalate:hi,forwardTo:di,getActionFunction:st,initEvent:we,isActionObject:ui,log:ci,pure:li,raise:Sr,resolveActions:Le,resolveLog:Ar,resolveRaise:Tr,resolveSend:br,resolveStop:Ir,respond:si,send:pe,sendParent:Dt,sendTo:ii,sendUpdate:oi,start:kr,stop:xr,toActionObject:Ae,toActionObjects:ce,toActivityDefinition:at},Symbol.toStringTag,{value:"Module"}));var ct=[],ke=function(t,e){ct.push(t);var r=e(t);return ct.pop(),r},yi=function(t){return t(ct[ct.length-1])};function _r(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[fe]=function(){return this},e}function mi(t,e,r,n){var i,o=Er(t.src),s=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[o.type],c=t.data?nt(t.data,r,n):void 0,d=s?Nt(s,t.id,c):_r(t.id);return d.meta=t,d}function Nt(t,e,r){var n=_r(e);if(n.deferred=!0,ae(t)){var i=n.state=ke(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function gi(t){try{return typeof t.send=="function"}catch{return!1}}function wi(t){return gi(t)&&"id"in t}function Ei(t){var e;return m((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[fe]=function(){return this},e),t)}var ut=function(t){return t.type==="atomic"||t.type==="final"};function Ur(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function je(t){return Ur(t).filter(function(e){return e.type!=="history"})}function Dr(t){var e=[t];return ut(t)?e:e.concat(V(je(t).map(Dr)))}function $e(t,e){var r,n,i,o,s,c,d,f,u=new Set(t),l=Ct(u),h=new Set(e);try{for(var y=M(h),v=y.next();!v.done;v=y.next())for(var w=v.value,T=w.parent;T&&!h.has(T);)h.add(T),T=T.parent}catch(j){r={error:j}}finally{try{v&&!v.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}var O=Ct(h);try{for(var S=M(h),A=S.next();!A.done;A=S.next()){var w=A.value;if(w.type==="compound"&&(!O.get(w)||!O.get(w).length))l.get(w)?l.get(w).forEach(function(k){return h.add(k)}):w.initialStateNodes.forEach(function(k){return h.add(k)});else if(w.type==="parallel")try{for(var N=(s=void 0,M(je(w))),R=N.next();!R.done;R=N.next()){var q=R.value;h.has(q)||(h.add(q),l.get(q)?l.get(q).forEach(function(k){return h.add(k)}):q.initialStateNodes.forEach(function(k){return h.add(k)}))}}catch(k){s={error:k}}finally{try{R&&!R.done&&(c=N.return)&&c.call(N)}finally{if(s)throw s.error}}}}catch(j){i={error:j}}finally{try{A&&!A.done&&(o=S.return)&&o.call(S)}finally{if(i)throw i.error}}try{for(var P=M(h),I=P.next();!I.done;I=P.next())for(var w=I.value,T=w.parent;T&&!h.has(T);)h.add(T),T=T.parent}catch(j){d={error:j}}finally{try{I&&!I.done&&(f=P.return)&&f.call(P)}finally{if(d)throw d.error}}return h}function Nr(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(ut(n))return n.key}else return{}}var i={};return r.forEach(function(o){i[o.key]=Nr(o,e)}),i}function Ct(t){var e,r,n=new Map;try{for(var i=M(t),o=i.next();!o.done;o=i.next()){var s=o.value;n.has(s)||n.set(s,[]),s.parent&&(n.has(s.parent)||n.set(s.parent,[]),n.get(s.parent).push(s))}}catch(c){e={error:c}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function Si(t,e){var r=$e([t],e);return Nr(t,Ct(r))}function Be(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Ti(t){return F([],D(new Set(V(F([],D(t.map(function(e){return e.ownEvents})),!1)))),!1)}function lt(t,e){return e.type==="compound"?je(e).some(function(r){return r.type==="final"&&Be(t,r)}):e.type==="parallel"?je(e).every(function(r){return lt(t,r)}):!1}function bi(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Cr(t){return new Set(V(t.map(function(e){return e.tags})))}function Mr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(L(t)||L(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Mr(t[i],e[i])})}function Ai(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function Oi(t,e){var r=t.exec,n=m(m({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var oe=function(){function t(e){var r=this,n;this.actions=[],this.activities=dr,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||dr,this.meta=bi(e.configuration),this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,this.tags=(n=Array.isArray(e.tags)?new Set(e.tags):e.tags)!==null&&n!==void 0?n:new Set,this.machine=e.machine,Object.defineProperty(this,"nextEvents",{get:function(){return Ti(r.configuration)}})}return t.from=function(e,r){if(e instanceof t)return e.context!==r?new t({value:e.value,context:r,_event:e._event,_sessionid:null,historyValue:e.historyValue,history:e.history,actions:[],activities:e.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):e;var n=we;return new t({value:e,context:r,_event:n,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})},t.create=function(e){return new t(e)},t.inert=function(e,r){if(e instanceof t){if(!e.actions.length)return e;var n=we;return new t({value:e.value,context:r,_event:n,_sessionid:null,historyValue:e.historyValue,history:e.history,activities:e.activities,configuration:e.configuration,transitions:[],children:{}})}return t.from(e,r)},t.prototype.toStrings=function(e,r){var n=this;if(e===void 0&&(e=this.value),r===void 0&&(r="."),L(e))return[e];var i=Object.keys(e);return i.concat.apply(i,F([],D(i.map(function(o){return n.toStrings(e[o],r).map(function(s){return o+r+s})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=Ot(e,["configuration","transitions","tags","machine"]);return m(m({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Pt(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;G&&z(!!this.machine,"state.can(...) used outside of a machine-created State object; this will always return false.");var n=(r=this.machine)===null||r===void 0?void 0:r.getTransitionData(this,e);return!!(n!=null&&n.transitions.length)&&n.transitions.some(function(i){return i.target!==void 0||i.actions.length})},t}(),ki={deferEvents:!1},Lr=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=m(m({},ki),e)}return t.prototype.initialize=function(e){if(this.initialized=!0,e){if(!this.options.deferEvents){this.schedule(e);return}this.process(e)}this.flushEvents()},t.prototype.schedule=function(e){if(!this.initialized||this.processingEvent){this.queue.push(e);return}if(this.queue.length!==0)throw new Error("Event queue should be empty when it is not processing events");this.process(e),this.flushEvents()},t.prototype.clear=function(){this.queue=[]},t.prototype.flushEvents=function(){for(var e=this.queue.shift();e;)this.process(e),e=this.queue.shift()},t.prototype.process=function(e){this.processingEvent=!0;try{e()}catch(r){throw this.clear(),r}finally{this.processingEvent=!1}},t}(),Mt=new Map,xi=0,dt={bookId:function(){return"x:".concat(xi++)},register:function(t,e){return Mt.set(t,e),t},get:function(t){return Mt.get(t)},free:function(t){Mt.delete(t)}};function Lt(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;G||console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function Ii(){var t=Lt();if(t&&"__xstate__"in t)return t.__xstate__}function Ri(t){if(Lt()){var e=Ii();e&&e.register(t)}}function Pi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],o=!1,s=function(){if(!o){for(o=!0;i.length>0;){var f=i.shift();r=t.transition(r,f,d),n.forEach(function(u){return u.next(r)})}o=!1}},c=Ei({id:e.id,send:function(f){i.push(f),s()},getSnapshot:function(){return r},subscribe:function(f,u,l){var h=it(f,u,l);return n.add(h),h.next(r),{unsubscribe:function(){n.delete(h)}}}}),d={parent:e.parent,self:c,id:e.id||"anonymous",observers:n};return r=t.start?t.start(d):r,c}var jt={sync:!1,autoForward:!1},Y;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(Y||(Y={}));var _i=function(){function t(e,r){r===void 0&&(r=t.defaultOptions);var n=this;this.machine=e,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this.status=Y.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(u,l){if(Te(u))return n.batch(u),n.state;var h=Q(Ut(u,l));if(n.status===Y.Stopped)return G||z(!1,'Event "'.concat(h.name,'" was sent to stopped service "').concat(n.machine.id,`". This service has already reached its final state, and will not transition.
15
15
  Event: `).concat(JSON.stringify(h.data))),n.state;if(n.status!==Y.Running&&!n.options.deferEvents)throw new Error('Event "'.concat(h.name,'" was sent to uninitialized service "').concat(n.machine.id,`". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.
16
- Event: `).concat(JSON.stringify(h.data)));return n.scheduler.schedule(function(){n.forward(h);var y=n._nextState(h);n.update(y,h)}),n._state},this.sendTo=function(c,l,h){var y=n.parent&&(l===ie.Parent||n.parent.id===l),v=y?n.parent:L(l)?n.children.get(l)||dt.get(l):ei(l)?l:void 0;if(!v){if(!y)throw new Error("Unable to send event to child '".concat(l,"' from service '").concat(n.id,"'."));G||z(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(c.type));return}if("machine"in v){if(n.status!==Y.Stopped||n.parent!==v||n.state.done){var w=m(m({},c),{name:c.name===It?"".concat(Oe(n.id)):c.name,origin:n.sessionId});!h&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,w]):v.send(w)}}else!h&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,c.data]):v.send(c.data)},this._exec=function(c,l,h,y){y===void 0&&(y=n.machine.options.actions);var v=c.exec||st(c.type,y),w=B(v)?v:v?v.exec:c.exec;if(w)try{return w(l,h.data,n.machine.config.predictableActionArguments?{action:c,_event:h}:{action:c,state:n.state,_event:h})}catch(J){throw n.parent&&n.parent.send({type:"xstate.error",data:J}),J}switch(c.type){case ge:var T=c;if(typeof T.delay=="number"){n.defer(T);return}else T.to?n.sendTo(T._event,T.to,h===we):n.send(T._event);break;case kt:n.cancel(c.sendId);break;case Ye:{if(n.status!==Y.Running)return;var O=c.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[O.id||O.type])break;if(O.type===$.Invoke){var S=Er(O.src),A=n.machine.options.services?n.machine.options.services[S.type]:void 0,N=O.id,R=O.data;G||z(!("forward"in O),"`forward` property is deprecated (found in invocation of '".concat(O.src,"' in in machine '").concat(n.machine.id,"'). ")+"Please use `autoForward` instead.");var q="autoForward"in O?O.autoForward:!!O.forward;if(!A){G||z(!1,"No service found for invocation '".concat(O.src,"' in machine '").concat(n.machine.id,"'."));return}var P=R?nt(R,l,h):void 0;if(typeof A=="string")return;var I=B(A)?A(l,h.data,{data:P,src:S,meta:O.meta}):A;if(!I)return;var j=void 0;ae(I)&&(I=P?I.withContext(P):I,j={autoForward:q}),n.spawn(I,N,j)}else n.spawnActivity(O);break}case We:{n.stopChild(c.activity.id);break}case Qe:var k=c.label,x=c.value;k?n.logger(k,x):n.logger(x);break;default:G||z(!1,"No implementation found for action type '".concat(c.type,"'"));break}};var i=m(m({},t.defaultOptions),r),o=i.clock,s=i.logger,u=i.parent,d=i.id,f=d!==void 0?d:e.id;this.id=f,this.logger=s,this.clock=o,this.parent=u,this.options=i,this.scheduler=new Lr({deferEvents:this.options.deferEvents}),this.sessionId=dt.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:ke(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return G||z(this.status!==Y.NotStarted,"Attempted to read state from uninitialized service '".concat(this.id,"'. Make sure the service is started first.")),this._state},enumerable:!1,configurable:!0}),t.prototype.execute=function(e,r){var n,i;try{for(var o=M(e.actions),s=o.next();!s.done;s=o.next()){var u=s.value;this.exec(u,e,r)}}catch(d){n={error:d}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,o,s,u,d,f,c,l=this;if(e._sessionid=this.sessionId,this._state=e,(!this.machine.config.predictableActionArguments||r===we)&&this.options.execute)this.execute(this.state);else for(var h=void 0;h=this._outgoingQueue.shift();)h[0].send(h[1]);if(this.children.forEach(function(j){l.state.children[j.id]=j}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var y=M(this.eventListeners),v=y.next();!v.done;v=y.next()){var w=v.value;w(e.event)}}catch(j){n={error:j}}finally{try{v&&!v.done&&(i=y.return)&&i.call(y)}finally{if(n)throw n.error}}try{for(var T=M(this.listeners),O=T.next();!O.done;O=T.next()){var w=O.value;w(e,e.event)}}catch(j){o={error:j}}finally{try{O&&!O.done&&(s=T.return)&&s.call(T)}finally{if(o)throw o.error}}try{for(var S=M(this.contextListeners),A=S.next();!A.done;A=S.next()){var N=A.value;N(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(j){u={error:j}}finally{try{A&&!A.done&&(d=S.return)&&d.call(S)}finally{if(u)throw u.error}}if(this.state.done){var R=e.configuration.find(function(j){return j.type==="final"&&j.parent===l.machine}),q=R&&R.doneData?nt(R.doneData,e.context,r):void 0;try{for(var P=M(this.doneListeners),I=P.next();!I.done;I=P.next()){var w=I.value;w(Me(this.id,q))}}catch(j){f={error:j}}finally{try{I&&!I.done&&(c=P.return)&&c.call(P)}finally{if(f)throw f.error}}this._stop(),this._stopChildren()}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===Y.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this,o=it(e,r,n);this.listeners.add(o.next),this.status!==Y.NotStarted&&o.next(this.state);var s=function(){i.doneListeners.delete(s),i.stopListeners.delete(s),o.complete()};return this.status===Y.Stopped?o.complete():(this.onDone(s),this.onStop(s)),{unsubscribe:function(){i.listeners.delete(o.next),i.doneListeners.delete(s),i.stopListeners.delete(s)}}},t.prototype.onEvent=function(e){return this.eventListeners.add(e),this},t.prototype.onSend=function(e){return this.sendListeners.add(e),this},t.prototype.onChange=function(e){return this.contextListeners.add(e),this},t.prototype.onStop=function(e){return this.stopListeners.add(e),this},t.prototype.onDone=function(e){return this.doneListeners.add(e),this},t.prototype.off=function(e){return this.listeners.delete(e),this.eventListeners.delete(e),this.sendListeners.delete(e),this.stopListeners.delete(e),this.doneListeners.delete(e),this.contextListeners.delete(e),this},t.prototype.start=function(e){var r=this;if(this.status===Y.Running)return this;this.machine._init(),dt.register(this.sessionId,this),this.initialized=!0,this.status=Y.Running;var n=e===void 0?this.initialState:ke(this,function(){return Ai(e)?r.machine.resolveState(e):r.machine.resolveState(oe.from(e,r.machine.context))});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(function(){r.update(n,we)}),this},t.prototype._stopChildren=function(){this.children.forEach(function(e){B(e.stop)&&e.stop()}),this.children.clear()},t.prototype._stop=function(){var e,r,n,i,o,s,u,d,f,c;try{for(var l=M(this.listeners),h=l.next();!h.done;h=l.next()){var y=h.value;this.listeners.delete(y)}}catch(P){e={error:P}}finally{try{h&&!h.done&&(r=l.return)&&r.call(l)}finally{if(e)throw e.error}}try{for(var v=M(this.stopListeners),w=v.next();!w.done;w=v.next()){var y=w.value;y(),this.stopListeners.delete(y)}}catch(P){n={error:P}}finally{try{w&&!w.done&&(i=v.return)&&i.call(v)}finally{if(n)throw n.error}}try{for(var T=M(this.contextListeners),O=T.next();!O.done;O=T.next()){var y=O.value;this.contextListeners.delete(y)}}catch(P){o={error:P}}finally{try{O&&!O.done&&(s=T.return)&&s.call(T)}finally{if(o)throw o.error}}try{for(var S=M(this.doneListeners),A=S.next();!A.done;A=S.next()){var y=A.value;this.doneListeners.delete(y)}}catch(P){u={error:P}}finally{try{A&&!A.done&&(d=S.return)&&d.call(S)}finally{if(u)throw u.error}}if(!this.initialized)return this;this.initialized=!1,this.status=Y.Stopped,this._initialState=void 0;try{for(var N=M(Object.keys(this.delayedEventsMap)),R=N.next();!R.done;R=N.next()){var q=R.value;this.clock.clearTimeout(this.delayedEventsMap[q])}}catch(P){f={error:P}}finally{try{R&&!R.done&&(c=N.return)&&c.call(N)}finally{if(f)throw f.error}}this.scheduler.clear(),this.scheduler=new Lr({deferEvents:this.options.deferEvents})},t.prototype.stop=function(){var e=this,r=this.scheduler;return this._stop(),r.schedule(function(){var n=Q({type:"xstate.stop"}),i=ke(e,function(){var o=V(F([],D(e.state.configuration),!1).sort(function(c,l){return l.order-c.order}).map(function(c){return ce(c.onExit,e.machine.options.actions)})),s=D(Le(e.machine,e.state,e.state.context,n,[o],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),u=s[0],d=s[1],f=new oe({value:e.state.value,context:d,_event:n,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:u.filter(function(c){return c.type!==me&&(c.type!==ge||!!c.to&&c.to!==ie.Internal)}),activities:{},events:[],configuration:[],transitions:[],children:{},done:e.state.done,tags:e.state.tags,machine:e.machine});return f.changed=!0,f});e.update(i,n),e._stopChildren(),dt.free(e.sessionId)}),this},t.prototype.batch=function(e){var r=this;if(this.status===Y.NotStarted&&this.options.deferEvents)G||z(!1,"".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,`" and are deferred. Make sure .start() is called for this service.
17
- Event: `).concat(JSON.stringify(event)));else if(this.status!==Y.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,o,s=r.state,u=!1,d=[],f=function(y){var v=Q(y);r.forward(v),s=ke(r,function(){return r.machine.transition(s,v,void 0,n||void 0)}),d.push.apply(d,F([],D(r.machine.config.predictableActionArguments?s.actions:s.actions.map(function(w){return Oi(w,s)})),!1)),u=u||!!s.changed};try{for(var c=M(e),l=c.next();!l.done;l=c.next()){var h=l.value;f(h)}}catch(y){i={error:y}}finally{try{l&&!l.done&&(o=c.return)&&o.call(c)}finally{if(i)throw i.error}}s.changed=u,s.actions=d,r.update(s,Q(e[e.length-1]))})}},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype._nextState=function(e,r){var n=this;r===void 0&&(r=!!this.machine.config.predictableActionArguments&&this._exec);var i=Q(e);if(i.name.indexOf(xt)===0&&!this.state.nextEvents.some(function(s){return s.indexOf(xt)===0}))throw i.data.data;var o=ke(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return o},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=M(this.forwardTo),o=i.next();!o.done;o=i.next()){var s=o.value,u=this.children.get(s);if(!u)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(s,"'."));u.send(e)}}catch(d){r={error:d}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this;this.delayedEventsMap[e.id]=this.clock.setTimeout(function(){e.to?r.sendTo(e._event,e.to,!0):r.send(e._event)},e.delay)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions),this._exec(e,r.context,r._event,n)},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);r&&(this.removeChild(e),B(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==Y.Running)return Nt(e,r);if(vr(e))return this.spawnPromise(Promise.resolve(e),r);if(B(e))return this.spawnCallback(e,r);if(wi(e))return this.spawnActor(e,r);if(Zn(e))return this.spawnObservable(e,r);if(ae(e))return this.spawnMachine(e,m(m({},n),{id:r}));if(Jn(e))return this.spawnBehavior(e,r);throw new Error('Unable to spawn entity "'.concat(r,'" of type "').concat(typeof e,'".'))},t.prototype.spawnMachine=function(e,r){var n=this;r===void 0&&(r={});var i=new t(e,m(m({},this.options),{parent:this,id:r.id||e.id})),o=m(m({},jt),r);o.sync&&i.onTransition(function(u){n.send(Ze,{state:u,id:i.id})});var s=i;return this.children.set(i.id,s),o.autoForward&&this.forwardTo.add(i.id),i.onDone(function(u){n.removeChild(i.id),n.send(Q(u,{origin:i.id}))}).start(),s},t.prototype.spawnBehavior=function(e,r){var n=Pi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,o=!1,s;e.then(function(d){o||(s=d,i.removeChild(r),i.send(Q(Me(r,d),{origin:r})))},function(d){if(!o){i.removeChild(r);var f=Oe(r,d);try{i.send(Q(f,{origin:r}))}catch(c){ni(d,c,r),i.devTools&&i.devTools.send(f,i.state),i.machine.strict&&i.stop()}}});var u=(n={id:r,send:function(){},subscribe:function(d,f,c){var l=it(d,f,c),h=!1;return e.then(function(y){h||(l.next(y),!h&&l.complete())},function(y){h||l.error(y)}),{unsubscribe:function(){return h=!0}}},stop:function(){o=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return s}},n[fe]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnCallback=function(e,r){var n,i=this,o=!1,s=new Set,u=new Set,d,f=function(h){d=h,u.forEach(function(y){return y(h)}),!o&&i.send(Q(h,{origin:r}))},c;try{c=e(f,function(h){s.add(h)})}catch(h){this.send(Oe(r,h))}if(vr(c))return this.spawnPromise(c,r);var l=(n={id:r,send:function(h){return s.forEach(function(y){return y(h)})},subscribe:function(h){var y=it(h);return u.add(y.next),{unsubscribe:function(){u.delete(y.next)}}},stop:function(){o=!0,B(c)&&c()},toJSON:function(){return{id:r}},getSnapshot:function(){return d}},n[fe]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnObservable=function(e,r){var n,i=this,o,s=e.subscribe(function(d){o=d,i.send(Q(d,{origin:r}))},function(d){i.removeChild(r),i.send(Q(Oe(r,d),{origin:r}))},function(){i.removeChild(r),i.send(Q(Me(r),{origin:r}))}),u=(n={id:r,send:function(){},subscribe:function(d,f,c){return e.subscribe(d,f,c)},stop:function(){return s.unsubscribe()},getSnapshot:function(){return o},toJSON:function(){return{id:r}}},n[fe]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnActor=function(e,r){return this.children.set(r,e),e},t.prototype.spawnActivity=function(e){var r=this.machine.options&&this.machine.options.activities?this.machine.options.activities[e.type]:void 0;if(!r){G||z(!1,"No implementation found for activity '".concat(e.type,"'"));return}var n=r(this.state.context,e);this.spawnEffect(e.id,n)},t.prototype.spawnEffect=function(e,r){var n;this.children.set(e,(n={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},stop:r||void 0,getSnapshot:function(){},toJSON:function(){return{id:e}}},n[fe]=function(){return this},n))},t.prototype.attachDev=function(){var e=Lt();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var r=typeof this.options.devTools=="object"?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(m(m({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:m({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Ri(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[fe]=function(){return this},t.prototype.getSnapshot=function(){return this.status===Y.NotStarted?this.initialState:this._state},t.defaultOptions={execute:!0,deferEvents:!0,clock:{setTimeout:function(e,r){return setTimeout(e,r)},clearTimeout:function(e){return clearTimeout(e)}},logger:console.log.bind(console),devTools:!1},t.interpret=xe,t}(),Ui=function(t){return L(t)?m(m({},jt),{name:t}):m(m(m({},jt),{name:ti()}),t)};function Di(t,e){var r=Ui(e);return yi(function(n){if(!G){var i=ae(t)||B(t);z(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(ae(t)?t.id:"undefined",'") outside of a service. This will have no effect.'))}return n?n.spawn(t,r.name,r):Nt(t,r.name)})}function xe(t,e){var r=new _i(t,e);return r}function Ni(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function ht(t){return m(m({type:Xe},t),{toJSON:function(){t.onDone,t.onError;var e=Ot(t,["onDone","onError"]);return m(m({},e),{type:Xe,src:Ni(t.src)})}})}var Ie="",$t="#",Fe="*",Re={},Pe=function(t){return t[0]===$t},Ci=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},Mi=function(t,e,r){var n=r.slice(0,-1).some(function(o){return!("cond"in o)&&!("in"in o)&&(L(o.target)||ae(o.target))}),i=e===Ie?"the transient event":"event '".concat(e,"'");z(!n,"One or more transitions for ".concat(i," on state '").concat(t.id,"' are unreachable. ")+"Make sure that the default transition is the last one defined.")},Li=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var o=this,s;this.config=e,this._context=n,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.tags=[],this.options=Object.assign(Ci(),r),this.parent=i==null?void 0:i.parent,this.key=this.config.key||(i==null?void 0:i.key)||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:lr),this.id=this.config.id||F([this.machine.key],D(this.path),!1).join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:(s=this.config.schema)!==null&&s!==void 0?s:{},this.description=this.config.description,G||z(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?Ne(this.config.states,function(f,c){var l,h=new t(f,{},void 0,{parent:o,key:c});return Object.assign(o.idMap,m((l={},l[h.id]=h,l),h.idMap)),h}):Re;var u=0;function d(f){var c,l;f.order=u++;try{for(var h=M(Ur(f)),y=h.next();!y.done;y=h.next()){var v=y.value;d(v)}}catch(w){c={error:w}}finally{try{y&&!y.done&&(l=h.return)&&l.call(h)}finally{if(c)throw c.error}}}d(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(f){var c=f.event;return c===Ie}):Ie in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=te(this.config.entry||this.config.onEntry).map(function(f){return Ae(f)}),this.onExit=te(this.config.exit||this.config.onExit).map(function(f){return Ae(f)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=te(this.config.invoke).map(function(f,c){var l,h;if(ae(f)){var y=ot(o.id,c);return o.machine.options.services=m((l={},l[y]=f,l),o.machine.options.services),ht({src:y,id:y})}else if(L(f.src)){var y=f.id||ot(o.id,c);return ht(m(m({},f),{id:y,src:f.src}))}else if(ae(f.src)||B(f.src)){var y=f.id||ot(o.id,c);return o.machine.options.services=m((h={},h[y]=f.src,h),o.machine.options.services),ht(m(m({id:y},f),{src:y}))}else{var v=f.src;return ht(m(m({id:ot(o.id,c)},f),{src:v}))}}),this.activities=te(this.config.activities).concat(this.invoke).map(function(f){return at(f)}),this.transition=this.transition.bind(this),this.tags=te(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||Dr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,o=n.activities,s=n.guards,u=n.services,d=n.delays;return new t(this.config,{actions:m(m({},i),e.actions),activities:m(m({},o),e.activities),guards:m(m({},s),e.guards),services:m(m({},u),e.services),delays:m(m({},d),e.delays)},r??this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return B(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:Ne(this.states,function(e){return e.definition}),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke,description:this.description,tags:this.tags}},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return this.definition},Object.defineProperty(t.prototype,"on",{get:function(){if(this.__cache.on)return this.__cache.on;var e=this.transitions;return this.__cache.on=e.reduce(function(r,n){return r[n.eventType]=r[n.eventType]||[],r[n.eventType].push(n),r},{})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transitions",{get:function(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)},enumerable:!1,configurable:!0}),t.prototype.getCandidates=function(e){if(this.__cache.candidates[e])return this.__cache.candidates[e];var r=e===Ie,n=this.transitions.filter(function(i){var o=i.eventType===e;return r?o:o||i.eventType===Fe});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(o,s){var u=B(o)?"".concat(e.id,":delay[").concat(s,"]"):o,d=Pr(u,e.id);return e.onEntry.push(pe(d,{delay:o})),e.onExit.push(Or(d)),d},i=Te(r)?r.map(function(o,s){var u=n(o.delay,s);return m(m({},o),{event:u})}):V(Object.keys(r).map(function(o,s){var u=r[o],d=L(u)?{target:u}:u,f=isNaN(+o)?o:+o,c=n(f,s);return te(d).map(function(l){return m(m({},l),{event:c,delay:f})})}));return i.map(function(o){var s=o.delay;return m(m({},e.formatTransition(o)),{delay:s})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof oe?e.value:De(e,this.delimiter);if(L(i)){var o=this.getStateNode(i).initial;return o!==void 0?this.getStateNodes((r={},r[i]=o,r)):[this,this.states[i]]}var s=Object.keys(i),u=[this];return u.push.apply(u,F([],D(V(s.map(function(d){return n.getStateNode(d).getStateNodes(i[d])}))),!1)),u},t.prototype.handles=function(e){var r=hr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof oe?e:oe.create(e),n=Array.from($e([],this.getStateNodes(r.value)));return new oe(m(m({},r),{value:this.resolve(r.value),configuration:n,done:lt(n,this),tags:Cr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),o=i.next(r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),o=this.getStateNode(i[0]),s=o._transition(e[i[0]],r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionParallelNode=function(e,r,n){var i,o,s={};try{for(var u=M(Object.keys(e)),d=u.next();!d.done;d=u.next()){var f=d.value,c=e[f];if(c){var l=this.getStateNode(f),h=l._transition(c,r,n);h&&(s[f]=h)}}}catch(S){i={error:S}}finally{try{d&&!d.done&&(o=u.return)&&o.call(u)}finally{if(i)throw i.error}}var y=Object.keys(s).map(function(S){return s[S]}),v=V(y.map(function(S){return S.transitions})),w=y.some(function(S){return S.transitions.length>0});if(!w)return this.next(r,n);var T=V(y.map(function(S){return S.entrySet})),O=V(Object.keys(s).map(function(S){return s[S].configuration}));return{transitions:v,entrySet:T,exitSet:V(y.map(function(S){return S.exitSet})),configuration:O,source:r,actions:V(Object.keys(s).map(function(S){return s[S].actions}))}},t.prototype._transition=function(e,r,n){return L(e)?this.transitionLeafNode(e,r,n):Object.keys(e).length===1?this.transitionCompoundNode(e,r,n):this.transitionParallelNode(e,r,n)},t.prototype.getTransitionData=function(e,r){return this._transition(e.value,e,Q(r))},t.prototype.next=function(e,r){var n,i,o=this,s=r.name,u=[],d=[],f;try{for(var c=M(this.getCandidates(s)),l=c.next();!l.done;l=c.next()){var h=l.value,y=h.cond,v=h.in,w=e.context,T=v?L(v)&&Pe(v)?e.matches(De(this.getStateNodeById(v).path,this.delimiter)):Pt(De(v,this.delimiter),zn(this.path.slice(0,-2))(e.value)):!0,O=!1;try{O=!y||wr(this.machine,y,w,r,e)}catch(R){throw new Error("Unable to evaluate guard '".concat(y.name||y.type,"' in transition for event '").concat(s,"' in state node '").concat(this.id,`':
18
- `).concat(R.message))}if(O&&T){h.target!==void 0&&(d=h.target),u.push.apply(u,F([],D(h.actions),!1)),f=h;break}}}catch(R){n={error:R}}finally{try{l&&!l.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}if(f){if(!d.length)return{transitions:[f],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:u};var S=V(d.map(function(R){return o.getRelativeStateNodes(R,e.historyValue)})),A=!!f.internal,N=[];return A||d.forEach(function(R){N.push.apply(N,F([],D(o.getExternalReentryNodes(R)),!1))}),{transitions:[f],entrySet:N,exitSet:A?[]:[this],configuration:S,source:e,actions:u}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=D(e.order>this.order?[e,this]:[this,e],2),i=n[0],o=n[1];i&&i!==o;)r.push(i),i=i.parent;return i!==o?[]:(r.push(o),r)},t.prototype.getActions=function(e,r,n,i,o,s,u){var d,f,c,l,h=this,y=$e([],s?this.getStateNodes(s.value):[this]);try{for(var v=M(e),w=v.next();!w.done;w=v.next()){var T=w.value;(!Be(y,T)||Be(n.entrySet,T.parent))&&n.entrySet.push(T)}}catch(k){d={error:k}}finally{try{w&&!w.done&&(f=v.return)&&f.call(v)}finally{if(d)throw d.error}}try{for(var O=M(y),S=O.next();!S.done;S=O.next()){var T=S.value;(!Be(e,T)||Be(n.exitSet,T.parent))&&n.exitSet.push(T)}}catch(k){c={error:k}}finally{try{S&&!S.done&&(l=O.return)&&l.call(O)}finally{if(c)throw c.error}}var A=V(n.entrySet.map(function(k){var x=[];if(k.type!=="final")return x;var J=k.parent;if(!J.parent)return x;x.push(Ce(k.id,k.doneData),Ce(J.id,k.doneData?nt(k.doneData,i,o):void 0));var K=J.parent;return K.type==="parallel"&&je(K).every(function(a){return lt(n.configuration,a)})&&x.push(Ce(K.id)),x}));n.exitSet.sort(function(k,x){return x.order-k.order}),n.entrySet.sort(function(k,x){return k.order-x.order});var N=new Set(n.entrySet),R=new Set(n.exitSet),q=Array.from(N).map(function(k){var x=k.onEntry,J=k.activities.map(function(K){return kr(K)});return ce(u?F(F([],D(x),!1),D(J),!1):F(F([],D(J),!1),D(x),!1),h.machine.options.actions)}).concat([A.map(Sr)]),P=Array.from(R).map(function(k){return ce(F(F([],D(k.onExit),!1),D(k.activities.map(function(x){return xr(x)})),!1),h.machine.options.actions)}),I=P.concat([ce(n.actions,this.machine.options.actions)]).concat(q);if(r){var j=ce(V(F([],D(e),!1).sort(function(k,x){return x.order-k.order}).map(function(k){return k.onExit})),this.machine.options.actions).filter(function(k){return k.type!==me&&(k.type!==ge||!!k.to&&k.to!==ie.Internal)});return I.concat([j])}return I},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var o=Q(r),s;if(e instanceof oe)s=n===void 0?e:this.resolveState(oe.from(e,n));else{var u=L(e)?this.resolve(tt(this.getResolvedPath(e))):this.resolve(e),d=n??this.machine.context;s=this.resolveState(oe.from(u,d))}if(!G&&o.name===Fe)throw new Error("An event cannot have the wildcard type ('".concat(Fe,"')"));if(this.strict&&!this.events.includes(o.name)&&!Wn(o.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(o.name,"'"));var f=this._transition(s.value,s,o)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:s,actions:[]},c=$e([],this.getStateNodes(s.value)),l=f.configuration.length?$e(c,f.configuration):c;return f.configuration=F([],D(l),!1),this.resolveTransition(f,s,s.context,i,o)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var o,s=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(o=e.actions).unshift.apply(o,F([],D(s),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,o){var s,u,d,f,c=this;o===void 0&&(o=we);var l=e.configuration,h=!r||e.transitions.length>0,y=h?e.configuration:r?r.configuration:[],v=lt(y,this),w=h?Si(this.machine,l):void 0,T=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,O=this.getActions(new Set(y),v,e,n,o,r,i),S=r?m({},r.activities):{};try{for(var A=M(O),N=A.next();!N.done;N=A.next()){var R=N.value;try{for(var q=(d=void 0,M(R)),P=q.next();!P.done;P=q.next()){var I=P.value;I.type===Ye?S[I.activity.id||I.activity.type]=I:I.type===We&&(S[I.activity.id||I.activity.type]=!1)}}catch(Z){d={error:Z}}finally{try{P&&!P.done&&(f=q.return)&&f.call(q)}finally{if(d)throw d.error}}}}catch(Z){s={error:Z}}finally{try{N&&!N.done&&(u=A.return)&&u.call(A)}finally{if(s)throw s.error}}var j=D(Le(this,r,n,o,O,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),k=j[0],x=j[1],J=D(Qn(k,function(Z){return Z.type===me||Z.type===ge&&Z.to===ie.Internal}),2),K=J[0],a=J[1],p=k.filter(function(Z){var Ue;return Z.type===Ye&&((Ue=Z.activity)===null||Ue===void 0?void 0:Ue.type)===Xe}),E=p.reduce(function(Z,Ue){return Z[Ue.activity.id]=mi(Ue.activity,c.machine,x,o),Z},r?m({},r.children):{}),C=new oe({value:w||r.value,context:x,_event:o,_sessionid:r?r._sessionid:null,historyValue:w?T?Xn(T,w):void 0:r?r.historyValue:void 0,history:!w||e.source?r:void 0,actions:w?a:[],activities:w?S:r?r.activities:{},events:[],configuration:y,transitions:e.transitions,children:E,done:v,tags:Cr(y),machine:this}),_=n!==x;C.changed=o.name===Ze||_;var b=C.history;b&&delete b.history;var ee=!v&&(this._transient||l.some(function(Z){return Z._transient}));if(!h&&(!ee||o.name===Ie))return C;var H=C;if(!v)for(ee&&(H=this.resolveRaisedTransition(H,{type:sr},o,i));K.length;){var he=K.shift();H=this.resolveRaisedTransition(H,he._event,o,i)}var yo=H.changed||(b?!!H.actions.length||_||typeof b.value!=typeof H.value||!Mr(H.value,b.value):void 0);return H.changed=yo,H.history=b,H},t.prototype.getStateNode=function(e){if(Pe(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var r=this.states[e];if(!r)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return r},t.prototype.getStateNodeById=function(e){var r=Pe(e)?e.slice($t.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&Pe(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=_t(e,this.delimiter).slice(),n=this;r.length;){var i=r.shift();if(!i.length)break;n=n.getStateNode(i)}return n},t.prototype.resolve=function(e){var r,n=this;if(!e)return this.initialStateValue||Re;switch(this.type){case"parallel":return Ne(this.initialStateValue,function(o,s){return o?n.getStateNode(s).resolve(e[s]||o):Re});case"compound":if(L(e)){var i=this.getStateNode(e);return i.type==="parallel"||i.type==="compound"?(r={},r[e]=i.initialStateValue,r):e}return Object.keys(e).length?Ne(e,function(o,s){return o?n.getStateNode(s).resolve(o):Re}):this.initialStateValue||{};default:return e||Re}},t.prototype.getResolvedPath=function(e){if(Pe(e)){var r=this.machine.idMap[e.slice($t.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return _t(e,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){var e;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var r;if(this.type==="parallel")r=fr(this.states,function(n){return n.initialStateValue||Re},function(n){return n.type!=="history"});else if(this.initial!==void 0){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));r=ut(this.states[this.initial])?this.initial:(e={},e[this.initial]=this.states[this.initial].initialStateValue,e)}else r={};return this.__cache.initialStateValue=r,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),t.prototype.getInitialState=function(e,r){this._init();var n=this.getStateNodes(e);return this.resolveTransition({configuration:n,entrySet:F([],D(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r??this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;L(r.target)?e=Pe(r.target)?tt(this.machine.getStateNodeById(r.target).path.slice(this.path.length-1)):r.target:e=r.target}return e},enumerable:!1,configurable:!0}),t.prototype.getRelativeStateNodes=function(e,r,n){return n===void 0&&(n=!0),n?e.type==="history"?e.resolveHistory(r):e.initialStateNodes:[e]},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var e=this;if(ut(this))return[this];if(this.type==="compound"&&!this.initial)return G||z(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=rt(this.initialStateValue);return V(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=D(e),n=r[0],i=r.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(n,"' from node with no states"));var o=this.getStateNode(n);if(o.type==="history")return o.resolveHistory();if(!this.states[n])throw new Error("Child state '".concat(n,"' does not exist on '").concat(this.id,"'"));return this.states[n].getFromRelativePath(i)},t.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:fr(this.states,function(r,n){if(!e)return r.historyValue();var i=L(e)?void 0:e[n];return r.historyValue(i||r.initialStateValue)},function(r){return!r.history})}},t.prototype.resolveHistory=function(e){var r=this;if(this.type!=="history")return[this];var n=this.parent;if(!e){var i=this.target;return i?V(rt(i).map(function(s){return n.getFromRelativePath(s)})):n.initialStateNodes}var o=Yn(n.path,"states")(e).current;return L(o)?[n.getStateNode(o)]:V(rt(o).map(function(s){return r.history==="deep"?n.getFromRelativePath(s):[n.states[s[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=V(Object.keys(this.states).map(function(n){return e.states[n].stateIds}));return[this.id].concat(r)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){var e,r,n,i;if(this.__cache.events)return this.__cache.events;var o=this.states,s=new Set(this.ownEvents);if(o)try{for(var u=M(Object.keys(o)),d=u.next();!d.done;d=u.next()){var f=d.value,c=o[f];if(c.states)try{for(var l=(n=void 0,M(c.events)),h=l.next();!h.done;h=l.next()){var y=h.value;s.add("".concat(y))}}catch(v){n={error:v}}finally{try{h&&!h.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}}catch(v){e={error:v}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(s)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter(function(r){return!(!r.target&&!r.actions.length&&r.internal)}).map(function(r){return r.eventType}));return Array.from(e)},enumerable:!1,configurable:!0}),t.prototype.resolveTarget=function(e){var r=this;if(e!==void 0)return e.map(function(n){if(!L(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var o=i?r.key+n:n;if(r.parent)try{var s=r.parent.getStateNodeByPath(o);return s}catch(u){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
19
- `).concat(u.message))}else return r.getStateNodeByPath(o)})},t.prototype.formatTransition=function(e){var r=this,n=ri(e.target),i="internal"in e?e.internal:n?n.some(function(d){return L(d)&&d[0]===r.delimiter}):!0,o=this.machine.options.guards,s=this.resolveTarget(n),u=m(m({},e),{actions:ce(te(e.actions)),cond:gr(e.cond,o),target:s,source:this,internal:i,eventType:e.event,toJSON:function(){return m(m({},u),{target:u.target?u.target.map(function(d){return"#".concat(d.id)}):void 0,source:"#".concat(r.id)})}});return u},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var o=this.config.on,s=Fe,u=o[s],d=u===void 0?[]:u,f=Ot(o,[typeof s=="symbol"?s:s+""]);i=V(Object.keys(f).map(function(S){!G&&S===Ie&&z(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var A=be(S,f[S]);return G||Mi(n,S,A),A}).concat(be(Fe,d)))}var c=this.config.always?be("",this.config.always):[],l=this.config.onDone?be(String(Ce(this.id)),this.config.onDone):[];G||z(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var h=V(this.invoke.map(function(S){var A=[];return S.onDone&&A.push.apply(A,F([],D(be(String(Me(S.id)),S.onDone)),!1)),S.onError&&A.push.apply(A,F([],D(be(String(Oe(S.id)),S.onError)),!1)),A})),y=this.after,v=V(F(F(F(F([],D(l),!1),D(h),!1),D(i),!1),D(c),!1).map(function(S){return te(S).map(function(A){return n.formatTransition(A)})}));try{for(var w=M(y),T=w.next();!T.done;T=w.next()){var O=T.value;v.push(O)}}catch(S){e={error:S}}finally{try{T&&!T.done&&(r=w.return)&&r.call(w)}finally{if(e)throw e.error}}return v},t}(),jr=!1;function ve(t,e){return!G&&!t.predictableActionArguments&&!jr&&(jr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new Li(t,e)}var U=Rr,W=pe;/*! js-cookie v3.0.1 | MIT */function ft(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)t[n]=r[n]}return t}var ji={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Bt(t,e){function r(i,o,s){if(!(typeof document>"u")){s=ft({},e,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var d in s)s[d]&&(u+="; "+d,s[d]!==!0&&(u+="="+s[d].split(";")[0]));return document.cookie=i+"="+t.write(o,i)+u}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var o=document.cookie?document.cookie.split("; "):[],s={},u=0;u<o.length;u++){var d=o[u].split("="),f=d.slice(1).join("=");try{var c=decodeURIComponent(d[0]);if(s[c]=t.read(f,c),i===c)break}catch{}}return i?s[i]:s}}return Object.create({set:r,get:n,remove:function(i,o){r(i,"",ft({},o,{expires:-1}))},withAttributes:function(i){return Bt(this.converter,ft({},this.attributes,i))},withConverter:function(i){return Bt(ft({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Ft=Bt(ji,{path:"/"}),$i=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qt={exports:{}};(function(t,e){var r=typeof self<"u"?self:$i,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function d(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(a){return a&&f.indexOf(Object.prototype.toString.call(a))>-1};function l(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function h(a){return typeof a!="string"&&(a=String(a)),a}function y(a){var p={next:function(){var E=a.shift();return{done:E===void 0,value:E}}};return u.iterable&&(p[Symbol.iterator]=function(){return p}),p}function v(a){this.map={},a instanceof v?a.forEach(function(p,E){this.append(E,p)},this):Array.isArray(a)?a.forEach(function(p){this.append(p[0],p[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(p){this.append(p,a[p])},this)}v.prototype.append=function(a,p){a=l(a),p=h(p);var E=this.map[a];this.map[a]=E?E+", "+p:p},v.prototype.delete=function(a){delete this.map[l(a)]},v.prototype.get=function(a){return a=l(a),this.has(a)?this.map[a]:null},v.prototype.has=function(a){return this.map.hasOwnProperty(l(a))},v.prototype.set=function(a,p){this.map[l(a)]=h(p)},v.prototype.forEach=function(a,p){for(var E in this.map)this.map.hasOwnProperty(E)&&a.call(p,this.map[E],E,this)},v.prototype.keys=function(){var a=[];return this.forEach(function(p,E){a.push(E)}),y(a)},v.prototype.values=function(){var a=[];return this.forEach(function(p){a.push(p)}),y(a)},v.prototype.entries=function(){var a=[];return this.forEach(function(p,E){a.push([E,p])}),y(a)},u.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function w(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function T(a){return new Promise(function(p,E){a.onload=function(){p(a.result)},a.onerror=function(){E(a.error)}})}function O(a){var p=new FileReader,E=T(p);return p.readAsArrayBuffer(a),E}function S(a){var p=new FileReader,E=T(p);return p.readAsText(a),E}function A(a){for(var p=new Uint8Array(a),E=new Array(p.length),C=0;C<p.length;C++)E[C]=String.fromCharCode(p[C]);return E.join("")}function N(a){if(a.slice)return a.slice(0);var p=new Uint8Array(a.byteLength);return p.set(new Uint8Array(a)),p.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&d(a)?(this._bodyArrayBuffer=N(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||c(a))?this._bodyArrayBuffer=N(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?w(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(O)}),this.text=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return S(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var q=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function P(a){var p=a.toUpperCase();return q.indexOf(p)>-1?p:a}function I(a,p){p=p||{};var E=p.body;if(a instanceof I){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,p.headers||(this.headers=new v(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!E&&a._bodyInit!=null&&(E=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new v(p.headers)),this.method=P(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function j(a){var p=new FormData;return a.trim().split("&").forEach(function(E){if(E){var C=E.split("="),_=C.shift().replace(/\+/g," "),b=C.join("=").replace(/\+/g," ");p.append(decodeURIComponent(_),decodeURIComponent(b))}}),p}function k(a){var p=new v,E=a.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var _=C.split(":"),b=_.shift().trim();if(b){var ee=_.join(":").trim();p.append(b,ee)}}),p}R.call(I.prototype);function x(a,p){p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in p?p.statusText:"OK",this.headers=new v(p.headers),this.url=p.url||"",this._initBody(a)}R.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},x.error=function(){var a=new x(null,{status:0,statusText:""});return a.type="error",a};var J=[301,302,303,307,308];x.redirect=function(a,p){if(J.indexOf(p)===-1)throw new RangeError("Invalid status code");return new x(null,{status:p,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(p,E){this.message=p,this.name=E;var C=Error(p);this.stack=C.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function K(a,p){return new Promise(function(E,C){var _=new I(a,p);if(_.signal&&_.signal.aborted)return C(new s.DOMException("Aborted","AbortError"));var b=new XMLHttpRequest;function ee(){b.abort()}b.onload=function(){var H={status:b.status,statusText:b.statusText,headers:k(b.getAllResponseHeaders()||"")};H.url="responseURL"in b?b.responseURL:H.headers.get("X-Request-URL");var he="response"in b?b.response:b.responseText;E(new x(he,H))},b.onerror=function(){C(new TypeError("Network request failed"))},b.ontimeout=function(){C(new TypeError("Network request failed"))},b.onabort=function(){C(new s.DOMException("Aborted","AbortError"))},b.open(_.method,_.url,!0),_.credentials==="include"?b.withCredentials=!0:_.credentials==="omit"&&(b.withCredentials=!1),"responseType"in b&&u.blob&&(b.responseType="blob"),_.headers.forEach(function(H,he){b.setRequestHeader(he,H)}),_.signal&&(_.signal.addEventListener("abort",ee),b.onreadystatechange=function(){b.readyState===4&&_.signal.removeEventListener("abort",ee)}),b.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=v,o.Request=I,o.Response=x),s.Headers=v,s.Request=I,s.Response=x,s.fetch=K,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(qt,qt.exports);const Gt=Bi(qt.exports),qe="nhostRefreshToken",Ge="nhostRefreshTokenExpiresAt",$r=3,Br=300,Vt=5,Ht=0,Kt=1,re=10,_e=20;class Ve extends Error{constructor(e){super(e.message),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Kt,message:e.message}):(this.name=e.error,this.error=e)}}const ue={status:re,error:"invalid-email",message:"Email is incorrectly formatted"},Fr={status:re,error:"invalid-mfa-type",message:"MFA type is invalid"},qr={status:re,error:"invalid-mfa-code",message:"MFA code is invalid"},pt={status:re,error:"invalid-password",message:"Password is incorrectly formatted"},zt={status:re,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Gr={status:re,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Vr={status:re,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Hr={status:re,error:"no-refresh-token",message:"No refresh token has been provided"},Kr={status:_e,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},se={status:_e,error:"already-signed-in",message:"User is already signed in"},zr={status:_e,error:"unauthenticated-user",message:"User is not authenticated"},Fi={status:_e,error:"user-not-anonymous",message:"User is not anonymous"},Yr={status:_e,error:"unverified-user",message:"Email needs verification"},Wr={status:re,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},Jr={status:Kt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},vt={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function qi(t){return new TextEncoder().encode(t)}function Ee(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Yt(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),o=new ArrayBuffer(i.length),s=new Uint8Array(o);for(let u=0;u<i.length;u++)s[u]=i.charCodeAt(u);return o}function Qr(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function Xr(t){const{id:e}=t;return{...t,id:Yt(e),transports:t.transports}}function Zr(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class X extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}}function Gi({error:t,options:e}){var r,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new X("Registration ceremony was sent an abort signal","AbortError")}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new X("Discoverable credentials were required but no available authenticator supported it","ConstraintError");if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new X("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new X("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new X("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new X('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new X("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const o=window.location.hostname;if(Zr(o)){if(i.rp.id!==o)return new X(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new X("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class Vi{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const yt=new Vi;async function en(t){if(!Qr())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:Yt(t.challenge),user:{...t.user,id:qi(t.user.id)},excludeCredentials:t.excludeCredentials.map(Xr)}};e.signal=yt.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(d){throw Gi({error:d,options:e})}finally{yt.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:o,type:s}=r,u={id:n,rawId:Ee(i),response:{attestationObject:Ee(o.attestationObject),clientDataJSON:Ee(o.clientDataJSON)},type:s,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof o.getTransports=="function"&&(u.transports=o.getTransports()),u}function Hi(t){return new TextDecoder("utf-8").decode(t)}async function Ki(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function zi({error:t,options:e}){var r;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new X("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new X("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new X("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(Zr(i)){if(n.rpId!==i)return new X(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function Yi(t,e=!1){var r,n;if(!Qr())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)===null||r===void 0?void 0:r.length)!==0&&(i=(n=t.allowCredentials)===null||n===void 0?void 0:n.map(Xr));const o={...t,challenge:Yt(t.challenge),allowCredentials:i},s={};if(e){if(!await Ki())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');s.mediation="conditional",o.allowCredentials=[]}s.publicKey=o,s.signal=yt.createNewAbortSignal();let u;try{u=await navigator.credentials.get(s)}catch(y){throw zi({error:y,options:s})}finally{yt.reset()}if(!u)throw new Error("Authentication was not completed");const{id:d,rawId:f,response:c,type:l}=u;let h;return c.userHandle&&(h=Hi(c.userHandle)),{id:d,rawId:Ee(f),response:{authenticatorData:Ee(c.authenticatorData),clientDataJSON:Ee(c.clientDataJSON),signature:Ee(c.signature),userHandle:h},type:l,clientExtensionResults:u.getClientExtensionResults(),authenticatorAttachment:u.authenticatorAttachment}}const mt=typeof window<"u",gt=new Map,Wi=t=>mt&&typeof localStorage<"u"?localStorage.getItem(t):gt.get(t)??null,Ji=(t,e)=>{mt&&typeof localStorage<"u"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?gt.set(t,e):gt.has(t)&&gt.delete(t)},tn=(t,e)=>{if(t==="localStorage"||t==="web")return Wi;if(t==="cookie")return r=>mt?Ft.get(r)??null:null;if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},rn=(t,e)=>{if(t==="localStorage"||t==="web")return Ji;if(t==="cookie")return(r,n)=>{mt&&(n?Ft.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Ft.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,o;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(o=e.remove)==null?void 0:o.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.deleteItemAsync)==null?void 0:o.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},He=t=>!t||!t.accessToken.value||!t.refreshToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},ye=({accessToken:t,isError:e,user:r,error:n})=>e?{session:null,error:n}:r&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:"",user:r},error:null}:{session:null,error:null},wt=()=>typeof window<"u",nn=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const o={method:e,headers:i};n&&(o.body=JSON.stringify(n));try{const s=await Gt(t,o);if(!s.ok){const u=await s.json();return Promise.reject({error:u})}try{return{data:await s.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const s={message:"Network Error",status:Ht,error:"network"};return Promise.reject({error:s})}},le=async(t,e,r)=>nn(t,"POST",{token:r,body:e}),on=(t,e)=>nn(t,"GET",{token:e}),Wt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const o=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(o)}`}).join("&");return r?`${t}?${r}`:t},ne=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),o=Object.fromEntries(new URLSearchParams(i.search)),s=new URL(r.startsWith("/")?i.origin+r:r),u=new URLSearchParams(s.search);let d=Object.fromEntries(u);r.startsWith("/")&&(d={...o,...d});let f=i.pathname;return s.pathname.length>1&&(f+=s.pathname.slice(1)),{...n,redirectTo:Wt(s.origin+f,d)}};function Ke(t,e){var r;if(!e){if(typeof window>"u")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function Jt(t){var e;if(typeof window>"u")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let o=window.location.pathname;Array.from(n).length&&(o+=`?${n.toString()}`),Array.from(i).length&&(o+=`#${i.toString()}`),window.history.pushState({},"",o)}}const de=t=>!!t&&typeof t=="string"&&!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),Et=t=>!!t&&typeof t=="string"&&t.length>=$r,Qt=t=>!!t&&typeof t=="string",sn=t=>t&&typeof t=="string"&&t.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),an=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:o=!0,autoSignIn:s=!0})=>{const u=tn(r,n),d=rn(r,n),f=async(c,l,h)=>(await le(`${t}${c}`,l,h)).data;return ve({schema:{context:{},events:{},services:{}},tsTypes:{},context:vt,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:W("SIGNED_IN"),reportSignedOut:W("SIGNED_OUT"),reportTokenChanged:W("TOKEN_CHANGED"),incrementTokenImportAttempts:U({importTokenAttempts:({importTokenAttempts:c})=>c+1}),clearContext:U(()=>(d(Ge,null),d(qe,null),{...vt})),clearContextExceptRefreshToken:U(({refreshToken:{value:c}})=>(d(Ge,null),{...vt,refreshToken:{value:c}})),saveSession:U({user:(c,{data:l})=>{var h;return((h=l==null?void 0:l.session)==null?void 0:h.user)||null},accessToken:(c,{data:l})=>{if(l.session){const{accessTokenExpiresIn:h,accessToken:y}=l.session,v=new Date(Date.now()+h*1e3);return d(Ge,v.toISOString()),{value:y,expiresAt:v}}return d(Ge,null),{value:null,expiresAt:null}},refreshToken:(c,{data:l})=>{var h;const y=((h=l.session)==null?void 0:h.refreshToken)||null;return y&&d(qe,y),{value:y}}}),saveMfaTicket:U({mfa:(c,l)=>{var h;return(h=l.data)==null?void 0:h.mfa}}),resetTimer:U({refreshTimer:c=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:U({refreshTimer:(c,l)=>({startedAt:c.refreshTimer.startedAt,attempts:c.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:U({errors:({errors:c},{data:{error:l}})=>({...c,authentication:l})}),resetErrors:U({errors:c=>({}),importTokenAttempts:c=>0}),saveRegistrationError:U({errors:({errors:c},{data:{error:l}})=>({...c,registration:l})}),destroyRefreshToken:U({refreshToken:c=>(d(qe,null),{value:null})}),cleanUrl:()=>{s&&Ke("refreshToken")&&(Jt("refreshToken"),Jt("type"))},broadcastToken:c=>{if(s)try{new BroadcastChannel("nhost").postMessage(c.refreshToken.value)}catch{}}},guards:{isAnonymous:(c,l)=>{var h;return!!((h=c.user)!=null&&h.isAnonymous)},isSignedIn:c=>!!c.user&&!!c.refreshToken.value&&!!c.accessToken.value,noToken:c=>!c.refreshToken.value,hasRefreshToken:c=>!!c.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:c=>{const{expiresAt:l}=c.accessToken;return l?c.refreshTimer.lastAttempt?c.refreshTimer.attempts>Vt?!1:Date.now()-c.refreshTimer.lastAttempt.getTime()>Math.pow(2,c.refreshTimer.attempts-1)*5e3:i&&Date.now()-c.refreshTimer.startedAt.getTime()>i*1e3?!0:l.getTime()-Date.now()-1e3*Br<=0:!1},shouldRetryImportToken:(c,l)=>c.importTokenAttempts<Vt&&(l.data.error.status===Ht||l.data.error.status>=500),unverified:(c,{data:{error:l}})=>l.status===401&&(l.message==="Email is not verified"||l.error==="unverified-user"),hasSession:(c,l)=>{var h;return!!((h=l.data)!=null&&h.session)},hasMfaTicket:(c,l)=>{var h;return!!((h=l.data)!=null&&h.mfa)}},services:{signInPassword:(c,{email:l,password:h})=>de(l)?Et(h)?f("/signin/email-password",{email:l,password:h}):Promise.reject({error:pt}):Promise.reject({error:ue}),passwordlessSms:(c,{phoneNumber:l,options:h})=>{var y;return Qt(l)?(y=c.user)!=null&&y.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),f("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:l,options:ne(e,h)},c.accessToken.value)):f("/signin/passwordless/sms",{phoneNumber:l,options:ne(e,h)}):Promise.reject({error:zt})},passwordlessSmsOtp:(c,{phoneNumber:l,otp:h})=>Qt(l)?f("/signin/passwordless/sms/otp",{phoneNumber:l,otp:h}):Promise.reject({error:zt}),passwordlessEmail:(c,{email:l,options:h})=>{var y;return de(l)?(y=c.user)!=null&&y.isAnonymous?f("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:l,options:ne(e,h)},c.accessToken.value):f("/signin/passwordless/email",{email:l,options:ne(e,h)}):Promise.reject({error:ue})},signInAnonymous:c=>f("/signin/anonymous"),signInMfaTotp:(c,l)=>{var h;const y=l.ticket||((h=c.mfa)==null?void 0:h.ticket);return y?sn(y)?f("/signin/mfa/totp",{ticket:y,otp:l.otp}):Promise.reject({error:Gr}):Promise.reject({error:Vr})},signInSecurityKeyEmail:async(c,{email:l})=>{if(!de(l))throw new Ve(ue);const h=await f("/signin/webauthn",{email:l});let y;try{y=await Yi(h)}catch(v){throw new Ve(v)}return f("/signin/webauthn/verify",{email:l,credential:y})},refreshToken:async(c,l)=>{const h=l.type==="TRY_TOKEN"?l.token:c.refreshToken.value;return{session:await f("/token",{refreshToken:h}),error:null}},signout:(c,l)=>f("/signout",{refreshToken:c.refreshToken.value,all:!!l.all}),signUpEmailPassword:async(c,{email:l,password:h,options:y})=>{var v;return de(l)?Et(h)?(v=c.user)!=null&&v.isAnonymous?f("/user/deanonymize",{signInMethod:"email-password",email:l,password:h,options:ne(e,y)},c.accessToken.value):f("/signup/email-password",{email:l,password:h,options:ne(e,y)}):Promise.reject({error:pt}):Promise.reject({error:ue})},signUpSecurityKey:async(c,{email:l,options:h})=>{if(!de(l))return Promise.reject({error:ue});const y=h==null?void 0:h.nickname;y&&delete h.nickname;const v=await f("/signup/webauthn",{email:l,options:h});let w;try{w=await en(v)}catch(T){throw new Ve(T)}return f("/signup/webauthn/verify",{credential:w,options:{redirectTo:h==null?void 0:h.redirectTo,nickname:y}})},importRefreshToken:async c=>{if(c.user&&c.refreshToken.value&&c.accessToken.value&&c.accessToken.expiresAt)return{session:{accessToken:c.accessToken.value,accessTokenExpiresIn:c.accessToken.expiresAt.getTime()-Date.now(),refreshToken:c.refreshToken.value,user:c.user},error:null};let l=null;if(s){const y=Ke("refreshToken")||null;if(y)try{return{session:await f("/token",{refreshToken:y}),error:null}}catch(v){l=v.error}else{const v=Ke("error");if(v)return Promise.reject({session:null,error:{status:re,error:v,message:Ke("errorDescription")||v}})}}const h=await u(qe);if(h)try{return{session:await f("/token",{refreshToken:h}),error:null}}catch(y){l=y.error}return l?Promise.reject({error:l,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:c})=>Math.pow(2,c-1)*5e3}})},cn=({backendUrl:t,clientUrl:e,interpreter:r})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changeEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:n=>ue}),saveRequestError:U({error:(n,{data:{error:i}})=>i}),reportError:W(n=>({type:"ERROR",error:n.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!de(i)},services:{requestChange:async(n,{email:i,options:o})=>(await le(`${t}/user/email/change`,{newEmail:i,options:ne(e,o)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),un=({backendUrl:t,interpreter:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidPassword",actions:"saveInvalidPasswordError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidPasswordError:U({error:r=>pt}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!Et(n)},services:{requestChange:(r,{password:n,ticket:i})=>le(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Qi=({backendUrl:t,interpreter:e})=>ve({schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,id:"enableMfa",initial:"idle",context:{error:null,imageUrl:null,secret:null},states:{idle:{initial:"initial",on:{GENERATE:"generating"},states:{initial:{},error:{}}},generating:{invoke:{src:"generate",id:"generate",onDone:{target:"generated",actions:["reportGeneratedSuccess","saveGeneration"]},onError:{actions:["saveError","reportGeneratedError"],target:"idle.error"}}},generated:{initial:"idle",states:{idle:{initial:"idle",on:{ACTIVATE:[{cond:"invalidMfaType",actions:"saveInvalidMfaTypeError",target:".error"},{cond:"invalidMfaCode",actions:"saveInvalidMfaCodeError",target:".error"},{target:"activating"}]},states:{idle:{},error:{}}},activating:{invoke:{src:"activate",id:"activate",onDone:{target:"activated",actions:"reportSuccess"},onError:{actions:["saveError","reportError"],target:"idle.error"}}},activated:{type:"final"}}}}},{actions:{saveInvalidMfaTypeError:U({error:r=>Fr}),saveInvalidMfaCodeError:U({error:r=>qr}),saveError:U({error:(r,{data:{error:n}})=>n}),saveGeneration:U({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:W((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS"),reportGeneratedSuccess:W("GENERATED"),reportGeneratedError:W(r=>({type:"GENERATED_ERROR",error:r.error}))},guards:{invalidMfaCode:(r,{code:n})=>!n,invalidMfaType:(r,{activeMfaType:n})=>!n||n!=="totp"},services:{generate:async r=>{const{data:n}=await on(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>le(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ln=({backendUrl:t,clientUrl:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:r=>ue}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{requestChange:(r,{email:n,options:i})=>le(`${t}/user/password/reset`,{email:n,options:ne(e,i)})}}),dn=({backendUrl:t,clientUrl:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"sendVerificationEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"request",id:"request",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:r=>ue}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{request:async(r,{email:n,options:i})=>(await le(`${t}/user/email/send-verification-email`,{email:n,options:ne(e,i)})).data}});let Xt=class{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:o,clientUrl:s,devTools:u,...d}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=o,this.clientUrl=s,this._machine=an({...d,backendUrl:o,clientUrl:s,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window<"u"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",f=>{var c;const l=(c=this.interpreter)==null?void 0:c.getSnapshot().context.refreshToken.value;this.interpreter&&f.data!==l&&this.interpreter.send("TRY_TOKEN",{token:f.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){const i={...this.machine.context};r&&(i.user=r.user,i.refreshToken.value=r.refreshToken??null,i.accessToken.value=r.accessToken??null,i.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const o=this.machine.withContext(i);this._interpreter||(this._interpreter=n||xe(o,{devTools:e})),(!this._started||typeof window>"u")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(s=>s())),this._interpreter.start(o.initialState),this._subscriptionsQueue.forEach(s=>s(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}};class hn extends Xt{constructor({...e}){super({...e,autoSignIn:wt()&&e.autoSignIn,autoRefreshToken:wt()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const Xi=hn,fn=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await le("/user/webauthn/add",{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await en(n)}catch(s){throw new Ve(s)}const{data:o}=await le(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:o,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},pn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),vn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),Zi=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),eo=(t,e)=>new Promise(r=>{t.send("ACTIVATE",{activeMfaType:"totp",code:e}),t.onTransition(n=>{n.matches({generated:"activated"})?r({error:null,isActivated:!0,isError:!1}):n.matches({generated:{idle:"error"}})&&r({error:n.context.error,isActivated:!1,isError:!0})})}),yn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),mn=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),gn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:se,user:null,accessToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null})})}),wn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:s.context.mfa,user:null}):s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.context.user})})}),Zt=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({error:o.context.errors.registration||null,isError:!0,isSuccess:!1}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),En=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:"signedIn"})&&r({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),Sn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:s.context.user})})}),er=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(o=>{o.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):o.matches("registration.incomplete.failed")&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Tn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(o=>{o.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:o.context.user,accessToken:o.context.accessToken.value}):o.matches({registration:{incomplete:"failed"}})&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),bn=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:zr});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),tr=(t,e,r,n)=>new Promise(i=>{const{changed:o,context:s}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!o)return i({error:se,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(u=>{u.matches("registration.incomplete.failed")?i({accessToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:u.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),An=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:se,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({accessToken:null,error:s.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})});class On{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:o,refreshIntervalTime:s,start:u=!0}){var d;this.url=e,this._client=new Xt({backendUrl:e,clientUrl:typeof window<"u"&&((d=window.location)==null?void 0:d.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:o,refreshIntervalTime:s})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?ye(await An(r,n,i)):ye(await tr(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await gn(r);return{...ye(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,o=Wt(`${this._client.backendUrl}/signin/provider/${n}`,ne(this._client.clientUrl,i));return wt()&&(window.location.href=o),{providerUrl:o,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await wn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:Yr}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ye(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await En(r,e.email);return{...ye(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:o}=await Zt(r,n,i);return{session:null,mfa:null,error:o}}if("phoneNumber"in e&&"otp"in e){const n=await Tn(r,e.phoneNumber,e.otp);return{...ye(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await er(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Sn(r,e.otp,e.ticket);return{...ye(n),mfa:null}}return{error:Jr,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await bn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=xe(ln(this._client)).start(),{error:i}=await yn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=xe(un(this._client)).start(),{error:i}=await vn(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=xe(dn(this._client)).start(),{error:i}=await mn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=xe(cn(this._client)).start(),{error:i}=await pn(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await Zt(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await er(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await tr(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await fn(this._client,e);return{error:r,key:n}}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:o})=>{i.type==="TOKEN_CHANGED"&&e(He(o))});return()=>n==null?void 0:n.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:o})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,He(o))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e;return((e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)??void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Bn(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const i=e||r.getSnapshot().context.refreshToken.value;if(!i)return n({session:null,error:Hr});const{changed:o}=r.send("TRY_TOKEN",{token:i});if(!o)return n({session:null,error:Kr});r.onTransition(s=>{s.matches({token:{idle:"error"}})?n({session:null,error:Wr}):s.event.type==="TOKEN_CHANGED"&&n({session:He(s.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return He((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n(`The state machine is not yet ready after ${15} seconds.`),15e3);e.onTransition(o=>{if(!o.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var kn=typeof self=="object"?self.FormData:window.FormData,to=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ro(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var rr={exports:{}};(function(t,e){var r=typeof self<"u"?self:to,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function d(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(a){return a&&f.indexOf(Object.prototype.toString.call(a))>-1};function l(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function h(a){return typeof a!="string"&&(a=String(a)),a}function y(a){var p={next:function(){var E=a.shift();return{done:E===void 0,value:E}}};return u.iterable&&(p[Symbol.iterator]=function(){return p}),p}function v(a){this.map={},a instanceof v?a.forEach(function(p,E){this.append(E,p)},this):Array.isArray(a)?a.forEach(function(p){this.append(p[0],p[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(p){this.append(p,a[p])},this)}v.prototype.append=function(a,p){a=l(a),p=h(p);var E=this.map[a];this.map[a]=E?E+", "+p:p},v.prototype.delete=function(a){delete this.map[l(a)]},v.prototype.get=function(a){return a=l(a),this.has(a)?this.map[a]:null},v.prototype.has=function(a){return this.map.hasOwnProperty(l(a))},v.prototype.set=function(a,p){this.map[l(a)]=h(p)},v.prototype.forEach=function(a,p){for(var E in this.map)this.map.hasOwnProperty(E)&&a.call(p,this.map[E],E,this)},v.prototype.keys=function(){var a=[];return this.forEach(function(p,E){a.push(E)}),y(a)},v.prototype.values=function(){var a=[];return this.forEach(function(p){a.push(p)}),y(a)},v.prototype.entries=function(){var a=[];return this.forEach(function(p,E){a.push([E,p])}),y(a)},u.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function w(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function T(a){return new Promise(function(p,E){a.onload=function(){p(a.result)},a.onerror=function(){E(a.error)}})}function O(a){var p=new FileReader,E=T(p);return p.readAsArrayBuffer(a),E}function S(a){var p=new FileReader,E=T(p);return p.readAsText(a),E}function A(a){for(var p=new Uint8Array(a),E=new Array(p.length),C=0;C<p.length;C++)E[C]=String.fromCharCode(p[C]);return E.join("")}function N(a){if(a.slice)return a.slice(0);var p=new Uint8Array(a.byteLength);return p.set(new Uint8Array(a)),p.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&d(a)?(this._bodyArrayBuffer=N(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||c(a))?this._bodyArrayBuffer=N(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?w(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(O)}),this.text=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return S(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var q=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function P(a){var p=a.toUpperCase();return q.indexOf(p)>-1?p:a}function I(a,p){p=p||{};var E=p.body;if(a instanceof I){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,p.headers||(this.headers=new v(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!E&&a._bodyInit!=null&&(E=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new v(p.headers)),this.method=P(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function j(a){var p=new FormData;return a.trim().split("&").forEach(function(E){if(E){var C=E.split("="),_=C.shift().replace(/\+/g," "),b=C.join("=").replace(/\+/g," ");p.append(decodeURIComponent(_),decodeURIComponent(b))}}),p}function k(a){var p=new v,E=a.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var _=C.split(":"),b=_.shift().trim();if(b){var ee=_.join(":").trim();p.append(b,ee)}}),p}R.call(I.prototype);function x(a,p){p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in p?p.statusText:"OK",this.headers=new v(p.headers),this.url=p.url||"",this._initBody(a)}R.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},x.error=function(){var a=new x(null,{status:0,statusText:""});return a.type="error",a};var J=[301,302,303,307,308];x.redirect=function(a,p){if(J.indexOf(p)===-1)throw new RangeError("Invalid status code");return new x(null,{status:p,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(a,p){this.message=a,this.name=p;var E=Error(a);this.stack=E.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function K(a,p){return new Promise(function(E,C){var _=new I(a,p);if(_.signal&&_.signal.aborted)return C(new s.DOMException("Aborted","AbortError"));var b=new XMLHttpRequest;function ee(){b.abort()}b.onload=function(){var H={status:b.status,statusText:b.statusText,headers:k(b.getAllResponseHeaders()||"")};H.url="responseURL"in b?b.responseURL:H.headers.get("X-Request-URL");var he="response"in b?b.response:b.responseText;E(new x(he,H))},b.onerror=function(){C(new TypeError("Network request failed"))},b.ontimeout=function(){C(new TypeError("Network request failed"))},b.onabort=function(){C(new s.DOMException("Aborted","AbortError"))},b.open(_.method,_.url,!0),_.credentials==="include"?b.withCredentials=!0:_.credentials==="omit"&&(b.withCredentials=!1),"responseType"in b&&u.blob&&(b.responseType="blob"),_.headers.forEach(function(H,he){b.setRequestHeader(he,H)}),_.signal&&(_.signal.addEventListener("abort",ee),b.onreadystatechange=function(){b.readyState===4&&_.signal.removeEventListener("abort",ee)}),b.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=v,o.Request=I,o.Response=x),s.Headers=v,s.Request=I,s.Response=x,s.fetch=K,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(rr,rr.exports);const nr=ro(rr.exports),no=t=>{try{return btoa(t),t}catch{return encodeURIComponent(t)}},xn=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:o,adminSecret:s,onUploadProgress:u}={})=>{const d={};i&&(d["x-nhost-file-id"]=i),o&&(d["x-nhost-bucket-id"]=o),n&&(d["x-nhost-file-name"]=no(n)),s&&(d["x-hasura-admin-secret"]=s),r&&(d.Authorization=`Bearer ${r}`);const f=`${t}/files`;if(typeof XMLHttpRequest>"u")try{const c=await nr(f,{method:"POST",headers:d,body:e});return c.ok?{fileMetadata:await c.json(),error:null}:{error:{status:c.status,message:await c.text(),error:c.statusText},fileMetadata:null}}catch(c){return{error:{status:0,message:c.message,error:c.message},fileMetadata:null}}return new Promise(c=>{console.log("NOOOOOOO");let l=new XMLHttpRequest;l.responseType="json",l.onload=()=>l.status<200&&l.status>=300?c({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}):c({fileMetadata:l.response,error:null}),l.onerror=()=>c({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}),u&&l.upload.addEventListener("progress",u,!1),l.open("POST",f,!0),Object.entries(d).forEach(([h,y])=>{l.setRequestHeader(h,y)}),l.send(e)})};class In{constructor({url:e}){this.url=e}async upload(e){const{formData:r}=e;return xn(this.url,r,{accessToken:this.accessToken,adminSecret:this.accessToken,bucketId:e.bucketId,fileId:e.id,name:e.name})}async getPresignedUrl(e){try{const{fileId:r}=e,n=await nr(`${this.url}/files/${r}/presignedurl`,{method:"GET",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{presignedUrl:await n.json(),error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e,n=await nr(`${this.url}/files/${r}`,{method:"DELETE",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateAuthHeaders(){if(!(!this.adminSecret&&!this.accessToken))return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}const Rn=(t,e)=>{const r=Object.entries(e).map(([n,i])=>`${Array.from(n)[0]}=${i}`).join("&");return r?`${t}?${r}`:t};class Pn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new In({url:e}),this.setAdminSecret(r)}async upload(e){let r;return"file"in e?(r=new kn,r.append("file",e.file)):r=e.formData,this.api.upload({...e,formData:r})}getPublicUrl(e){const{fileId:r,...n}=e;return Rn(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{presignedUrl:r,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}const St={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},_n=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...St},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(t,e)=>!!t.file||!!e.file},actions:{incrementProgress:U({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:U({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:U({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:U({progress:t=>null,loaded:t=>0}),resetContext:U(t=>St),addFile:U({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new kn;i.append("file",n);let o=0;return xn(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:s=>{const u=s.total?Math.round(s.loaded*n.size/s.total):0,d=u-o;o=u,r({type:"UPLOAD_PROGRESS",progress:s.total?Math.round(u*100/s.total):0,loaded:u,additions:d})}}).then(({fileMetadata:s,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),s){const{id:d,bucketId:f}=s;r({type:"UPLOAD_DONE",id:d,bucketId:f})}}),()=>{}}}}),{pure:ir,sendParent:Tt}=vi,io=()=>ve({id:"files-list",schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,context:{progress:null,files:[],loaded:0,total:0},initial:"idle",on:{UPLOAD:{cond:"hasFileToDownload",actions:"addItem",target:"uploading"},ADD:{actions:"addItem"},REMOVE:{actions:"removeItem"}},states:{idle:{entry:["resetProgress","resetLoaded","resetTotal"],on:{CLEAR:{actions:"clearList",target:"idle"}}},uploading:{entry:["upload","startProgress","resetLoaded","resetTotal"],on:{UPLOAD_PROGRESS:{actions:["incrementProgress"]},UPLOAD_DONE:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],UPLOAD_ERROR:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],CANCEL:{actions:"cancel",target:"idle"}}},uploaded:{entry:"setUploaded",on:{CLEAR:{actions:"clearList",target:"idle"}}},error:{on:{CLEAR:{actions:"clearList",target:"idle"}}}}},{guards:{hasFileToDownload:(t,e)=>t.files.some(r=>r.getSnapshot().matches("idle"))||!!e.files,isAllUploaded:t=>t.files.every(e=>{var r;return(r=e.getSnapshot())==null?void 0:r.matches("uploaded")}),isAllUploadedOrError:t=>t.files.every(e=>{const r=e.getSnapshot();return(r==null?void 0:r.matches("error"))||(r==null?void 0:r.matches("uploaded"))})},actions:{incrementProgress:U((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:U({progress:t=>100,loaded:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetTotal:U({total:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>!e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetLoaded:U({loaded:t=>0}),startProgress:U({progress:t=>0}),resetProgress:U({progress:t=>null}),addItem:U((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"length"in e?Array.from(e):[e]:[],i=t.total+n.reduce((s,u)=>s+u.size,0),o=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(s=>Di(_n().withConfig({actions:{sendProgress:Tt((u,{additions:d})=>({type:"UPLOAD_PROGRESS",additions:d})),sendDone:Tt("UPLOAD_DONE"),sendError:Tt("UPLOAD_ERROR"),sendDestroy:Tt("REMOVE")}}).withContext({...St,file:s,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:o}}),removeItem:U({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:ir(t=>t.files.map(e=>W({type:"DESTROY"},{to:e.id}))),upload:ir((t,e)=>t.files.map(r=>W(e,{to:r.id}))),cancel:ir(t=>t.files.map(e=>W({type:"CANCEL"},{to:e.id})))}}),oo=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),so=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var o;return(o=i.getSnapshot())==null?void 0:o.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),ao=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function bt(t,e){const{backendUrl:r,subdomain:n,region:i}=t;if(r)return`${r}/v1/${e}`;if(!n)throw new Error("Either `backendUrl` or `subdomain` must be set.");const o=n.match(ao);if(o!=null&&o.groups){const{protocol:s="http",host:u,port:d=1337}=o.groups,f=lo(e);return f||`${s}://${u}:${d}/v1/${e}`}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${n}.${e}.${i}.nhost.run/v1`}function co(){return typeof window<"u"}function uo(){return typeof process<"u"&&process.env}function lo(t){return co()||!uo()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function Un(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new On({url:e,...t})}function Dn(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Nn({url:e,...t})}class Nn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};try{const o=await Gt(e,{body:JSON.stringify(r),headers:i,method:"POST"});if(!o.ok)throw new Error(o.statusText);let s;try{s=await o.json()}catch{s=await o.text()}return{res:{data:s,status:o.status,statusText:o.statusText},error:null}}catch(o){const s=o;return{res:null,error:{message:s.message,status:s.name==="AbortError"?0:500,error:s.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function ho(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function Cn(t){var e;let r;const n=t.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(r=(e=n[0].name)==null?void 0:e.value),r}function fo(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=Cn(n)}catch{}return{query:t,operationName:r}}const e=Cn(t);return{query:Se.print(t),operationName:e}}class po{constructor(e){const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...r){const[n,i]=r,o=ho(e,n,i),{headers:s,...u}=i||{},{query:d,operationName:f}=fo(o.document);try{const c=await Gt(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:f,query:d,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...s},...u});if(!c.ok)return{data:null,error:{error:c.statusText,message:c.statusText,status:c.status}};const{data:l,errors:h}=await c.json();return h?{data:null,error:h}:typeof l!="object"||Array.isArray(l)||l===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:l,error:null}}catch(c){const l=c;return{data:null,error:{message:l.message,status:l.name==="AbortError"?0:500,error:l.name==="AbortError"?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function Mn(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new po({url:e,...t})}function Ln(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Pn({url:e,...t})}const vo=t=>new jn(t);class jn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,adminSecret:s,devTools:u,start:d=!0,...f}){this.auth=Un({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,start:d,...f}),this.storage=Ln({adminSecret:s,...f}),this.functions=Dn({adminSecret:s,...f}),this.graphql=Mn({adminSecret:s,...f}),this.auth.onAuthStateChanged((c,l)=>{c==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(c=>{const l=c==null?void 0:c.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=s,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}g.AuthClient=Xt,g.AuthClientSSR=Xi,g.AuthCookieClient=hn,g.CodifiedError=Ve,g.EMAIL_NEEDS_VERIFICATION=Yr,g.HasuraAuthClient=On,g.HasuraStorageApi=In,g.HasuraStorageClient=Pn,g.INITIAL_FILE_CONTEXT=St,g.INITIAL_MACHINE_CONTEXT=vt,g.INVALID_EMAIL_ERROR=ue,g.INVALID_MFA_CODE_ERROR=qr,g.INVALID_MFA_TICKET_ERROR=Gr,g.INVALID_MFA_TYPE_ERROR=Fr,g.INVALID_PASSWORD_ERROR=pt,g.INVALID_PHONE_NUMBER_ERROR=zt,g.INVALID_REFRESH_TOKEN=Wr,g.INVALID_SIGN_IN_METHOD=Jr,g.MIN_PASSWORD_LENGTH=$r,g.NETWORK_ERROR_CODE=Ht,g.NHOST_JWT_EXPIRES_AT_KEY=Ge,g.NHOST_REFRESH_TOKEN_KEY=qe,g.NO_MFA_TICKET_ERROR=Vr,g.NO_REFRESH_TOKEN=Hr,g.NhostClient=jn,g.NhostFunctionsClient=Nn,g.OTHER_ERROR_CODE=Kt,g.REFRESH_TOKEN_MAX_ATTEMPTS=Vt,g.STATE_ERROR_CODE=_e,g.TOKEN_REFRESHER_RUNNING_ERROR=Kr,g.TOKEN_REFRESH_MARGIN=Br,g.USER_ALREADY_SIGNED_IN=se,g.USER_NOT_ANONYMOUS=Fi,g.USER_UNAUTHENTICATED=zr,g.VALIDATION_ERROR_CODE=re,g.activateMfaPromise=eo,g.addSecurityKeyPromise=fn,g.appendImageTransformationParameters=Rn,g.changeEmailPromise=pn,g.changePasswordPromise=vn,g.createAuthClient=Un,g.createAuthMachine=an,g.createChangeEmailMachine=cn,g.createChangePasswordMachine=un,g.createEnableMfaMachine=Qi,g.createFileUploadMachine=_n,g.createFunctionsClient=Dn,g.createGraphqlClient=Mn,g.createMultipleFilesUploadMachine=io,g.createNhostClient=vo,g.createResetPasswordMachine=ln,g.createSendVerificationEmailMachine=dn,g.createStorageClient=Ln,g.encodeQueryParameters=Wt,g.generateQrCodePromise=Zi,g.getAuthenticationResult=ye,g.getFetch=on,g.getParameterByName=Ke,g.getSession=He,g.isBrowser=wt,g.isValidEmail=de,g.isValidPassword=Et,g.isValidPhoneNumber=Qt,g.isValidTicket=sn,g.localStorageGetter=tn,g.localStorageSetter=rn,g.postFetch=le,g.removeParameterFromWindow=Jt,g.resetPasswordPromise=yn,g.rewriteRedirectTo=ne,g.sendVerificationEmailPromise=mn,g.signInAnonymousPromise=gn,g.signInEmailPasswordPromise=wn,g.signInEmailPasswordlessPromise=Zt,g.signInEmailSecurityKeyPromise=En,g.signInMfaTotpPromise=Sn,g.signInSmsPasswordlessOtpPromise=Tn,g.signInSmsPasswordlessPromise=er,g.signOutPromise=bn,g.signUpEmailPasswordPromise=tr,g.signUpEmailSecurityKeyPromise=An,g.uploadFilePromise=oo,g.uploadMultipleFilesPromise=so,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
16
+ Event: `).concat(JSON.stringify(h.data)));return n.scheduler.schedule(function(){n.forward(h);var y=n._nextState(h);n.update(y,h)}),n._state},this.sendTo=function(u,l,h){var y=n.parent&&(l===ie.Parent||n.parent.id===l),v=y?n.parent:L(l)?n.children.get(l)||dt.get(l):ei(l)?l:void 0;if(!v){if(!y)throw new Error("Unable to send event to child '".concat(l,"' from service '").concat(n.id,"'."));G||z(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(u.type));return}if("machine"in v){if(n.status!==Y.Stopped||n.parent!==v||n.state.done){var w=m(m({},u),{name:u.name===It?"".concat(Oe(n.id)):u.name,origin:n.sessionId});!h&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,w]):v.send(w)}}else!h&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,u.data]):v.send(u.data)},this._exec=function(u,l,h,y){y===void 0&&(y=n.machine.options.actions);var v=u.exec||st(u.type,y),w=B(v)?v:v?v.exec:u.exec;if(w)try{return w(l,h.data,n.machine.config.predictableActionArguments?{action:u,_event:h}:{action:u,state:n.state,_event:h})}catch(J){throw n.parent&&n.parent.send({type:"xstate.error",data:J}),J}switch(u.type){case ge:var T=u;if(typeof T.delay=="number"){n.defer(T);return}else T.to?n.sendTo(T._event,T.to,h===we):n.send(T._event);break;case kt:n.cancel(u.sendId);break;case Ye:{if(n.status!==Y.Running)return;var O=u.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[O.id||O.type])break;if(O.type===$.Invoke){var S=Er(O.src),A=n.machine.options.services?n.machine.options.services[S.type]:void 0,N=O.id,R=O.data;G||z(!("forward"in O),"`forward` property is deprecated (found in invocation of '".concat(O.src,"' in in machine '").concat(n.machine.id,"'). ")+"Please use `autoForward` instead.");var q="autoForward"in O?O.autoForward:!!O.forward;if(!A){G||z(!1,"No service found for invocation '".concat(O.src,"' in machine '").concat(n.machine.id,"'."));return}var P=R?nt(R,l,h):void 0;if(typeof A=="string")return;var I=B(A)?A(l,h.data,{data:P,src:S,meta:O.meta}):A;if(!I)return;var j=void 0;ae(I)&&(I=P?I.withContext(P):I,j={autoForward:q}),n.spawn(I,N,j)}else n.spawnActivity(O);break}case We:{n.stopChild(u.activity.id);break}case Qe:var k=u.label,x=u.value;k?n.logger(k,x):n.logger(x);break;default:G||z(!1,"No implementation found for action type '".concat(u.type,"'"));break}};var i=m(m({},t.defaultOptions),r),o=i.clock,s=i.logger,c=i.parent,d=i.id,f=d!==void 0?d:e.id;this.id=f,this.logger=s,this.clock=o,this.parent=c,this.options=i,this.scheduler=new Lr({deferEvents:this.options.deferEvents}),this.sessionId=dt.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:ke(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return G||z(this.status!==Y.NotStarted,"Attempted to read state from uninitialized service '".concat(this.id,"'. Make sure the service is started first.")),this._state},enumerable:!1,configurable:!0}),t.prototype.execute=function(e,r){var n,i;try{for(var o=M(e.actions),s=o.next();!s.done;s=o.next()){var c=s.value;this.exec(c,e,r)}}catch(d){n={error:d}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,o,s,c,d,f,u,l=this;if(e._sessionid=this.sessionId,this._state=e,(!this.machine.config.predictableActionArguments||r===we)&&this.options.execute)this.execute(this.state);else for(var h=void 0;h=this._outgoingQueue.shift();)h[0].send(h[1]);if(this.children.forEach(function(j){l.state.children[j.id]=j}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var y=M(this.eventListeners),v=y.next();!v.done;v=y.next()){var w=v.value;w(e.event)}}catch(j){n={error:j}}finally{try{v&&!v.done&&(i=y.return)&&i.call(y)}finally{if(n)throw n.error}}try{for(var T=M(this.listeners),O=T.next();!O.done;O=T.next()){var w=O.value;w(e,e.event)}}catch(j){o={error:j}}finally{try{O&&!O.done&&(s=T.return)&&s.call(T)}finally{if(o)throw o.error}}try{for(var S=M(this.contextListeners),A=S.next();!A.done;A=S.next()){var N=A.value;N(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(j){c={error:j}}finally{try{A&&!A.done&&(d=S.return)&&d.call(S)}finally{if(c)throw c.error}}if(this.state.done){var R=e.configuration.find(function(j){return j.type==="final"&&j.parent===l.machine}),q=R&&R.doneData?nt(R.doneData,e.context,r):void 0;try{for(var P=M(this.doneListeners),I=P.next();!I.done;I=P.next()){var w=I.value;w(Me(this.id,q))}}catch(j){f={error:j}}finally{try{I&&!I.done&&(u=P.return)&&u.call(P)}finally{if(f)throw f.error}}this._stop(),this._stopChildren()}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===Y.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this,o=it(e,r,n);this.listeners.add(o.next),this.status!==Y.NotStarted&&o.next(this.state);var s=function(){i.doneListeners.delete(s),i.stopListeners.delete(s),o.complete()};return this.status===Y.Stopped?o.complete():(this.onDone(s),this.onStop(s)),{unsubscribe:function(){i.listeners.delete(o.next),i.doneListeners.delete(s),i.stopListeners.delete(s)}}},t.prototype.onEvent=function(e){return this.eventListeners.add(e),this},t.prototype.onSend=function(e){return this.sendListeners.add(e),this},t.prototype.onChange=function(e){return this.contextListeners.add(e),this},t.prototype.onStop=function(e){return this.stopListeners.add(e),this},t.prototype.onDone=function(e){return this.doneListeners.add(e),this},t.prototype.off=function(e){return this.listeners.delete(e),this.eventListeners.delete(e),this.sendListeners.delete(e),this.stopListeners.delete(e),this.doneListeners.delete(e),this.contextListeners.delete(e),this},t.prototype.start=function(e){var r=this;if(this.status===Y.Running)return this;this.machine._init(),dt.register(this.sessionId,this),this.initialized=!0,this.status=Y.Running;var n=e===void 0?this.initialState:ke(this,function(){return Ai(e)?r.machine.resolveState(e):r.machine.resolveState(oe.from(e,r.machine.context))});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(function(){r.update(n,we)}),this},t.prototype._stopChildren=function(){this.children.forEach(function(e){B(e.stop)&&e.stop()}),this.children.clear()},t.prototype._stop=function(){var e,r,n,i,o,s,c,d,f,u;try{for(var l=M(this.listeners),h=l.next();!h.done;h=l.next()){var y=h.value;this.listeners.delete(y)}}catch(P){e={error:P}}finally{try{h&&!h.done&&(r=l.return)&&r.call(l)}finally{if(e)throw e.error}}try{for(var v=M(this.stopListeners),w=v.next();!w.done;w=v.next()){var y=w.value;y(),this.stopListeners.delete(y)}}catch(P){n={error:P}}finally{try{w&&!w.done&&(i=v.return)&&i.call(v)}finally{if(n)throw n.error}}try{for(var T=M(this.contextListeners),O=T.next();!O.done;O=T.next()){var y=O.value;this.contextListeners.delete(y)}}catch(P){o={error:P}}finally{try{O&&!O.done&&(s=T.return)&&s.call(T)}finally{if(o)throw o.error}}try{for(var S=M(this.doneListeners),A=S.next();!A.done;A=S.next()){var y=A.value;this.doneListeners.delete(y)}}catch(P){c={error:P}}finally{try{A&&!A.done&&(d=S.return)&&d.call(S)}finally{if(c)throw c.error}}if(!this.initialized)return this;this.initialized=!1,this.status=Y.Stopped,this._initialState=void 0;try{for(var N=M(Object.keys(this.delayedEventsMap)),R=N.next();!R.done;R=N.next()){var q=R.value;this.clock.clearTimeout(this.delayedEventsMap[q])}}catch(P){f={error:P}}finally{try{R&&!R.done&&(u=N.return)&&u.call(N)}finally{if(f)throw f.error}}this.scheduler.clear(),this.scheduler=new Lr({deferEvents:this.options.deferEvents})},t.prototype.stop=function(){var e=this,r=this.scheduler;return this._stop(),r.schedule(function(){var n=Q({type:"xstate.stop"}),i=ke(e,function(){var o=V(F([],D(e.state.configuration),!1).sort(function(u,l){return l.order-u.order}).map(function(u){return ce(u.onExit,e.machine.options.actions)})),s=D(Le(e.machine,e.state,e.state.context,n,[o],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),c=s[0],d=s[1],f=new oe({value:e.state.value,context:d,_event:n,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:c.filter(function(u){return u.type!==me&&(u.type!==ge||!!u.to&&u.to!==ie.Internal)}),activities:{},events:[],configuration:[],transitions:[],children:{},done:e.state.done,tags:e.state.tags,machine:e.machine});return f.changed=!0,f});e.update(i,n),e._stopChildren(),dt.free(e.sessionId)}),this},t.prototype.batch=function(e){var r=this;if(this.status===Y.NotStarted&&this.options.deferEvents)G||z(!1,"".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,`" and are deferred. Make sure .start() is called for this service.
17
+ Event: `).concat(JSON.stringify(event)));else if(this.status!==Y.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,o,s=r.state,c=!1,d=[],f=function(y){var v=Q(y);r.forward(v),s=ke(r,function(){return r.machine.transition(s,v,void 0,n||void 0)}),d.push.apply(d,F([],D(r.machine.config.predictableActionArguments?s.actions:s.actions.map(function(w){return Oi(w,s)})),!1)),c=c||!!s.changed};try{for(var u=M(e),l=u.next();!l.done;l=u.next()){var h=l.value;f(h)}}catch(y){i={error:y}}finally{try{l&&!l.done&&(o=u.return)&&o.call(u)}finally{if(i)throw i.error}}s.changed=c,s.actions=d,r.update(s,Q(e[e.length-1]))})}},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype._nextState=function(e,r){var n=this;r===void 0&&(r=!!this.machine.config.predictableActionArguments&&this._exec);var i=Q(e);if(i.name.indexOf(xt)===0&&!this.state.nextEvents.some(function(s){return s.indexOf(xt)===0}))throw i.data.data;var o=ke(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return o},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=M(this.forwardTo),o=i.next();!o.done;o=i.next()){var s=o.value,c=this.children.get(s);if(!c)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(s,"'."));c.send(e)}}catch(d){r={error:d}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this;this.delayedEventsMap[e.id]=this.clock.setTimeout(function(){e.to?r.sendTo(e._event,e.to,!0):r.send(e._event)},e.delay)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions),this._exec(e,r.context,r._event,n)},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);r&&(this.removeChild(e),B(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==Y.Running)return Nt(e,r);if(vr(e))return this.spawnPromise(Promise.resolve(e),r);if(B(e))return this.spawnCallback(e,r);if(wi(e))return this.spawnActor(e,r);if(Zn(e))return this.spawnObservable(e,r);if(ae(e))return this.spawnMachine(e,m(m({},n),{id:r}));if(Jn(e))return this.spawnBehavior(e,r);throw new Error('Unable to spawn entity "'.concat(r,'" of type "').concat(typeof e,'".'))},t.prototype.spawnMachine=function(e,r){var n=this;r===void 0&&(r={});var i=new t(e,m(m({},this.options),{parent:this,id:r.id||e.id})),o=m(m({},jt),r);o.sync&&i.onTransition(function(c){n.send(Ze,{state:c,id:i.id})});var s=i;return this.children.set(i.id,s),o.autoForward&&this.forwardTo.add(i.id),i.onDone(function(c){n.removeChild(i.id),n.send(Q(c,{origin:i.id}))}).start(),s},t.prototype.spawnBehavior=function(e,r){var n=Pi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,o=!1,s;e.then(function(d){o||(s=d,i.removeChild(r),i.send(Q(Me(r,d),{origin:r})))},function(d){if(!o){i.removeChild(r);var f=Oe(r,d);try{i.send(Q(f,{origin:r}))}catch(u){ni(d,u,r),i.devTools&&i.devTools.send(f,i.state),i.machine.strict&&i.stop()}}});var c=(n={id:r,send:function(){},subscribe:function(d,f,u){var l=it(d,f,u),h=!1;return e.then(function(y){h||(l.next(y),!h&&l.complete())},function(y){h||l.error(y)}),{unsubscribe:function(){return h=!0}}},stop:function(){o=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return s}},n[fe]=function(){return this},n);return this.children.set(r,c),c},t.prototype.spawnCallback=function(e,r){var n,i=this,o=!1,s=new Set,c=new Set,d,f=function(h){d=h,c.forEach(function(y){return y(h)}),!o&&i.send(Q(h,{origin:r}))},u;try{u=e(f,function(h){s.add(h)})}catch(h){this.send(Oe(r,h))}if(vr(u))return this.spawnPromise(u,r);var l=(n={id:r,send:function(h){return s.forEach(function(y){return y(h)})},subscribe:function(h){var y=it(h);return c.add(y.next),{unsubscribe:function(){c.delete(y.next)}}},stop:function(){o=!0,B(u)&&u()},toJSON:function(){return{id:r}},getSnapshot:function(){return d}},n[fe]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnObservable=function(e,r){var n,i=this,o,s=e.subscribe(function(d){o=d,i.send(Q(d,{origin:r}))},function(d){i.removeChild(r),i.send(Q(Oe(r,d),{origin:r}))},function(){i.removeChild(r),i.send(Q(Me(r),{origin:r}))}),c=(n={id:r,send:function(){},subscribe:function(d,f,u){return e.subscribe(d,f,u)},stop:function(){return s.unsubscribe()},getSnapshot:function(){return o},toJSON:function(){return{id:r}}},n[fe]=function(){return this},n);return this.children.set(r,c),c},t.prototype.spawnActor=function(e,r){return this.children.set(r,e),e},t.prototype.spawnActivity=function(e){var r=this.machine.options&&this.machine.options.activities?this.machine.options.activities[e.type]:void 0;if(!r){G||z(!1,"No implementation found for activity '".concat(e.type,"'"));return}var n=r(this.state.context,e);this.spawnEffect(e.id,n)},t.prototype.spawnEffect=function(e,r){var n;this.children.set(e,(n={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},stop:r||void 0,getSnapshot:function(){},toJSON:function(){return{id:e}}},n[fe]=function(){return this},n))},t.prototype.attachDev=function(){var e=Lt();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var r=typeof this.options.devTools=="object"?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(m(m({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:m({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Ri(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[fe]=function(){return this},t.prototype.getSnapshot=function(){return this.status===Y.NotStarted?this.initialState:this._state},t.defaultOptions={execute:!0,deferEvents:!0,clock:{setTimeout:function(e,r){return setTimeout(e,r)},clearTimeout:function(e){return clearTimeout(e)}},logger:console.log.bind(console),devTools:!1},t.interpret=xe,t}(),Ui=function(t){return L(t)?m(m({},jt),{name:t}):m(m(m({},jt),{name:ti()}),t)};function Di(t,e){var r=Ui(e);return yi(function(n){if(!G){var i=ae(t)||B(t);z(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(ae(t)?t.id:"undefined",'") outside of a service. This will have no effect.'))}return n?n.spawn(t,r.name,r):Nt(t,r.name)})}function xe(t,e){var r=new _i(t,e);return r}function Ni(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function ht(t){return m(m({type:Xe},t),{toJSON:function(){t.onDone,t.onError;var e=Ot(t,["onDone","onError"]);return m(m({},e),{type:Xe,src:Ni(t.src)})}})}var Ie="",$t="#",Fe="*",Re={},Pe=function(t){return t[0]===$t},Ci=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},Mi=function(t,e,r){var n=r.slice(0,-1).some(function(o){return!("cond"in o)&&!("in"in o)&&(L(o.target)||ae(o.target))}),i=e===Ie?"the transient event":"event '".concat(e,"'");z(!n,"One or more transitions for ".concat(i," on state '").concat(t.id,"' are unreachable. ")+"Make sure that the default transition is the last one defined.")},Li=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var o=this,s;this.config=e,this._context=n,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.tags=[],this.options=Object.assign(Ci(),r),this.parent=i==null?void 0:i.parent,this.key=this.config.key||(i==null?void 0:i.key)||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:lr),this.id=this.config.id||F([this.machine.key],D(this.path),!1).join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:(s=this.config.schema)!==null&&s!==void 0?s:{},this.description=this.config.description,G||z(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?Ne(this.config.states,function(f,u){var l,h=new t(f,{},void 0,{parent:o,key:u});return Object.assign(o.idMap,m((l={},l[h.id]=h,l),h.idMap)),h}):Re;var c=0;function d(f){var u,l;f.order=c++;try{for(var h=M(Ur(f)),y=h.next();!y.done;y=h.next()){var v=y.value;d(v)}}catch(w){u={error:w}}finally{try{y&&!y.done&&(l=h.return)&&l.call(h)}finally{if(u)throw u.error}}}d(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(f){var u=f.event;return u===Ie}):Ie in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=te(this.config.entry||this.config.onEntry).map(function(f){return Ae(f)}),this.onExit=te(this.config.exit||this.config.onExit).map(function(f){return Ae(f)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=te(this.config.invoke).map(function(f,u){var l,h;if(ae(f)){var y=ot(o.id,u);return o.machine.options.services=m((l={},l[y]=f,l),o.machine.options.services),ht({src:y,id:y})}else if(L(f.src)){var y=f.id||ot(o.id,u);return ht(m(m({},f),{id:y,src:f.src}))}else if(ae(f.src)||B(f.src)){var y=f.id||ot(o.id,u);return o.machine.options.services=m((h={},h[y]=f.src,h),o.machine.options.services),ht(m(m({id:y},f),{src:y}))}else{var v=f.src;return ht(m(m({id:ot(o.id,u)},f),{src:v}))}}),this.activities=te(this.config.activities).concat(this.invoke).map(function(f){return at(f)}),this.transition=this.transition.bind(this),this.tags=te(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||Dr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,o=n.activities,s=n.guards,c=n.services,d=n.delays;return new t(this.config,{actions:m(m({},i),e.actions),activities:m(m({},o),e.activities),guards:m(m({},s),e.guards),services:m(m({},c),e.services),delays:m(m({},d),e.delays)},r??this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return B(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:Ne(this.states,function(e){return e.definition}),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke,description:this.description,tags:this.tags}},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return this.definition},Object.defineProperty(t.prototype,"on",{get:function(){if(this.__cache.on)return this.__cache.on;var e=this.transitions;return this.__cache.on=e.reduce(function(r,n){return r[n.eventType]=r[n.eventType]||[],r[n.eventType].push(n),r},{})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transitions",{get:function(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)},enumerable:!1,configurable:!0}),t.prototype.getCandidates=function(e){if(this.__cache.candidates[e])return this.__cache.candidates[e];var r=e===Ie,n=this.transitions.filter(function(i){var o=i.eventType===e;return r?o:o||i.eventType===Fe});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(o,s){var c=B(o)?"".concat(e.id,":delay[").concat(s,"]"):o,d=Pr(c,e.id);return e.onEntry.push(pe(d,{delay:o})),e.onExit.push(Or(d)),d},i=Te(r)?r.map(function(o,s){var c=n(o.delay,s);return m(m({},o),{event:c})}):V(Object.keys(r).map(function(o,s){var c=r[o],d=L(c)?{target:c}:c,f=isNaN(+o)?o:+o,u=n(f,s);return te(d).map(function(l){return m(m({},l),{event:u,delay:f})})}));return i.map(function(o){var s=o.delay;return m(m({},e.formatTransition(o)),{delay:s})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof oe?e.value:De(e,this.delimiter);if(L(i)){var o=this.getStateNode(i).initial;return o!==void 0?this.getStateNodes((r={},r[i]=o,r)):[this,this.states[i]]}var s=Object.keys(i),c=[this];return c.push.apply(c,F([],D(V(s.map(function(d){return n.getStateNode(d).getStateNodes(i[d])}))),!1)),c},t.prototype.handles=function(e){var r=hr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof oe?e:oe.create(e),n=Array.from($e([],this.getStateNodes(r.value)));return new oe(m(m({},r),{value:this.resolve(r.value),configuration:n,done:lt(n,this),tags:Cr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),o=i.next(r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),o=this.getStateNode(i[0]),s=o._transition(e[i[0]],r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionParallelNode=function(e,r,n){var i,o,s={};try{for(var c=M(Object.keys(e)),d=c.next();!d.done;d=c.next()){var f=d.value,u=e[f];if(u){var l=this.getStateNode(f),h=l._transition(u,r,n);h&&(s[f]=h)}}}catch(S){i={error:S}}finally{try{d&&!d.done&&(o=c.return)&&o.call(c)}finally{if(i)throw i.error}}var y=Object.keys(s).map(function(S){return s[S]}),v=V(y.map(function(S){return S.transitions})),w=y.some(function(S){return S.transitions.length>0});if(!w)return this.next(r,n);var T=V(y.map(function(S){return S.entrySet})),O=V(Object.keys(s).map(function(S){return s[S].configuration}));return{transitions:v,entrySet:T,exitSet:V(y.map(function(S){return S.exitSet})),configuration:O,source:r,actions:V(Object.keys(s).map(function(S){return s[S].actions}))}},t.prototype._transition=function(e,r,n){return L(e)?this.transitionLeafNode(e,r,n):Object.keys(e).length===1?this.transitionCompoundNode(e,r,n):this.transitionParallelNode(e,r,n)},t.prototype.getTransitionData=function(e,r){return this._transition(e.value,e,Q(r))},t.prototype.next=function(e,r){var n,i,o=this,s=r.name,c=[],d=[],f;try{for(var u=M(this.getCandidates(s)),l=u.next();!l.done;l=u.next()){var h=l.value,y=h.cond,v=h.in,w=e.context,T=v?L(v)&&Pe(v)?e.matches(De(this.getStateNodeById(v).path,this.delimiter)):Pt(De(v,this.delimiter),zn(this.path.slice(0,-2))(e.value)):!0,O=!1;try{O=!y||wr(this.machine,y,w,r,e)}catch(R){throw new Error("Unable to evaluate guard '".concat(y.name||y.type,"' in transition for event '").concat(s,"' in state node '").concat(this.id,`':
18
+ `).concat(R.message))}if(O&&T){h.target!==void 0&&(d=h.target),c.push.apply(c,F([],D(h.actions),!1)),f=h;break}}}catch(R){n={error:R}}finally{try{l&&!l.done&&(i=u.return)&&i.call(u)}finally{if(n)throw n.error}}if(f){if(!d.length)return{transitions:[f],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:c};var S=V(d.map(function(R){return o.getRelativeStateNodes(R,e.historyValue)})),A=!!f.internal,N=[];return A||d.forEach(function(R){N.push.apply(N,F([],D(o.getExternalReentryNodes(R)),!1))}),{transitions:[f],entrySet:N,exitSet:A?[]:[this],configuration:S,source:e,actions:c}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=D(e.order>this.order?[e,this]:[this,e],2),i=n[0],o=n[1];i&&i!==o;)r.push(i),i=i.parent;return i!==o?[]:(r.push(o),r)},t.prototype.getActions=function(e,r,n,i,o,s,c){var d,f,u,l,h=this,y=$e([],s?this.getStateNodes(s.value):[this]);try{for(var v=M(e),w=v.next();!w.done;w=v.next()){var T=w.value;(!Be(y,T)||Be(n.entrySet,T.parent))&&n.entrySet.push(T)}}catch(k){d={error:k}}finally{try{w&&!w.done&&(f=v.return)&&f.call(v)}finally{if(d)throw d.error}}try{for(var O=M(y),S=O.next();!S.done;S=O.next()){var T=S.value;(!Be(e,T)||Be(n.exitSet,T.parent))&&n.exitSet.push(T)}}catch(k){u={error:k}}finally{try{S&&!S.done&&(l=O.return)&&l.call(O)}finally{if(u)throw u.error}}var A=V(n.entrySet.map(function(k){var x=[];if(k.type!=="final")return x;var J=k.parent;if(!J.parent)return x;x.push(Ce(k.id,k.doneData),Ce(J.id,k.doneData?nt(k.doneData,i,o):void 0));var K=J.parent;return K.type==="parallel"&&je(K).every(function(a){return lt(n.configuration,a)})&&x.push(Ce(K.id)),x}));n.exitSet.sort(function(k,x){return x.order-k.order}),n.entrySet.sort(function(k,x){return k.order-x.order});var N=new Set(n.entrySet),R=new Set(n.exitSet),q=Array.from(N).map(function(k){var x=k.onEntry,J=k.activities.map(function(K){return kr(K)});return ce(c?F(F([],D(x),!1),D(J),!1):F(F([],D(J),!1),D(x),!1),h.machine.options.actions)}).concat([A.map(Sr)]),P=Array.from(R).map(function(k){return ce(F(F([],D(k.onExit),!1),D(k.activities.map(function(x){return xr(x)})),!1),h.machine.options.actions)}),I=P.concat([ce(n.actions,this.machine.options.actions)]).concat(q);if(r){var j=ce(V(F([],D(e),!1).sort(function(k,x){return x.order-k.order}).map(function(k){return k.onExit})),this.machine.options.actions).filter(function(k){return k.type!==me&&(k.type!==ge||!!k.to&&k.to!==ie.Internal)});return I.concat([j])}return I},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var o=Q(r),s;if(e instanceof oe)s=n===void 0?e:this.resolveState(oe.from(e,n));else{var c=L(e)?this.resolve(tt(this.getResolvedPath(e))):this.resolve(e),d=n??this.machine.context;s=this.resolveState(oe.from(c,d))}if(!G&&o.name===Fe)throw new Error("An event cannot have the wildcard type ('".concat(Fe,"')"));if(this.strict&&!this.events.includes(o.name)&&!Wn(o.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(o.name,"'"));var f=this._transition(s.value,s,o)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:s,actions:[]},u=$e([],this.getStateNodes(s.value)),l=f.configuration.length?$e(u,f.configuration):u;return f.configuration=F([],D(l),!1),this.resolveTransition(f,s,s.context,i,o)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var o,s=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(o=e.actions).unshift.apply(o,F([],D(s),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,o){var s,c,d,f,u=this;o===void 0&&(o=we);var l=e.configuration,h=!r||e.transitions.length>0,y=h?e.configuration:r?r.configuration:[],v=lt(y,this),w=h?Si(this.machine,l):void 0,T=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,O=this.getActions(new Set(y),v,e,n,o,r,i),S=r?m({},r.activities):{};try{for(var A=M(O),N=A.next();!N.done;N=A.next()){var R=N.value;try{for(var q=(d=void 0,M(R)),P=q.next();!P.done;P=q.next()){var I=P.value;I.type===Ye?S[I.activity.id||I.activity.type]=I:I.type===We&&(S[I.activity.id||I.activity.type]=!1)}}catch(Z){d={error:Z}}finally{try{P&&!P.done&&(f=q.return)&&f.call(q)}finally{if(d)throw d.error}}}}catch(Z){s={error:Z}}finally{try{N&&!N.done&&(c=A.return)&&c.call(A)}finally{if(s)throw s.error}}var j=D(Le(this,r,n,o,O,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),k=j[0],x=j[1],J=D(Qn(k,function(Z){return Z.type===me||Z.type===ge&&Z.to===ie.Internal}),2),K=J[0],a=J[1],p=k.filter(function(Z){var Ue;return Z.type===Ye&&((Ue=Z.activity)===null||Ue===void 0?void 0:Ue.type)===Xe}),E=p.reduce(function(Z,Ue){return Z[Ue.activity.id]=mi(Ue.activity,u.machine,x,o),Z},r?m({},r.children):{}),C=new oe({value:w||r.value,context:x,_event:o,_sessionid:r?r._sessionid:null,historyValue:w?T?Xn(T,w):void 0:r?r.historyValue:void 0,history:!w||e.source?r:void 0,actions:w?a:[],activities:w?S:r?r.activities:{},events:[],configuration:y,transitions:e.transitions,children:E,done:v,tags:Cr(y),machine:this}),_=n!==x;C.changed=o.name===Ze||_;var b=C.history;b&&delete b.history;var ee=!v&&(this._transient||l.some(function(Z){return Z._transient}));if(!h&&(!ee||o.name===Ie))return C;var H=C;if(!v)for(ee&&(H=this.resolveRaisedTransition(H,{type:sr},o,i));K.length;){var he=K.shift();H=this.resolveRaisedTransition(H,he._event,o,i)}var yo=H.changed||(b?!!H.actions.length||_||typeof b.value!=typeof H.value||!Mr(H.value,b.value):void 0);return H.changed=yo,H.history=b,H},t.prototype.getStateNode=function(e){if(Pe(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var r=this.states[e];if(!r)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return r},t.prototype.getStateNodeById=function(e){var r=Pe(e)?e.slice($t.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&Pe(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=_t(e,this.delimiter).slice(),n=this;r.length;){var i=r.shift();if(!i.length)break;n=n.getStateNode(i)}return n},t.prototype.resolve=function(e){var r,n=this;if(!e)return this.initialStateValue||Re;switch(this.type){case"parallel":return Ne(this.initialStateValue,function(o,s){return o?n.getStateNode(s).resolve(e[s]||o):Re});case"compound":if(L(e)){var i=this.getStateNode(e);return i.type==="parallel"||i.type==="compound"?(r={},r[e]=i.initialStateValue,r):e}return Object.keys(e).length?Ne(e,function(o,s){return o?n.getStateNode(s).resolve(o):Re}):this.initialStateValue||{};default:return e||Re}},t.prototype.getResolvedPath=function(e){if(Pe(e)){var r=this.machine.idMap[e.slice($t.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return _t(e,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){var e;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var r;if(this.type==="parallel")r=fr(this.states,function(n){return n.initialStateValue||Re},function(n){return n.type!=="history"});else if(this.initial!==void 0){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));r=ut(this.states[this.initial])?this.initial:(e={},e[this.initial]=this.states[this.initial].initialStateValue,e)}else r={};return this.__cache.initialStateValue=r,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),t.prototype.getInitialState=function(e,r){this._init();var n=this.getStateNodes(e);return this.resolveTransition({configuration:n,entrySet:F([],D(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r??this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;L(r.target)?e=Pe(r.target)?tt(this.machine.getStateNodeById(r.target).path.slice(this.path.length-1)):r.target:e=r.target}return e},enumerable:!1,configurable:!0}),t.prototype.getRelativeStateNodes=function(e,r,n){return n===void 0&&(n=!0),n?e.type==="history"?e.resolveHistory(r):e.initialStateNodes:[e]},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var e=this;if(ut(this))return[this];if(this.type==="compound"&&!this.initial)return G||z(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=rt(this.initialStateValue);return V(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=D(e),n=r[0],i=r.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(n,"' from node with no states"));var o=this.getStateNode(n);if(o.type==="history")return o.resolveHistory();if(!this.states[n])throw new Error("Child state '".concat(n,"' does not exist on '").concat(this.id,"'"));return this.states[n].getFromRelativePath(i)},t.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:fr(this.states,function(r,n){if(!e)return r.historyValue();var i=L(e)?void 0:e[n];return r.historyValue(i||r.initialStateValue)},function(r){return!r.history})}},t.prototype.resolveHistory=function(e){var r=this;if(this.type!=="history")return[this];var n=this.parent;if(!e){var i=this.target;return i?V(rt(i).map(function(s){return n.getFromRelativePath(s)})):n.initialStateNodes}var o=Yn(n.path,"states")(e).current;return L(o)?[n.getStateNode(o)]:V(rt(o).map(function(s){return r.history==="deep"?n.getFromRelativePath(s):[n.states[s[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=V(Object.keys(this.states).map(function(n){return e.states[n].stateIds}));return[this.id].concat(r)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){var e,r,n,i;if(this.__cache.events)return this.__cache.events;var o=this.states,s=new Set(this.ownEvents);if(o)try{for(var c=M(Object.keys(o)),d=c.next();!d.done;d=c.next()){var f=d.value,u=o[f];if(u.states)try{for(var l=(n=void 0,M(u.events)),h=l.next();!h.done;h=l.next()){var y=h.value;s.add("".concat(y))}}catch(v){n={error:v}}finally{try{h&&!h.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}}catch(v){e={error:v}}finally{try{d&&!d.done&&(r=c.return)&&r.call(c)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(s)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter(function(r){return!(!r.target&&!r.actions.length&&r.internal)}).map(function(r){return r.eventType}));return Array.from(e)},enumerable:!1,configurable:!0}),t.prototype.resolveTarget=function(e){var r=this;if(e!==void 0)return e.map(function(n){if(!L(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var o=i?r.key+n:n;if(r.parent)try{var s=r.parent.getStateNodeByPath(o);return s}catch(c){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
19
+ `).concat(c.message))}else return r.getStateNodeByPath(o)})},t.prototype.formatTransition=function(e){var r=this,n=ri(e.target),i="internal"in e?e.internal:n?n.some(function(d){return L(d)&&d[0]===r.delimiter}):!0,o=this.machine.options.guards,s=this.resolveTarget(n),c=m(m({},e),{actions:ce(te(e.actions)),cond:gr(e.cond,o),target:s,source:this,internal:i,eventType:e.event,toJSON:function(){return m(m({},c),{target:c.target?c.target.map(function(d){return"#".concat(d.id)}):void 0,source:"#".concat(r.id)})}});return c},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var o=this.config.on,s=Fe,c=o[s],d=c===void 0?[]:c,f=Ot(o,[typeof s=="symbol"?s:s+""]);i=V(Object.keys(f).map(function(S){!G&&S===Ie&&z(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var A=be(S,f[S]);return G||Mi(n,S,A),A}).concat(be(Fe,d)))}var u=this.config.always?be("",this.config.always):[],l=this.config.onDone?be(String(Ce(this.id)),this.config.onDone):[];G||z(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var h=V(this.invoke.map(function(S){var A=[];return S.onDone&&A.push.apply(A,F([],D(be(String(Me(S.id)),S.onDone)),!1)),S.onError&&A.push.apply(A,F([],D(be(String(Oe(S.id)),S.onError)),!1)),A})),y=this.after,v=V(F(F(F(F([],D(l),!1),D(h),!1),D(i),!1),D(u),!1).map(function(S){return te(S).map(function(A){return n.formatTransition(A)})}));try{for(var w=M(y),T=w.next();!T.done;T=w.next()){var O=T.value;v.push(O)}}catch(S){e={error:S}}finally{try{T&&!T.done&&(r=w.return)&&r.call(w)}finally{if(e)throw e.error}}return v},t}(),jr=!1;function ve(t,e){return!G&&!t.predictableActionArguments&&!jr&&(jr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new Li(t,e)}var U=Rr,W=pe;/*! js-cookie v3.0.1 | MIT */function ft(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)t[n]=r[n]}return t}var ji={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Bt(t,e){function r(i,o,s){if(!(typeof document>"u")){s=ft({},e,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var c="";for(var d in s)s[d]&&(c+="; "+d,s[d]!==!0&&(c+="="+s[d].split(";")[0]));return document.cookie=i+"="+t.write(o,i)+c}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var o=document.cookie?document.cookie.split("; "):[],s={},c=0;c<o.length;c++){var d=o[c].split("="),f=d.slice(1).join("=");try{var u=decodeURIComponent(d[0]);if(s[u]=t.read(f,u),i===u)break}catch{}}return i?s[i]:s}}return Object.create({set:r,get:n,remove:function(i,o){r(i,"",ft({},o,{expires:-1}))},withAttributes:function(i){return Bt(this.converter,ft({},this.attributes,i))},withConverter:function(i){return Bt(ft({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Ft=Bt(ji,{path:"/"}),$i=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qt={exports:{}};(function(t,e){var r=typeof self<"u"?self:$i,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var c={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function d(a){return a&&DataView.prototype.isPrototypeOf(a)}if(c.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(a){return a&&f.indexOf(Object.prototype.toString.call(a))>-1};function l(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function h(a){return typeof a!="string"&&(a=String(a)),a}function y(a){var p={next:function(){var E=a.shift();return{done:E===void 0,value:E}}};return c.iterable&&(p[Symbol.iterator]=function(){return p}),p}function v(a){this.map={},a instanceof v?a.forEach(function(p,E){this.append(E,p)},this):Array.isArray(a)?a.forEach(function(p){this.append(p[0],p[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(p){this.append(p,a[p])},this)}v.prototype.append=function(a,p){a=l(a),p=h(p);var E=this.map[a];this.map[a]=E?E+", "+p:p},v.prototype.delete=function(a){delete this.map[l(a)]},v.prototype.get=function(a){return a=l(a),this.has(a)?this.map[a]:null},v.prototype.has=function(a){return this.map.hasOwnProperty(l(a))},v.prototype.set=function(a,p){this.map[l(a)]=h(p)},v.prototype.forEach=function(a,p){for(var E in this.map)this.map.hasOwnProperty(E)&&a.call(p,this.map[E],E,this)},v.prototype.keys=function(){var a=[];return this.forEach(function(p,E){a.push(E)}),y(a)},v.prototype.values=function(){var a=[];return this.forEach(function(p){a.push(p)}),y(a)},v.prototype.entries=function(){var a=[];return this.forEach(function(p,E){a.push([E,p])}),y(a)},c.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function w(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function T(a){return new Promise(function(p,E){a.onload=function(){p(a.result)},a.onerror=function(){E(a.error)}})}function O(a){var p=new FileReader,E=T(p);return p.readAsArrayBuffer(a),E}function S(a){var p=new FileReader,E=T(p);return p.readAsText(a),E}function A(a){for(var p=new Uint8Array(a),E=new Array(p.length),C=0;C<p.length;C++)E[C]=String.fromCharCode(p[C]);return E.join("")}function N(a){if(a.slice)return a.slice(0);var p=new Uint8Array(a.byteLength);return p.set(new Uint8Array(a)),p.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:c.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:c.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():c.arrayBuffer&&c.blob&&d(a)?(this._bodyArrayBuffer=N(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||u(a))?this._bodyArrayBuffer=N(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?w(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(O)}),this.text=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return S(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var q=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function P(a){var p=a.toUpperCase();return q.indexOf(p)>-1?p:a}function I(a,p){p=p||{};var E=p.body;if(a instanceof I){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,p.headers||(this.headers=new v(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!E&&a._bodyInit!=null&&(E=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new v(p.headers)),this.method=P(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function j(a){var p=new FormData;return a.trim().split("&").forEach(function(E){if(E){var C=E.split("="),_=C.shift().replace(/\+/g," "),b=C.join("=").replace(/\+/g," ");p.append(decodeURIComponent(_),decodeURIComponent(b))}}),p}function k(a){var p=new v,E=a.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var _=C.split(":"),b=_.shift().trim();if(b){var ee=_.join(":").trim();p.append(b,ee)}}),p}R.call(I.prototype);function x(a,p){p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in p?p.statusText:"OK",this.headers=new v(p.headers),this.url=p.url||"",this._initBody(a)}R.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},x.error=function(){var a=new x(null,{status:0,statusText:""});return a.type="error",a};var J=[301,302,303,307,308];x.redirect=function(a,p){if(J.indexOf(p)===-1)throw new RangeError("Invalid status code");return new x(null,{status:p,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(p,E){this.message=p,this.name=E;var C=Error(p);this.stack=C.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function K(a,p){return new Promise(function(E,C){var _=new I(a,p);if(_.signal&&_.signal.aborted)return C(new s.DOMException("Aborted","AbortError"));var b=new XMLHttpRequest;function ee(){b.abort()}b.onload=function(){var H={status:b.status,statusText:b.statusText,headers:k(b.getAllResponseHeaders()||"")};H.url="responseURL"in b?b.responseURL:H.headers.get("X-Request-URL");var he="response"in b?b.response:b.responseText;E(new x(he,H))},b.onerror=function(){C(new TypeError("Network request failed"))},b.ontimeout=function(){C(new TypeError("Network request failed"))},b.onabort=function(){C(new s.DOMException("Aborted","AbortError"))},b.open(_.method,_.url,!0),_.credentials==="include"?b.withCredentials=!0:_.credentials==="omit"&&(b.withCredentials=!1),"responseType"in b&&c.blob&&(b.responseType="blob"),_.headers.forEach(function(H,he){b.setRequestHeader(he,H)}),_.signal&&(_.signal.addEventListener("abort",ee),b.onreadystatechange=function(){b.readyState===4&&_.signal.removeEventListener("abort",ee)}),b.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=v,o.Request=I,o.Response=x),s.Headers=v,s.Request=I,s.Response=x,s.fetch=K,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(qt,qt.exports);const Gt=Bi(qt.exports),qe="nhostRefreshToken",Ge="nhostRefreshTokenExpiresAt",$r=3,Br=300,Vt=5,Ht=0,Kt=1,re=10,_e=20;class Ve extends Error{constructor(e){super(e.message),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Kt,message:e.message}):(this.name=e.error,this.error=e)}}const ue={status:re,error:"invalid-email",message:"Email is incorrectly formatted"},Fr={status:re,error:"invalid-mfa-type",message:"MFA type is invalid"},qr={status:re,error:"invalid-mfa-code",message:"MFA code is invalid"},pt={status:re,error:"invalid-password",message:"Password is incorrectly formatted"},zt={status:re,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Gr={status:re,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Vr={status:re,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Hr={status:re,error:"no-refresh-token",message:"No refresh token has been provided"},Kr={status:_e,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},se={status:_e,error:"already-signed-in",message:"User is already signed in"},zr={status:_e,error:"unauthenticated-user",message:"User is not authenticated"},Fi={status:_e,error:"user-not-anonymous",message:"User is not anonymous"},Yr={status:_e,error:"unverified-user",message:"Email needs verification"},Wr={status:re,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},Jr={status:Kt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},vt={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function qi(t){return new TextEncoder().encode(t)}function Ee(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Yt(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),o=new ArrayBuffer(i.length),s=new Uint8Array(o);for(let c=0;c<i.length;c++)s[c]=i.charCodeAt(c);return o}function Qr(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function Xr(t){const{id:e}=t;return{...t,id:Yt(e),transports:t.transports}}function Zr(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class X extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}}function Gi({error:t,options:e}){var r,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new X("Registration ceremony was sent an abort signal","AbortError")}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new X("Discoverable credentials were required but no available authenticator supported it","ConstraintError");if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new X("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new X("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new X("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new X('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new X("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const o=window.location.hostname;if(Zr(o)){if(i.rp.id!==o)return new X(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new X("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class Vi{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const yt=new Vi;async function en(t){if(!Qr())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:Yt(t.challenge),user:{...t.user,id:qi(t.user.id)},excludeCredentials:t.excludeCredentials.map(Xr)}};e.signal=yt.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(d){throw Gi({error:d,options:e})}finally{yt.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:o,type:s}=r,c={id:n,rawId:Ee(i),response:{attestationObject:Ee(o.attestationObject),clientDataJSON:Ee(o.clientDataJSON)},type:s,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof o.getTransports=="function"&&(c.transports=o.getTransports()),c}function Hi(t){return new TextDecoder("utf-8").decode(t)}async function Ki(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function zi({error:t,options:e}){var r;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new X("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new X("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new X("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(Zr(i)){if(n.rpId!==i)return new X(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function Yi(t,e=!1){var r,n;if(!Qr())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)===null||r===void 0?void 0:r.length)!==0&&(i=(n=t.allowCredentials)===null||n===void 0?void 0:n.map(Xr));const o={...t,challenge:Yt(t.challenge),allowCredentials:i},s={};if(e){if(!await Ki())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');s.mediation="conditional",o.allowCredentials=[]}s.publicKey=o,s.signal=yt.createNewAbortSignal();let c;try{c=await navigator.credentials.get(s)}catch(y){throw zi({error:y,options:s})}finally{yt.reset()}if(!c)throw new Error("Authentication was not completed");const{id:d,rawId:f,response:u,type:l}=c;let h;return u.userHandle&&(h=Hi(u.userHandle)),{id:d,rawId:Ee(f),response:{authenticatorData:Ee(u.authenticatorData),clientDataJSON:Ee(u.clientDataJSON),signature:Ee(u.signature),userHandle:h},type:l,clientExtensionResults:c.getClientExtensionResults(),authenticatorAttachment:c.authenticatorAttachment}}const mt=typeof window<"u",gt=new Map,Wi=t=>mt&&typeof localStorage<"u"?localStorage.getItem(t):gt.get(t)??null,Ji=(t,e)=>{mt&&typeof localStorage<"u"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?gt.set(t,e):gt.has(t)&&gt.delete(t)},tn=(t,e)=>{if(t==="localStorage"||t==="web")return Wi;if(t==="cookie")return r=>mt?Ft.get(r)??null:null;if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},rn=(t,e)=>{if(t==="localStorage"||t==="web")return Ji;if(t==="cookie")return(r,n)=>{mt&&(n?Ft.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Ft.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,o;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(o=e.remove)==null?void 0:o.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.deleteItemAsync)==null?void 0:o.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},He=t=>!t||!t.accessToken.value||!t.refreshToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},ye=({accessToken:t,isError:e,user:r,error:n})=>e?{session:null,error:n}:r&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:"",user:r},error:null}:{session:null,error:null},wt=()=>typeof window<"u",nn=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const o={method:e,headers:i};n&&(o.body=JSON.stringify(n));try{const s=await Gt(t,o);if(!s.ok){const c=await s.json();return Promise.reject({error:c})}try{return{data:await s.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const s={message:"Network Error",status:Ht,error:"network"};return Promise.reject({error:s})}},le=async(t,e,r)=>nn(t,"POST",{token:r,body:e}),on=(t,e)=>nn(t,"GET",{token:e}),Wt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const o=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(o)}`}).join("&");return r?`${t}?${r}`:t},ne=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),o=Object.fromEntries(new URLSearchParams(i.search)),s=new URL(r.startsWith("/")?i.origin+r:r),c=new URLSearchParams(s.search);let d=Object.fromEntries(c);r.startsWith("/")&&(d={...o,...d});let f=i.pathname;return s.pathname.length>1&&(f+=s.pathname.slice(1)),{...n,redirectTo:Wt(s.origin+f,d)}};function Ke(t,e){var r;if(!e){if(typeof window>"u")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function Jt(t){var e;if(typeof window>"u")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let o=window.location.pathname;Array.from(n).length&&(o+=`?${n.toString()}`),Array.from(i).length&&(o+=`#${i.toString()}`),window.history.pushState({},"",o)}}const de=t=>!!t&&typeof t=="string"&&!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),Et=t=>!!t&&typeof t=="string"&&t.length>=$r,Qt=t=>!!t&&typeof t=="string",sn=t=>t&&typeof t=="string"&&t.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),an=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:o=!0,autoSignIn:s=!0})=>{const c=tn(r,n),d=rn(r,n),f=async(u,l,h)=>(await le(`${t}${u}`,l,h)).data;return ve({schema:{context:{},events:{},services:{}},tsTypes:{},context:vt,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:W("SIGNED_IN"),reportSignedOut:W("SIGNED_OUT"),reportTokenChanged:W("TOKEN_CHANGED"),incrementTokenImportAttempts:U({importTokenAttempts:({importTokenAttempts:u})=>u+1}),clearContext:U(()=>(d(Ge,null),d(qe,null),{...vt})),clearContextExceptRefreshToken:U(({refreshToken:{value:u}})=>(d(Ge,null),{...vt,refreshToken:{value:u}})),saveSession:U({user:(u,{data:l})=>{var h;return((h=l==null?void 0:l.session)==null?void 0:h.user)||null},accessToken:(u,{data:l})=>{if(l.session){const{accessTokenExpiresIn:h,accessToken:y}=l.session,v=new Date(Date.now()+h*1e3);return d(Ge,v.toISOString()),{value:y,expiresAt:v}}return d(Ge,null),{value:null,expiresAt:null}},refreshToken:(u,{data:l})=>{var h;const y=((h=l.session)==null?void 0:h.refreshToken)||null;return y&&d(qe,y),{value:y}}}),saveMfaTicket:U({mfa:(u,l)=>{var h;return(h=l.data)==null?void 0:h.mfa}}),resetTimer:U({refreshTimer:u=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:U({refreshTimer:(u,l)=>({startedAt:u.refreshTimer.startedAt,attempts:u.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:U({errors:({errors:u},{data:{error:l}})=>({...u,authentication:l})}),resetErrors:U({errors:u=>({}),importTokenAttempts:u=>0}),saveRegistrationError:U({errors:({errors:u},{data:{error:l}})=>({...u,registration:l})}),destroyRefreshToken:U({refreshToken:u=>(d(qe,null),{value:null})}),cleanUrl:()=>{s&&Ke("refreshToken")&&(Jt("refreshToken"),Jt("type"))},broadcastToken:u=>{if(s)try{new BroadcastChannel("nhost").postMessage(u.refreshToken.value)}catch{}}},guards:{isAnonymous:(u,l)=>{var h;return!!((h=u.user)!=null&&h.isAnonymous)},isSignedIn:u=>!!u.user&&!!u.refreshToken.value&&!!u.accessToken.value,noToken:u=>!u.refreshToken.value,hasRefreshToken:u=>!!u.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:u=>{const{expiresAt:l}=u.accessToken;return l?u.refreshTimer.lastAttempt?u.refreshTimer.attempts>Vt?!1:Date.now()-u.refreshTimer.lastAttempt.getTime()>Math.pow(2,u.refreshTimer.attempts-1)*5e3:i&&Date.now()-u.refreshTimer.startedAt.getTime()>i*1e3?!0:l.getTime()-Date.now()-1e3*Br<=0:!1},shouldRetryImportToken:(u,l)=>u.importTokenAttempts<Vt&&(l.data.error.status===Ht||l.data.error.status>=500),unverified:(u,{data:{error:l}})=>l.status===401&&(l.message==="Email is not verified"||l.error==="unverified-user"),hasSession:(u,l)=>{var h;return!!((h=l.data)!=null&&h.session)},hasMfaTicket:(u,l)=>{var h;return!!((h=l.data)!=null&&h.mfa)}},services:{signInPassword:(u,{email:l,password:h})=>de(l)?Et(h)?f("/signin/email-password",{email:l,password:h}):Promise.reject({error:pt}):Promise.reject({error:ue}),passwordlessSms:(u,{phoneNumber:l,options:h})=>{var y;return Qt(l)?(y=u.user)!=null&&y.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),f("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:l,options:ne(e,h)},u.accessToken.value)):f("/signin/passwordless/sms",{phoneNumber:l,options:ne(e,h)}):Promise.reject({error:zt})},passwordlessSmsOtp:(u,{phoneNumber:l,otp:h})=>Qt(l)?f("/signin/passwordless/sms/otp",{phoneNumber:l,otp:h}):Promise.reject({error:zt}),passwordlessEmail:(u,{email:l,options:h})=>{var y;return de(l)?(y=u.user)!=null&&y.isAnonymous?f("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:l,options:ne(e,h)},u.accessToken.value):f("/signin/passwordless/email",{email:l,options:ne(e,h)}):Promise.reject({error:ue})},signInAnonymous:u=>f("/signin/anonymous"),signInMfaTotp:(u,l)=>{var h;const y=l.ticket||((h=u.mfa)==null?void 0:h.ticket);return y?sn(y)?f("/signin/mfa/totp",{ticket:y,otp:l.otp}):Promise.reject({error:Gr}):Promise.reject({error:Vr})},signInSecurityKeyEmail:async(u,{email:l})=>{if(!de(l))throw new Ve(ue);const h=await f("/signin/webauthn",{email:l});let y;try{y=await Yi(h)}catch(v){throw new Ve(v)}return f("/signin/webauthn/verify",{email:l,credential:y})},refreshToken:async(u,l)=>{const h=l.type==="TRY_TOKEN"?l.token:u.refreshToken.value;return{session:await f("/token",{refreshToken:h}),error:null}},signout:(u,l)=>f("/signout",{refreshToken:u.refreshToken.value,all:!!l.all}),signUpEmailPassword:async(u,{email:l,password:h,options:y})=>{var v;return de(l)?Et(h)?(v=u.user)!=null&&v.isAnonymous?f("/user/deanonymize",{signInMethod:"email-password",email:l,password:h,options:ne(e,y)},u.accessToken.value):f("/signup/email-password",{email:l,password:h,options:ne(e,y)}):Promise.reject({error:pt}):Promise.reject({error:ue})},signUpSecurityKey:async(u,{email:l,options:h})=>{if(!de(l))return Promise.reject({error:ue});const y=h==null?void 0:h.nickname;y&&delete h.nickname;const v=await f("/signup/webauthn",{email:l,options:h});let w;try{w=await en(v)}catch(T){throw new Ve(T)}return f("/signup/webauthn/verify",{credential:w,options:{redirectTo:h==null?void 0:h.redirectTo,nickname:y}})},importRefreshToken:async u=>{if(u.user&&u.refreshToken.value&&u.accessToken.value&&u.accessToken.expiresAt)return{session:{accessToken:u.accessToken.value,accessTokenExpiresIn:u.accessToken.expiresAt.getTime()-Date.now(),refreshToken:u.refreshToken.value,user:u.user},error:null};let l=null;if(s){const y=Ke("refreshToken")||null;if(y)try{return{session:await f("/token",{refreshToken:y}),error:null}}catch(v){l=v.error}else{const v=Ke("error");if(v)return Promise.reject({session:null,error:{status:re,error:v,message:Ke("errorDescription")||v}})}}const h=await c(qe);if(h)try{return{session:await f("/token",{refreshToken:h}),error:null}}catch(y){l=y.error}return l?Promise.reject({error:l,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:u})=>Math.pow(2,u-1)*5e3}})},cn=({backendUrl:t,clientUrl:e,interpreter:r})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changeEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:n=>ue}),saveRequestError:U({error:(n,{data:{error:i}})=>i}),reportError:W(n=>({type:"ERROR",error:n.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!de(i)},services:{requestChange:async(n,{email:i,options:o})=>(await le(`${t}/user/email/change`,{newEmail:i,options:ne(e,o)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),un=({backendUrl:t,interpreter:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidPassword",actions:"saveInvalidPasswordError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidPasswordError:U({error:r=>pt}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!Et(n)},services:{requestChange:(r,{password:n,ticket:i})=>le(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Qi=({backendUrl:t,interpreter:e})=>ve({schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,id:"enableMfa",initial:"idle",context:{error:null,imageUrl:null,secret:null},states:{idle:{initial:"initial",on:{GENERATE:"generating"},states:{initial:{},error:{}}},generating:{invoke:{src:"generate",id:"generate",onDone:{target:"generated",actions:["reportGeneratedSuccess","saveGeneration"]},onError:{actions:["saveError","reportGeneratedError"],target:"idle.error"}}},generated:{initial:"idle",states:{idle:{initial:"idle",on:{ACTIVATE:[{cond:"invalidMfaType",actions:"saveInvalidMfaTypeError",target:".error"},{cond:"invalidMfaCode",actions:"saveInvalidMfaCodeError",target:".error"},{target:"activating"}]},states:{idle:{},error:{}}},activating:{invoke:{src:"activate",id:"activate",onDone:{target:"activated",actions:"reportSuccess"},onError:{actions:["saveError","reportError"],target:"idle.error"}}},activated:{type:"final"}}}}},{actions:{saveInvalidMfaTypeError:U({error:r=>Fr}),saveInvalidMfaCodeError:U({error:r=>qr}),saveError:U({error:(r,{data:{error:n}})=>n}),saveGeneration:U({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:W((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS"),reportGeneratedSuccess:W("GENERATED"),reportGeneratedError:W(r=>({type:"GENERATED_ERROR",error:r.error}))},guards:{invalidMfaCode:(r,{code:n})=>!n,invalidMfaType:(r,{activeMfaType:n})=>!n||n!=="totp"},services:{generate:async r=>{const{data:n}=await on(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>le(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ln=({backendUrl:t,clientUrl:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:r=>ue}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{requestChange:(r,{email:n,options:i})=>le(`${t}/user/password/reset`,{email:n,options:ne(e,i)})}}),dn=({backendUrl:t,clientUrl:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"sendVerificationEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"request",id:"request",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:r=>ue}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{request:async(r,{email:n,options:i})=>(await le(`${t}/user/email/send-verification-email`,{email:n,options:ne(e,i)})).data}});let Xt=class{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:o,clientUrl:s,devTools:c,...d}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=o,this.clientUrl=s,this._machine=an({...d,backendUrl:o,clientUrl:s,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:c}),typeof window<"u"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",f=>{var u;const l=(u=this.interpreter)==null?void 0:u.getSnapshot().context.refreshToken.value;this.interpreter&&f.data!==l&&this.interpreter.send("TRY_TOKEN",{token:f.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){const i={...this.machine.context};r&&(i.user=r.user,i.refreshToken.value=r.refreshToken??null,i.accessToken.value=r.accessToken??null,i.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const o=this.machine.withContext(i);this._interpreter||(this._interpreter=n||xe(o,{devTools:e})),(!this._started||typeof window>"u")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(s=>s())),this._interpreter.start(o.initialState),this._subscriptionsQueue.forEach(s=>s(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}};class hn extends Xt{constructor({...e}){super({...e,autoSignIn:wt()&&e.autoSignIn,autoRefreshToken:wt()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const Xi=hn,fn=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await le("/user/webauthn/add",{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await en(n)}catch(s){throw new Ve(s)}const{data:o}=await le(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:o,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},pn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),vn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),Zi=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),eo=(t,e)=>new Promise(r=>{t.send("ACTIVATE",{activeMfaType:"totp",code:e}),t.onTransition(n=>{n.matches({generated:"activated"})?r({error:null,isActivated:!0,isError:!1}):n.matches({generated:{idle:"error"}})&&r({error:n.context.error,isActivated:!1,isError:!0})})}),yn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),mn=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),gn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:se,user:null,accessToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null})})}),wn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:s.context.mfa,user:null}):s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.context.user})})}),Zt=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({error:o.context.errors.registration||null,isError:!0,isSuccess:!1}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),En=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:"signedIn"})&&r({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),Sn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:s.context.user})})}),er=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(o=>{o.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):o.matches("registration.incomplete.failed")&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Tn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(o=>{o.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:o.context.user,accessToken:o.context.accessToken.value}):o.matches({registration:{incomplete:"failed"}})&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),bn=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:zr});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),tr=(t,e,r,n)=>new Promise(i=>{const{changed:o,context:s}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!o)return i({error:se,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(c=>{c.matches("registration.incomplete.failed")?i({accessToken:null,error:c.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):c.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):c.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:c.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:c.context.user})})}),An=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:se,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({accessToken:null,error:s.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})});class On{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:o,refreshIntervalTime:s,start:c=!0}){var d;this.url=e,this._client=new Xt({backendUrl:e,clientUrl:typeof window<"u"&&((d=window.location)==null?void 0:d.origin)||"",autoRefreshToken:r,autoSignIn:n,start:c,clientStorage:i,clientStorageType:o,refreshIntervalTime:s})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?ye(await An(r,n,i)):ye(await tr(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await gn(r);return{...ye(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,o=Wt(`${this._client.backendUrl}/signin/provider/${n}`,ne(this._client.clientUrl,i));return wt()&&(window.location.href=o),{providerUrl:o,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await wn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:Yr}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ye(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await En(r,e.email);return{...ye(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:o}=await Zt(r,n,i);return{session:null,mfa:null,error:o}}if("phoneNumber"in e&&"otp"in e){const n=await Tn(r,e.phoneNumber,e.otp);return{...ye(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await er(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Sn(r,e.otp,e.ticket);return{...ye(n),mfa:null}}return{error:Jr,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await bn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=xe(ln(this._client)).start(),{error:i}=await yn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=xe(un(this._client)).start(),{error:i}=await vn(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=xe(dn(this._client)).start(),{error:i}=await mn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=xe(cn(this._client)).start(),{error:i}=await pn(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await Zt(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await er(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await tr(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await fn(this._client,e);return{error:r,key:n}}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:o})=>{i.type==="TOKEN_CHANGED"&&e(He(o))});return()=>n==null?void 0:n.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:o})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,He(o))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e;return((e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)??void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Bn(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const i=e||r.getSnapshot().context.refreshToken.value;if(!i)return n({session:null,error:Hr});const{changed:o}=r.send("TRY_TOKEN",{token:i});if(!o)return n({session:null,error:Kr});r.onTransition(s=>{s.matches({token:{idle:"error"}})?n({session:null,error:Wr}):s.event.type==="TOKEN_CHANGED"&&n({session:He(s.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return He((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n(`The state machine is not yet ready after ${15} seconds.`),15e3);e.onTransition(o=>{if(!o.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var kn=typeof self=="object"?self.FormData:window.FormData,to=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ro(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var rr={exports:{}};(function(t,e){var r=typeof self<"u"?self:to,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var c={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function d(a){return a&&DataView.prototype.isPrototypeOf(a)}if(c.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(a){return a&&f.indexOf(Object.prototype.toString.call(a))>-1};function l(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function h(a){return typeof a!="string"&&(a=String(a)),a}function y(a){var p={next:function(){var E=a.shift();return{done:E===void 0,value:E}}};return c.iterable&&(p[Symbol.iterator]=function(){return p}),p}function v(a){this.map={},a instanceof v?a.forEach(function(p,E){this.append(E,p)},this):Array.isArray(a)?a.forEach(function(p){this.append(p[0],p[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(p){this.append(p,a[p])},this)}v.prototype.append=function(a,p){a=l(a),p=h(p);var E=this.map[a];this.map[a]=E?E+", "+p:p},v.prototype.delete=function(a){delete this.map[l(a)]},v.prototype.get=function(a){return a=l(a),this.has(a)?this.map[a]:null},v.prototype.has=function(a){return this.map.hasOwnProperty(l(a))},v.prototype.set=function(a,p){this.map[l(a)]=h(p)},v.prototype.forEach=function(a,p){for(var E in this.map)this.map.hasOwnProperty(E)&&a.call(p,this.map[E],E,this)},v.prototype.keys=function(){var a=[];return this.forEach(function(p,E){a.push(E)}),y(a)},v.prototype.values=function(){var a=[];return this.forEach(function(p){a.push(p)}),y(a)},v.prototype.entries=function(){var a=[];return this.forEach(function(p,E){a.push([E,p])}),y(a)},c.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function w(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function T(a){return new Promise(function(p,E){a.onload=function(){p(a.result)},a.onerror=function(){E(a.error)}})}function O(a){var p=new FileReader,E=T(p);return p.readAsArrayBuffer(a),E}function S(a){var p=new FileReader,E=T(p);return p.readAsText(a),E}function A(a){for(var p=new Uint8Array(a),E=new Array(p.length),C=0;C<p.length;C++)E[C]=String.fromCharCode(p[C]);return E.join("")}function N(a){if(a.slice)return a.slice(0);var p=new Uint8Array(a.byteLength);return p.set(new Uint8Array(a)),p.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:c.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:c.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():c.arrayBuffer&&c.blob&&d(a)?(this._bodyArrayBuffer=N(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||u(a))?this._bodyArrayBuffer=N(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?w(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(O)}),this.text=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return S(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var q=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function P(a){var p=a.toUpperCase();return q.indexOf(p)>-1?p:a}function I(a,p){p=p||{};var E=p.body;if(a instanceof I){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,p.headers||(this.headers=new v(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!E&&a._bodyInit!=null&&(E=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new v(p.headers)),this.method=P(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function j(a){var p=new FormData;return a.trim().split("&").forEach(function(E){if(E){var C=E.split("="),_=C.shift().replace(/\+/g," "),b=C.join("=").replace(/\+/g," ");p.append(decodeURIComponent(_),decodeURIComponent(b))}}),p}function k(a){var p=new v,E=a.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var _=C.split(":"),b=_.shift().trim();if(b){var ee=_.join(":").trim();p.append(b,ee)}}),p}R.call(I.prototype);function x(a,p){p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in p?p.statusText:"OK",this.headers=new v(p.headers),this.url=p.url||"",this._initBody(a)}R.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},x.error=function(){var a=new x(null,{status:0,statusText:""});return a.type="error",a};var J=[301,302,303,307,308];x.redirect=function(a,p){if(J.indexOf(p)===-1)throw new RangeError("Invalid status code");return new x(null,{status:p,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(a,p){this.message=a,this.name=p;var E=Error(a);this.stack=E.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function K(a,p){return new Promise(function(E,C){var _=new I(a,p);if(_.signal&&_.signal.aborted)return C(new s.DOMException("Aborted","AbortError"));var b=new XMLHttpRequest;function ee(){b.abort()}b.onload=function(){var H={status:b.status,statusText:b.statusText,headers:k(b.getAllResponseHeaders()||"")};H.url="responseURL"in b?b.responseURL:H.headers.get("X-Request-URL");var he="response"in b?b.response:b.responseText;E(new x(he,H))},b.onerror=function(){C(new TypeError("Network request failed"))},b.ontimeout=function(){C(new TypeError("Network request failed"))},b.onabort=function(){C(new s.DOMException("Aborted","AbortError"))},b.open(_.method,_.url,!0),_.credentials==="include"?b.withCredentials=!0:_.credentials==="omit"&&(b.withCredentials=!1),"responseType"in b&&c.blob&&(b.responseType="blob"),_.headers.forEach(function(H,he){b.setRequestHeader(he,H)}),_.signal&&(_.signal.addEventListener("abort",ee),b.onreadystatechange=function(){b.readyState===4&&_.signal.removeEventListener("abort",ee)}),b.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=v,o.Request=I,o.Response=x),s.Headers=v,s.Request=I,s.Response=x,s.fetch=K,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(rr,rr.exports);const nr=ro(rr.exports),no=t=>{try{return btoa(t),t}catch{return encodeURIComponent(t)}},xn=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:o,adminSecret:s,onUploadProgress:c}={})=>{const d={};i&&(d["x-nhost-file-id"]=i),o&&(d["x-nhost-bucket-id"]=o),n&&(d["x-nhost-file-name"]=no(n)),s&&(d["x-hasura-admin-secret"]=s),r&&(d.Authorization=`Bearer ${r}`);const f=`${t}/files`;if(typeof XMLHttpRequest>"u")try{const u=await nr(f,{method:"POST",headers:d,body:e});return u.ok?{fileMetadata:await u.json(),error:null}:{error:{status:u.status,message:await u.text(),error:u.statusText},fileMetadata:null}}catch(u){return{error:{status:0,message:u.message,error:u.message},fileMetadata:null}}return new Promise(u=>{let l=new XMLHttpRequest;l.responseType="json",l.onload=()=>l.status<200&&l.status>=300?u({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}):u({fileMetadata:l.response,error:null}),l.onerror=()=>u({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}),c&&l.upload.addEventListener("progress",c,!1),l.open("POST",f,!0),Object.entries(d).forEach(([h,y])=>{l.setRequestHeader(h,y)}),l.send(e)})};class In{constructor({url:e}){this.url=e}async upload(e){const{formData:r}=e;return xn(this.url,r,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:e.bucketId,fileId:e.id,name:e.name})}async getPresignedUrl(e){try{const{fileId:r}=e,n=await nr(`${this.url}/files/${r}/presignedurl`,{method:"GET",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{presignedUrl:await n.json(),error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e,n=await nr(`${this.url}/files/${r}`,{method:"DELETE",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateAuthHeaders(){if(!(!this.adminSecret&&!this.accessToken))return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}const Rn=(t,e)=>{const r=Object.entries(e).map(([n,i])=>`${Array.from(n)[0]}=${i}`).join("&");return r?`${t}?${r}`:t};class Pn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new In({url:e}),this.setAdminSecret(r)}async upload(e){let r;return"file"in e?(r=new kn,r.append("file",e.file)):r=e.formData,this.api.upload({...e,formData:r})}getPublicUrl(e){const{fileId:r,...n}=e;return Rn(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{presignedUrl:r,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}const St={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},_n=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...St},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(t,e)=>!!t.file||!!e.file},actions:{incrementProgress:U({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:U({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:U({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:U({progress:t=>null,loaded:t=>0}),resetContext:U(t=>St),addFile:U({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new kn;i.append("file",n);let o=0;return xn(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:s=>{const c=s.total?Math.round(s.loaded*n.size/s.total):0,d=c-o;o=c,r({type:"UPLOAD_PROGRESS",progress:s.total?Math.round(c*100/s.total):0,loaded:c,additions:d})}}).then(({fileMetadata:s,error:c})=>{if(c&&r({type:"UPLOAD_ERROR",error:c}),s){const{id:d,bucketId:f}=s;r({type:"UPLOAD_DONE",id:d,bucketId:f})}}),()=>{}}}}),{pure:ir,sendParent:Tt}=vi,io=()=>ve({id:"files-list",schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,context:{progress:null,files:[],loaded:0,total:0},initial:"idle",on:{UPLOAD:{cond:"hasFileToDownload",actions:"addItem",target:"uploading"},ADD:{actions:"addItem"},REMOVE:{actions:"removeItem"}},states:{idle:{entry:["resetProgress","resetLoaded","resetTotal"],on:{CLEAR:{actions:"clearList",target:"idle"}}},uploading:{entry:["upload","startProgress","resetLoaded","resetTotal"],on:{UPLOAD_PROGRESS:{actions:["incrementProgress"]},UPLOAD_DONE:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],UPLOAD_ERROR:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],CANCEL:{actions:"cancel",target:"idle"}}},uploaded:{entry:"setUploaded",on:{CLEAR:{actions:"clearList",target:"idle"}}},error:{on:{CLEAR:{actions:"clearList",target:"idle"}}}}},{guards:{hasFileToDownload:(t,e)=>t.files.some(r=>r.getSnapshot().matches("idle"))||!!e.files,isAllUploaded:t=>t.files.every(e=>{var r;return(r=e.getSnapshot())==null?void 0:r.matches("uploaded")}),isAllUploadedOrError:t=>t.files.every(e=>{const r=e.getSnapshot();return(r==null?void 0:r.matches("error"))||(r==null?void 0:r.matches("uploaded"))})},actions:{incrementProgress:U((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:U({progress:t=>100,loaded:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetTotal:U({total:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>!e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetLoaded:U({loaded:t=>0}),startProgress:U({progress:t=>0}),resetProgress:U({progress:t=>null}),addItem:U((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"length"in e?Array.from(e):[e]:[],i=t.total+n.reduce((s,c)=>s+c.size,0),o=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(s=>Di(_n().withConfig({actions:{sendProgress:Tt((c,{additions:d})=>({type:"UPLOAD_PROGRESS",additions:d})),sendDone:Tt("UPLOAD_DONE"),sendError:Tt("UPLOAD_ERROR"),sendDestroy:Tt("REMOVE")}}).withContext({...St,file:s,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:o}}),removeItem:U({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:ir(t=>t.files.map(e=>W({type:"DESTROY"},{to:e.id}))),upload:ir((t,e)=>t.files.map(r=>W(e,{to:r.id}))),cancel:ir(t=>t.files.map(e=>W({type:"CANCEL"},{to:e.id})))}}),oo=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),so=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var o;return(o=i.getSnapshot())==null?void 0:o.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),ao=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function bt(t,e){const{backendUrl:r,subdomain:n,region:i}=t;if(r)return`${r}/v1/${e}`;if(!n)throw new Error("Either `backendUrl` or `subdomain` must be set.");const o=n.match(ao);if(o!=null&&o.groups){const{protocol:s="http",host:c,port:d=1337}=o.groups,f=lo(e);return f||`${s}://${c}:${d}/v1/${e}`}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${n}.${e}.${i}.nhost.run/v1`}function co(){return typeof window<"u"}function uo(){return typeof process<"u"&&process.env}function lo(t){return co()||!uo()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function Un(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new On({url:e,...t})}function Dn(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Nn({url:e,...t})}class Nn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers},o=this.url,s=e.startsWith("/")?e:`/${e}`;try{const c=await Gt(`${o}/${s}`,{body:JSON.stringify(r),headers:i,method:"POST"});if(!c.ok)throw new Error(c.statusText);let d;return c.headers.get("content-type")==="application/json"?d=await c.json():d=await c.text(),{res:{data:d,status:c.status,statusText:c.statusText},error:null}}catch(c){const d=c;return{res:null,error:{message:d.message,status:d.name==="AbortError"?0:500,error:d.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function ho(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function Cn(t){var e;let r;const n=t.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(r=(e=n[0].name)==null?void 0:e.value),r}function fo(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=Cn(n)}catch{}return{query:t,operationName:r}}const e=Cn(t);return{query:Se.print(t),operationName:e}}class po{constructor(e){const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...r){const[n,i]=r,o=ho(e,n,i),{headers:s,...c}=i||{},{query:d,operationName:f}=fo(o.document);try{const u=await Gt(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:f,query:d,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...s},...c});if(!u.ok)return{data:null,error:{error:u.statusText,message:u.statusText,status:u.status}};const{data:l,errors:h}=await u.json();return h?{data:null,error:h}:typeof l!="object"||Array.isArray(l)||l===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:l,error:null}}catch(u){const l=u;return{data:null,error:{message:l.message,status:l.name==="AbortError"?0:500,error:l.name==="AbortError"?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function Mn(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new po({url:e,...t})}function Ln(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Pn({url:e,...t})}const vo=t=>new jn(t);class jn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,adminSecret:s,devTools:c,start:d=!0,...f}){this.auth=Un({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,start:d,...f}),this.storage=Ln({adminSecret:s,...f}),this.functions=Dn({adminSecret:s,...f}),this.graphql=Mn({adminSecret:s,...f}),this.auth.onAuthStateChanged((u,l)=>{u==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(u=>{const l=u==null?void 0:u.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=s,this.devTools=c}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}g.AuthClient=Xt,g.AuthClientSSR=Xi,g.AuthCookieClient=hn,g.CodifiedError=Ve,g.EMAIL_NEEDS_VERIFICATION=Yr,g.HasuraAuthClient=On,g.HasuraStorageApi=In,g.HasuraStorageClient=Pn,g.INITIAL_FILE_CONTEXT=St,g.INITIAL_MACHINE_CONTEXT=vt,g.INVALID_EMAIL_ERROR=ue,g.INVALID_MFA_CODE_ERROR=qr,g.INVALID_MFA_TICKET_ERROR=Gr,g.INVALID_MFA_TYPE_ERROR=Fr,g.INVALID_PASSWORD_ERROR=pt,g.INVALID_PHONE_NUMBER_ERROR=zt,g.INVALID_REFRESH_TOKEN=Wr,g.INVALID_SIGN_IN_METHOD=Jr,g.MIN_PASSWORD_LENGTH=$r,g.NETWORK_ERROR_CODE=Ht,g.NHOST_JWT_EXPIRES_AT_KEY=Ge,g.NHOST_REFRESH_TOKEN_KEY=qe,g.NO_MFA_TICKET_ERROR=Vr,g.NO_REFRESH_TOKEN=Hr,g.NhostClient=jn,g.NhostFunctionsClient=Nn,g.OTHER_ERROR_CODE=Kt,g.REFRESH_TOKEN_MAX_ATTEMPTS=Vt,g.STATE_ERROR_CODE=_e,g.TOKEN_REFRESHER_RUNNING_ERROR=Kr,g.TOKEN_REFRESH_MARGIN=Br,g.USER_ALREADY_SIGNED_IN=se,g.USER_NOT_ANONYMOUS=Fi,g.USER_UNAUTHENTICATED=zr,g.VALIDATION_ERROR_CODE=re,g.activateMfaPromise=eo,g.addSecurityKeyPromise=fn,g.appendImageTransformationParameters=Rn,g.changeEmailPromise=pn,g.changePasswordPromise=vn,g.createAuthClient=Un,g.createAuthMachine=an,g.createChangeEmailMachine=cn,g.createChangePasswordMachine=un,g.createEnableMfaMachine=Qi,g.createFileUploadMachine=_n,g.createFunctionsClient=Dn,g.createGraphqlClient=Mn,g.createMultipleFilesUploadMachine=io,g.createNhostClient=vo,g.createResetPasswordMachine=ln,g.createSendVerificationEmailMachine=dn,g.createStorageClient=Ln,g.encodeQueryParameters=Wt,g.generateQrCodePromise=Zi,g.getAuthenticationResult=ye,g.getFetch=on,g.getParameterByName=Ke,g.getSession=He,g.isBrowser=wt,g.isValidEmail=de,g.isValidPassword=Et,g.isValidPhoneNumber=Qt,g.isValidTicket=sn,g.localStorageGetter=tn,g.localStorageSetter=rn,g.postFetch=le,g.removeParameterFromWindow=Jt,g.resetPasswordPromise=yn,g.rewriteRedirectTo=ne,g.sendVerificationEmailPromise=mn,g.signInAnonymousPromise=gn,g.signInEmailPasswordPromise=wn,g.signInEmailPasswordlessPromise=Zt,g.signInEmailSecurityKeyPromise=En,g.signInMfaTotpPromise=Sn,g.signInSmsPasswordlessOtpPromise=Tn,g.signInSmsPasswordlessPromise=er,g.signOutPromise=bn,g.signUpEmailPasswordPromise=tr,g.signUpEmailSecurityKeyPromise=An,g.uploadFilePromise=oo,g.uploadMultipleFilesPromise=so,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
20
20
  //# sourceMappingURL=nhost-js.umd.js.map