@nhost/nhost-js 1.5.2 → 1.6.1

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.
@@ -1,4 +1,4 @@
1
- (function(Q,Ce){typeof exports=="object"&&typeof module!="undefined"?Ce(exports,require("graphql")):typeof define=="function"&&define.amd?define(["exports","graphql"],Ce):(Q=typeof globalThis!="undefined"?globalThis:Q||self,Ce(Q["@nhost/nhost-js"]={},Q.graphql))})(this,function(Q,Ce){"use strict";function Ot(t){this.message=t}Ot.prototype=new Error,Ot.prototype.name="InvalidCharacterError";var fr=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new Ot("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,i=0,s=0,o="";n=e.charAt(s++);~n&&(r=i%4?64*r+n:n,i++%4)?o+=String.fromCharCode(255&r>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return o};function In(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(r){return decodeURIComponent(fr(r).replace(/(.)/g,function(n,i){var s=i.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch{return fr(e)}}function Ke(t){this.message=t}function kn(t,e){if(typeof t!="string")throw new Ke("Invalid token specified");var r=(e=e||{}).header===!0?0:1;try{return JSON.parse(In(t.split(".")[r]))}catch(n){throw new Ke("Invalid token specified: "+n.message)}}Ke.prototype=new Error,Ke.prototype.name="InvalidTokenError";/*! *****************************************************************************
1
+ (function(F,W){typeof exports=="object"&&typeof module<"u"?W(exports,require("graphql")):typeof define=="function"&&define.amd?define(["exports","graphql"],W):(F=typeof globalThis<"u"?globalThis:F||self,W(F["@nhost/nhost-js"]={},F.graphql))})(this,function(F,W){"use strict";var Do=Object.defineProperty;var _o=(F,W,ne)=>W in F?Do(F,W,{enumerable:!0,configurable:!0,writable:!0,value:ne}):F[W]=ne;var J=(F,W,ne)=>(_o(F,typeof W!="symbol"?W+"":W,ne),ne);function ne(t){this.message=t}ne.prototype=new Error,ne.prototype.name="InvalidCharacterError";var ar=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new ne("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,i=0,s=0,o="";n=e.charAt(s++);~n&&(r=i%4?64*r+n:n,i++%4)?o+=String.fromCharCode(255&r>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return o};function Un(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(r){return decodeURIComponent(ar(r).replace(/(.)/g,function(n,i){var s=i.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch{return ar(e)}}function Qe(t){this.message=t}function Dn(t,e){if(typeof t!="string")throw new Qe("Invalid token specified");var r=(e=e||{}).header===!0?0:1;try{return JSON.parse(Un(t.split(".")[r]))}catch(n){throw new Qe("Invalid token specified: "+n.message)}}Qe.prototype=new Error,Qe.prototype.name="InvalidTokenError";/*! *****************************************************************************
2
2
  Copyright (c) Microsoft Corporation.
3
3
 
4
4
  Permission to use, copy, modify, and/or distribute this software for any
@@ -11,10 +11,11 @@
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 y=function(){return y=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},y.apply(this,arguments)};function Rt(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 b(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 A(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function P(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}var k;(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"})(k||(k={}));var ne;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(ne||(ne={}));var _t=k.Start,It=k.Stop,he=k.Raise,pe=k.Send,dr=k.Cancel,Nn=k.NullEvent,kt=k.Assign;k.After,k.DoneState;var hr=k.Log,Pn=k.Init,Nt=k.Invoke;k.ErrorExecution;var pr=k.ErrorPlatform,Cn=k.ErrorCustom,vr=k.Update,Dn=k.Choose,Un=k.Pure,mr=".",yr={},Pt="xstate.guard",Ln="",De=!0,He;function Ct(t,e,r){r===void 0&&(r=mr);var n=Ue(t,r),i=Ue(e,r);return _(i)?_(n)?i===n:!1:_(n)?n in i:Object.keys(n).every(function(s){return s in i?Ct(n[s],i[s]):!1})}function gr(t){try{return _(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 Dt(t,e){try{return ve(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function $n(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function Ue(t,e){if($n(t))return t.value;if(ve(t))return ze(t);if(typeof t!="string")return t;var r=Dt(t,e);return ze(r)}function ze(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 Le(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var s=n[i];r[s]=e(t[s],s,t,i)}return r}function Er(t,e,r){var n,i,s={};try{for(var o=b(Object.keys(t)),a=o.next();!a.done;a=o.next()){var u=a.value,f=t[u];!r(f)||(s[u]=e(f,u,t))}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}var jn=function(t){return function(e){var r,n,i=e;try{for(var s=b(t),o=s.next();!o.done;o=s.next()){var a=o.value;i=i[a]}}catch(u){r={error:u}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}};function Mn(t,e){return function(r){var n,i,s=r;try{for(var o=b(t),a=o.next();!a.done;a=o.next()){var u=a.value;s=s[e][u]}}catch(f){n={error:f}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}}function We(t){if(!t)return[[]];if(_(t))return[[t]];var e=U(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:We(t[r]).map(function(i){return[r].concat(i)})}));return e}function U(t){var e;return(e=[]).concat.apply(e,P([],A(t),!1))}function wr(t){return ve(t)?t:[t]}function z(t){return t===void 0?[]:wr(t)}function Ge(t,e,r){var n,i;if(N(t))return t(e,r.data);var s={};try{for(var o=b(Object.keys(t)),a=o.next();!a.done;a=o.next()){var u=a.value,f=t[u];N(f)?s[u]=f(e,r.data):s[u]=f}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}function qn(t){return/^(done|error)\./.test(t)}function Sr(t){return!!(t instanceof Promise||t!==null&&(N(t)||typeof t=="object")&&N(t.then))}function Bn(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function Fn(t,e){var r,n,i=A([[],[]],2),s=i[0],o=i[1];try{for(var a=b(t),u=a.next();!u.done;u=a.next()){var f=u.value;e(f)?s.push(f):o.push(f)}}catch(c){r={error:c}}finally{try{u&&!u.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return[s,o]}function Tr(t,e){return Le(t.states,function(r,n){if(!!r){var i=(_(e)?void 0:e[n])||(r?r.current:void 0);if(!!i)return{current:i,states:Tr(r,i)}}})}function Vn(t,e){return{current:e,states:Tr(t,e)}}function br(t,e,r,n){var i=t&&r.reduce(function(s,o){var a,u,f=o.assignment,c={state:n,action:o,_event:e},p={};if(N(f))p=f(s,e.data,c);else try{for(var d=b(Object.keys(f)),l=d.next();!l.done;l=d.next()){var h=l.value,v=f[h];p[h]=N(v)?v(s,e.data,c):v}}catch(m){a={error:m}}finally{try{l&&!l.done&&(u=d.return)&&u.call(d)}finally{if(a)throw a.error}}return Object.assign({},s,p)},t);return i}var Ut=function(){};function ve(t){return Array.isArray(t)}function N(t){return typeof t=="function"}function _(t){return typeof t=="string"}function Ar(t,e){if(!!t)return _(t)?{type:Pt,name:t,predicate:e?e[t]:void 0}:N(t)?{type:Pt,name:t.name,predicate:t}:t}function Kn(t){try{return"subscribe"in t&&N(t.subscribe)}catch{return!1}}var ie=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();He={},He[ie]=function(){return this},He[Symbol.observable]=function(){return this};function me(t){return!!t&&"__xstatenode"in t}function Hn(t){return!!t&&typeof t.send=="function"}function Lt(t,e){return _(t)||typeof t=="number"?y({type:t},e):t}function j(t,e){if(!_(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=Lt(t);return y({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function ye(t,e){var r=wr(e).map(function(n){return typeof n=="undefined"||typeof n=="string"||me(n)?{target:n,event:t}:y(y({},n),{event:t})});return r}function zn(t){if(!(t===void 0||t===Ln))return z(t)}function Wn(t,e,r){if(!De){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 xr(t,e,r,n,i){var s=t.options.guards,o={state:i,cond:e,_event:n};if(e.type===Pt)return((s==null?void 0:s[e.name])||e.predicate)(r,n.data,o);var a=s==null?void 0:s[e.type];if(!a)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return a(r,n.data,o)}function Or(t){return typeof t=="string"?{type:t}:t}function Je(t,e,r){var n=function(){},i=typeof t=="object",s=i?t:null;return{next:((i?t.next:t)||n).bind(s),error:((i?t.error:e)||n).bind(s),complete:((i?t.complete:r)||n).bind(s)}}function Ye(t,e){return"".concat(t,":invocation[").concat(e,"]")}var ge=j({type:Pn});function $t(t,e){return e&&e[t]||void 0}function $e(t,e){var r;if(_(t)||typeof t=="number"){var n=$t(t,e);N(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(N(t))r={type:t.name||t.toString(),exec:t};else{var n=$t(t.type,e);if(N(n))r=y(y({},t),{exec:n});else if(n){var i=n.type||t.type;r=y(y(y({},n),t),{type:i})}else r=t}return r}var se=function(t,e){if(!t)return[];var r=ve(t)?t:[t];return r.map(function(n){return $e(n,e)})};function jt(t){var e=$e(t);return y(y({id:_(t)?t:e.id},e),{type:e.type})}function Gn(t){return _(t)?{type:he,event:t}:Mt(t,{to:ne.Internal})}function Jn(t){return{type:he,_event:j(t.event)}}function Mt(t,e){return{to:e?e.to:void 0,type:pe,event:N(t)?t:Lt(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:N(t)?t.name:gr(t)}}function Yn(t,e,r,n){var i={_event:r},s=j(N(t.event)?t.event(e,r.data,i):t.event),o;if(_(t.delay)){var a=n&&n[t.delay];o=N(a)?a(e,r.data,i):a}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;var u=N(t.to)?t.to(e,r.data,i):t.to;return y(y({},t),{to:u,_event:s,event:s.data,delay:o})}var Qn=function(t,e,r){return y(y({},t),{value:_(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Xn=function(t){return{type:dr,sendId:t}};function Zn(t){var e=jt(t);return{type:k.Start,activity:e,exec:void 0}}function ei(t){var e=N(t)?t:jt(t);return{type:k.Stop,activity:e,exec:void 0}}function ti(t,e,r){var n=N(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,s={type:k.Stop,activity:i};return s}var ri=function(t){return{type:kt,assignment:t}};function ni(t,e){var r=e?"#".concat(e):"";return"".concat(k.After,"(").concat(t,")").concat(r)}function Qe(t,e){var r="".concat(k.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Xe(t,e){var r="".concat(k.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function je(t,e){var r="".concat(k.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}var ii=function(t){var e,r,n=[];try{for(var i=b(t),s=i.next();!s.done;s=i.next())for(var o=s.value,a=0;a<o.length;){if(o[a].type===kt){n.push(o[a]),o.splice(a,1);continue}a++}}catch(u){e={error:u}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function Ze(t,e,r,n,i,s,o){o===void 0&&(o=!1);var a=o?[]:ii(i),u=a.length?br(r,n,a,e):r,f=o?[r]:void 0,c=[];function p(h){var v;switch(h.type){case he:return Jn(h);case pe:var m=Yn(h,u,n,t.options.delays);return s&&m.to!==ne.Internal&&c.push(m),m;case hr:{var E=Qn(h,u,n);return s==null||s(E,u,n),E}case Dn:{var g=h,w=(v=g.conds.find(function(J){var re=Ar(J.cond,t.options.guards);return!re||xr(t,re,u,n,s?void 0:e)}))===null||v===void 0?void 0:v.actions;if(!w)return[];var O=A(Ze(t,e,u,n,[se(z(w),t.options.actions)],s,o),2),T=O[0],D=O[1];return u=D,f==null||f.push(u),T}case Un:{var w=h.get(u,n.data);if(!w)return[];var x=A(Ze(t,e,u,n,[se(z(w),t.options.actions)],s,o),2),R=x[0],I=x[1];return u=I,f==null||f.push(u),R}case It:{var E=ti(h,u,n);return s==null||s(E,r,n),E}case kt:{u=br(u,n,[h],s?void 0:e),f==null||f.push(u);break}default:var S=$e(h,t.options.actions),C=S.exec;if(s)s(S,u,n);else if(C&&f){var K=f.length-1;S=y(y({},S),{exec:function(J){for(var re=[],ke=1;ke<arguments.length;ke++)re[ke-1]=arguments[ke];C.apply(void 0,P([f[K]],A(re),!1))}})}return S}}function d(h){var v,m,E=[];try{for(var g=b(h),w=g.next();!w.done;w=g.next()){var O=w.value,T=p(O);T&&(E=E.concat(T))}}catch(D){v={error:D}}finally{try{w&&!w.done&&(m=g.return)&&m.call(g)}finally{if(v)throw v.error}}return c.forEach(function(D){s(D,u,n)}),c.length=0,E}var l=U(i.map(d));return[l,u]}var Ee=function(t,e){var r=e(t);return r};function Rr(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[ie]=function(){return this},e}function si(t,e,r,n){var i,s=Or(t.src),o=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[s.type],a=t.data?Ge(t.data,r,n):void 0,u=o?_r(o,t.id,a):Rr(t.id);return u.meta=t,u}function _r(t,e,r){var n=Rr(e);if(n.deferred=!0,me(t)){var i=n.state=Ee(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function oi(t){try{return typeof t.send=="function"}catch{return!1}}function ai(t){return oi(t)&&"id"in t}function ui(t){var e;return y((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[ie]=function(){return this},e),t)}var et=function(t){return t.type==="atomic"||t.type==="final"};function Ir(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function Me(t){return Ir(t).filter(function(e){return e.type!=="history"})}function kr(t){var e=[t];return et(t)?e:e.concat(U(Me(t).map(kr)))}function qe(t,e){var r,n,i,s,o,a,u,f,c=new Set(t),p=qt(c),d=new Set(e);try{for(var l=b(d),h=l.next();!h.done;h=l.next())for(var v=h.value,m=v.parent;m&&!d.has(m);)d.add(m),m=m.parent}catch(I){r={error:I}}finally{try{h&&!h.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}var E=qt(d);try{for(var g=b(d),w=g.next();!w.done;w=g.next()){var v=w.value;if(v.type==="compound"&&(!E.get(v)||!E.get(v).length))p.get(v)?p.get(v).forEach(function(S){return d.add(S)}):v.initialStateNodes.forEach(function(S){return d.add(S)});else if(v.type==="parallel")try{for(var O=(o=void 0,b(Me(v))),T=O.next();!T.done;T=O.next()){var D=T.value;d.has(D)||(d.add(D),p.get(D)?p.get(D).forEach(function(S){return d.add(S)}):D.initialStateNodes.forEach(function(S){return d.add(S)}))}}catch(S){o={error:S}}finally{try{T&&!T.done&&(a=O.return)&&a.call(O)}finally{if(o)throw o.error}}}}catch(I){i={error:I}}finally{try{w&&!w.done&&(s=g.return)&&s.call(g)}finally{if(i)throw i.error}}try{for(var x=b(d),R=x.next();!R.done;R=x.next())for(var v=R.value,m=v.parent;m&&!d.has(m);)d.add(m),m=m.parent}catch(I){u={error:I}}finally{try{R&&!R.done&&(f=x.return)&&f.call(x)}finally{if(u)throw u.error}}return d}function Nr(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(et(n))return n.key}else return{}}var i={};return r.forEach(function(s){i[s.key]=Nr(s,e)}),i}function qt(t){var e,r,n=new Map;try{for(var i=b(t),s=i.next();!s.done;s=i.next()){var o=s.value;n.has(o)||n.set(o,[]),o.parent&&(n.has(o.parent)||n.set(o.parent,[]),n.get(o.parent).push(o))}}catch(a){e={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function ci(t,e){var r=qe([t],e);return Nr(t,qt(r))}function Be(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function li(t){return P([],A(new Set(U(P([],A(t.map(function(e){return e.ownEvents})),!1)))),!1)}function tt(t,e){return e.type==="compound"?Me(e).some(function(r){return r.type==="final"&&Be(t,r)}):e.type==="parallel"?Me(e).every(function(r){return tt(t,r)}):!1}function fi(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Pr(t){return new Set(U(t.map(function(e){return e.tags})))}function Cr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(_(t)||_(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Cr(t[i],e[i])})}function di(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function hi(t,e){var r=t.exec,n=y(y({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var X=function(){function t(e){var r=this,n;this.actions=[],this.activities=yr,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||yr,this.meta=fi(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 li(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=ge;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=ge;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="."),_(e))return[e];var i=Object.keys(e);return i.concat.apply(i,P([],A(i.map(function(s){return n.toStrings(e[s],r).map(function(o){return s+r+o})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=Rt(e,["configuration","transitions","tags","machine"]);return y(y({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Ct(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;Ut(!!this.machine);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}(),pi={deferEvents:!1},Dr=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=y(y({},pi),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}(),Bt=new Map,vi=0,rt={bookId:function(){return"x:".concat(vi++)},register:function(t,e){return Bt.set(t,e),t},get:function(t){return Bt.get(t)},free:function(t){Bt.delete(t)}};function Ft(){if(typeof globalThis!="undefined")return globalThis;if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;De||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 mi(){var t=Ft();if(t&&"__xstate__"in t)return t.__xstate__}function yi(t){if(!!Ft()){var e=mi();e&&e.register(t)}}function gi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],s=!1,o=function(){if(!s){for(s=!0;i.length>0;){var f=i.shift();r=t.transition(r,f,u),n.forEach(function(c){return c.next(r)})}s=!1}},a=ui({id:e.id,send:function(f){i.push(f),o()},getSnapshot:function(){return r},subscribe:function(f,c,p){var d=Je(f,c,p);return n.add(d),d.next(r),{unsubscribe:function(){n.delete(d)}}}}),u={parent:e.parent,self:a,id:e.id||"anonymous",observers:n};return r=t.start?t.start(u):r,a}var Ei={sync:!1,autoForward:!1},M;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(M||(M={}));var wi=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=M.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(c,p){if(ve(c))return n.batch(c),n.state;var d=j(Lt(c,p));if(n.status===M.Stopped)return n.state;if(n.status!==M.Running&&!n.options.deferEvents)throw new Error('Event "'.concat(d.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.
15
- Event: `).concat(JSON.stringify(d.data)));return n.scheduler.schedule(function(){n.forward(d);var l=n._nextState(d);n.update(l,d)}),n._state},this.sendTo=function(c,p,d){var l=n.parent&&(p===ne.Parent||n.parent.id===p),h=l?n.parent:_(p)?n.children.get(p)||rt.get(p):Hn(p)?p:void 0;if(!h){if(!l)throw new Error("Unable to send event to child '".concat(p,"' from service '").concat(n.id,"'."));return}if("machine"in h){if(n.status!==M.Stopped||n.parent!==h||n.state.done){var v=y(y({},c),{name:c.name===Cn?"".concat(je(n.id)):c.name,origin:n.sessionId});!d&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([h,v]):h.send(v)}}else!d&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([h,c.data]):h.send(c.data)},this._exec=function(c,p,d,l){l===void 0&&(l=n.machine.options.actions);var h=c.exec||$t(c.type,l),v=N(h)?h:h?h.exec:c.exec;if(v)try{return v(p,d.data,n.machine.config.predictableActionArguments?{action:c,_event:d}:{action:c,state:n.state,_event:d})}catch(K){throw n.parent&&n.parent.send({type:"xstate.error",data:K}),K}switch(c.type){case pe:var m=c;if(typeof m.delay=="number"){n.defer(m);return}else m.to?n.sendTo(m._event,m.to,d===ge):n.send(m._event);break;case dr:n.cancel(c.sendId);break;case _t:{if(n.status!==M.Running)return;var E=c.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[E.id||E.type])break;if(E.type===k.Invoke){var g=Or(E.src),w=n.machine.options.services?n.machine.options.services[g.type]:void 0,O=E.id,T=E.data,D="autoForward"in E?E.autoForward:!!E.forward;if(!w)return;var x=T?Ge(T,p,d):void 0;if(typeof w=="string")return;var R=N(w)?w(p,d.data,{data:x,src:g,meta:E.meta}):w;if(!R)return;var I=void 0;me(R)&&(R=x?R.withContext(x):R,I={autoForward:D}),n.spawn(R,O,I)}else n.spawnActivity(E);break}case It:{n.stopChild(c.activity.id);break}case hr:var S=c.label,C=c.value;S?n.logger(S,C):n.logger(C);break}};var i=y(y({},t.defaultOptions),r),s=i.clock,o=i.logger,a=i.parent,u=i.id,f=u!==void 0?u:e.id;this.id=f,this.logger=o,this.clock=s,this.parent=a,this.options=i,this.scheduler=new Dr({deferEvents:this.options.deferEvents}),this.sessionId=rt.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:Ee(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),t.prototype.execute=function(e,r){var n,i;try{for(var s=b(e.actions),o=s.next();!o.done;o=s.next()){var a=o.value;this.exec(a,e,r)}}catch(u){n={error:u}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,s,o,a,u,f,c,p=this;if(e._sessionid=this.sessionId,this._state=e,(!this.machine.config.predictableActionArguments||r===ge)&&this.options.execute)this.execute(this.state);else for(var d=void 0;d=this._outgoingQueue.shift();)d[0].send(d[1]);if(this.children.forEach(function(I){p.state.children[I.id]=I}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var l=b(this.eventListeners),h=l.next();!h.done;h=l.next()){var v=h.value;v(e.event)}}catch(I){n={error:I}}finally{try{h&&!h.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}try{for(var m=b(this.listeners),E=m.next();!E.done;E=m.next()){var v=E.value;v(e,e.event)}}catch(I){s={error:I}}finally{try{E&&!E.done&&(o=m.return)&&o.call(m)}finally{if(s)throw s.error}}try{for(var g=b(this.contextListeners),w=g.next();!w.done;w=g.next()){var O=w.value;O(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(I){a={error:I}}finally{try{w&&!w.done&&(u=g.return)&&u.call(g)}finally{if(a)throw a.error}}if(this.state.done){var T=e.configuration.find(function(I){return I.type==="final"&&I.parent===p.machine}),D=T&&T.doneData?Ge(T.doneData,e.context,r):void 0;try{for(var x=b(this.doneListeners),R=x.next();!R.done;R=x.next()){var v=R.value;v(Xe(this.id,D))}}catch(I){f={error:I}}finally{try{R&&!R.done&&(c=x.return)&&c.call(x)}finally{if(f)throw f.error}}this._stop(),this._stopChildren()}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===M.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this,s=Je(e,r,n);this.listeners.add(s.next),this.status!==M.NotStarted&&s.next(this.state);var o=function(){i.doneListeners.delete(o),i.stopListeners.delete(o),s.complete()};return this.status===M.Stopped?s.complete():(this.onDone(o),this.onStop(o)),{unsubscribe:function(){i.listeners.delete(s.next),i.doneListeners.delete(o),i.stopListeners.delete(o)}}},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===M.Running)return this;this.machine._init(),rt.register(this.sessionId,this),this.initialized=!0,this.status=M.Running;var n=e===void 0?this.initialState:Ee(this,function(){return di(e)?r.machine.resolveState(e):r.machine.resolveState(X.from(e,r.machine.context))});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(function(){r.update(n,ge)}),this},t.prototype._stopChildren=function(){this.children.forEach(function(e){N(e.stop)&&e.stop()}),this.children.clear()},t.prototype._stop=function(){var e,r,n,i,s,o,a,u,f,c;try{for(var p=b(this.listeners),d=p.next();!d.done;d=p.next()){var l=d.value;this.listeners.delete(l)}}catch(x){e={error:x}}finally{try{d&&!d.done&&(r=p.return)&&r.call(p)}finally{if(e)throw e.error}}try{for(var h=b(this.stopListeners),v=h.next();!v.done;v=h.next()){var l=v.value;l(),this.stopListeners.delete(l)}}catch(x){n={error:x}}finally{try{v&&!v.done&&(i=h.return)&&i.call(h)}finally{if(n)throw n.error}}try{for(var m=b(this.contextListeners),E=m.next();!E.done;E=m.next()){var l=E.value;this.contextListeners.delete(l)}}catch(x){s={error:x}}finally{try{E&&!E.done&&(o=m.return)&&o.call(m)}finally{if(s)throw s.error}}try{for(var g=b(this.doneListeners),w=g.next();!w.done;w=g.next()){var l=w.value;this.doneListeners.delete(l)}}catch(x){a={error:x}}finally{try{w&&!w.done&&(u=g.return)&&u.call(g)}finally{if(a)throw a.error}}if(!this.initialized)return this;this.initialized=!1,this.status=M.Stopped,this._initialState=void 0;try{for(var O=b(Object.keys(this.delayedEventsMap)),T=O.next();!T.done;T=O.next()){var D=T.value;this.clock.clearTimeout(this.delayedEventsMap[D])}}catch(x){f={error:x}}finally{try{T&&!T.done&&(c=O.return)&&c.call(O)}finally{if(f)throw f.error}}this.scheduler.clear(),this.scheduler=new Dr({deferEvents:this.options.deferEvents})},t.prototype.stop=function(){var e=this,r=this.scheduler;return this._stop(),r.schedule(function(){var n=j({type:"xstate.stop"}),i=Ee(e,function(){var s=U(P([],A(e.state.configuration),!1).sort(function(c,p){return p.order-c.order}).map(function(c){return se(c.onExit,e.machine.options.actions)})),o=A(Ze(e.machine,e.state,e.state.context,n,[s],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),a=o[0],u=o[1],f=new X({value:e.state.value,context:u,_event:n,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:a.filter(function(c){return c.type!==he&&(c.type!==pe||!!c.to&&c.to!==ne.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(),rt.free(e.sessionId)}),this},t.prototype.batch=function(e){var r=this;if(this.status===M.NotStarted&&this.options.deferEvents)De||Ut(!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.
16
- Event: `).concat(JSON.stringify(event)));else if(this.status!==M.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,s,o=r.state,a=!1,u=[],f=function(l){var h=j(l);r.forward(h),o=Ee(r,function(){return r.machine.transition(o,h,void 0,n||void 0)}),u.push.apply(u,P([],A(r.machine.config.predictableActionArguments?o.actions:o.actions.map(function(v){return hi(v,o)})),!1)),a=a||!!o.changed};try{for(var c=b(e),p=c.next();!p.done;p=c.next()){var d=p.value;f(d)}}catch(l){i={error:l}}finally{try{p&&!p.done&&(s=c.return)&&s.call(c)}finally{if(i)throw i.error}}o.changed=a,o.actions=u,r.update(o,j(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=j(e);if(i.name.indexOf(pr)===0&&!this.state.nextEvents.some(function(o){return o.indexOf(pr)===0}))throw i.data.data;var s=Ee(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return s},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=b(this.forwardTo),s=i.next();!s.done;s=i.next()){var o=s.value,a=this.children.get(o);if(!a)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(o,"'."));a.send(e)}}catch(u){r={error:u}}finally{try{s&&!s.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),N(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==M.Running)return _r(e,r);if(Sr(e))return this.spawnPromise(Promise.resolve(e),r);if(N(e))return this.spawnCallback(e,r);if(ai(e))return this.spawnActor(e,r);if(Kn(e))return this.spawnObservable(e,r);if(me(e))return this.spawnMachine(e,y(y({},n),{id:r}));if(Bn(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,y(y({},this.options),{parent:this,id:r.id||e.id})),s=y(y({},Ei),r);s.sync&&i.onTransition(function(a){n.send(vr,{state:a,id:i.id})});var o=i;return this.children.set(i.id,o),s.autoForward&&this.forwardTo.add(i.id),i.onDone(function(a){n.removeChild(i.id),n.send(j(a,{origin:i.id}))}).start(),o},t.prototype.spawnBehavior=function(e,r){var n=gi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,s=!1,o;e.then(function(u){s||(o=u,i.removeChild(r),i.send(j(Xe(r,u),{origin:r})))},function(u){if(!s){i.removeChild(r);var f=je(r,u);try{i.send(j(f,{origin:r}))}catch(c){Wn(u,c,r),i.devTools&&i.devTools.send(f,i.state),i.machine.strict&&i.stop()}}});var a=(n={id:r,send:function(){},subscribe:function(u,f,c){var p=Je(u,f,c),d=!1;return e.then(function(l){d||(p.next(l),!d&&p.complete())},function(l){d||p.error(l)}),{unsubscribe:function(){return d=!0}}},stop:function(){s=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return o}},n[ie]=function(){return this},n);return this.children.set(r,a),a},t.prototype.spawnCallback=function(e,r){var n,i=this,s=!1,o=new Set,a=new Set,u,f=function(d){u=d,a.forEach(function(l){return l(d)}),!s&&i.send(j(d,{origin:r}))},c;try{c=e(f,function(d){o.add(d)})}catch(d){this.send(je(r,d))}if(Sr(c))return this.spawnPromise(c,r);var p=(n={id:r,send:function(d){return o.forEach(function(l){return l(d)})},subscribe:function(d){var l=Je(d);return a.add(l.next),{unsubscribe:function(){a.delete(l.next)}}},stop:function(){s=!0,N(c)&&c()},toJSON:function(){return{id:r}},getSnapshot:function(){return u}},n[ie]=function(){return this},n);return this.children.set(r,p),p},t.prototype.spawnObservable=function(e,r){var n,i=this,s,o=e.subscribe(function(u){s=u,i.send(j(u,{origin:r}))},function(u){i.removeChild(r),i.send(j(je(r,u),{origin:r}))},function(){i.removeChild(r),i.send(j(Xe(r),{origin:r}))}),a=(n={id:r,send:function(){},subscribe:function(u,f,c){return e.subscribe(u,f,c)},stop:function(){return o.unsubscribe()},getSnapshot:function(){return s},toJSON:function(){return{id:r}}},n[ie]=function(){return this},n);return this.children.set(r,a),a},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){De||Ut(!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[ie]=function(){return this},n))},t.prototype.attachDev=function(){var e=Ft();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(y(y({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:y({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}yi(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[ie]=function(){return this},t.prototype.getSnapshot=function(){return this.status===M.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=we,t}();function we(t,e){var r=new wi(t,e);return r}function Si(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function nt(t){return y(y({type:Nt},t),{toJSON:function(){t.onDone,t.onError;var e=Rt(t,["onDone","onError"]);return y(y({},e),{type:Nt,src:Si(t.src)})}})}var it="",Vt="#",Kt="*",Se={},Te=function(t){return t[0]===Vt},Ti=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},bi=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var s=this,o;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(Ti(),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:mr),this.id=this.config.id||P([this.machine.key],A(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:(o=this.config.schema)!==null&&o!==void 0?o:{},this.description=this.config.description,this.initial=this.config.initial,this.states=this.config.states?Le(this.config.states,function(f,c){var p,d=new t(f,{},void 0,{parent:s,key:c});return Object.assign(s.idMap,y((p={},p[d.id]=d,p),d.idMap)),d}):Se;var a=0;function u(f){var c,p;f.order=a++;try{for(var d=b(Ir(f)),l=d.next();!l.done;l=d.next()){var h=l.value;u(h)}}catch(v){c={error:v}}finally{try{l&&!l.done&&(p=d.return)&&p.call(d)}finally{if(c)throw c.error}}}u(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===it}):it in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=z(this.config.entry||this.config.onEntry).map(function(f){return $e(f)}),this.onExit=z(this.config.exit||this.config.onExit).map(function(f){return $e(f)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=z(this.config.invoke).map(function(f,c){var p,d;if(me(f)){var l=Ye(s.id,c);return s.machine.options.services=y((p={},p[l]=f,p),s.machine.options.services),nt({src:l,id:l})}else if(_(f.src)){var l=f.id||Ye(s.id,c);return nt(y(y({},f),{id:l,src:f.src}))}else if(me(f.src)||N(f.src)){var l=f.id||Ye(s.id,c);return s.machine.options.services=y((d={},d[l]=f.src,d),s.machine.options.services),nt(y(y({id:l},f),{src:l}))}else{var h=f.src;return nt(y(y({id:Ye(s.id,c)},f),{src:h}))}}),this.activities=z(this.config.activities).concat(this.invoke).map(function(f){return jt(f)}),this.transition=this.transition.bind(this),this.tags=z(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||kr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,s=n.activities,o=n.guards,a=n.services,u=n.delays;return new t(this.config,{actions:y(y({},i),e.actions),activities:y(y({},s),e.activities),guards:y(y({},o),e.guards),services:y(y({},a),e.services),delays:y(y({},u),e.delays)},r!=null?r:this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return N(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:Le(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===it,n=this.transitions.filter(function(i){var s=i.eventType===e;return r?s:s||i.eventType===Kt});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(s,o){var a=N(s)?"".concat(e.id,":delay[").concat(o,"]"):s,u=ni(a,e.id);return e.onEntry.push(Mt(u,{delay:s})),e.onExit.push(Xn(u)),u},i=ve(r)?r.map(function(s,o){var a=n(s.delay,o);return y(y({},s),{event:a})}):U(Object.keys(r).map(function(s,o){var a=r[s],u=_(a)?{target:a}:a,f=isNaN(+s)?s:+s,c=n(f,o);return z(u).map(function(p){return y(y({},p),{event:c,delay:f})})}));return i.map(function(s){var o=s.delay;return y(y({},e.formatTransition(s)),{delay:o})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof X?e.value:Ue(e,this.delimiter);if(_(i)){var s=this.getStateNode(i).initial;return s!==void 0?this.getStateNodes((r={},r[i]=s,r)):[this,this.states[i]]}var o=Object.keys(i),a=[this];return a.push.apply(a,P([],A(U(o.map(function(u){return n.getStateNode(u).getStateNodes(i[u])}))),!1)),a},t.prototype.handles=function(e){var r=gr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof X?e:X.create(e),n=Array.from(qe([],this.getStateNodes(r.value)));return new X(y(y({},r),{value:this.resolve(r.value),configuration:n,done:tt(n,this),tags:Pr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),s=i.next(r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),s=this.getStateNode(i[0]),o=s._transition(e[i[0]],r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionParallelNode=function(e,r,n){var i,s,o={};try{for(var a=b(Object.keys(e)),u=a.next();!u.done;u=a.next()){var f=u.value,c=e[f];if(!!c){var p=this.getStateNode(f),d=p._transition(c,r,n);d&&(o[f]=d)}}}catch(g){i={error:g}}finally{try{u&&!u.done&&(s=a.return)&&s.call(a)}finally{if(i)throw i.error}}var l=Object.keys(o).map(function(g){return o[g]}),h=U(l.map(function(g){return g.transitions})),v=l.some(function(g){return g.transitions.length>0});if(!v)return this.next(r,n);var m=U(l.map(function(g){return g.entrySet})),E=U(Object.keys(o).map(function(g){return o[g].configuration}));return{transitions:h,entrySet:m,exitSet:U(l.map(function(g){return g.exitSet})),configuration:E,source:r,actions:U(Object.keys(o).map(function(g){return o[g].actions}))}},t.prototype._transition=function(e,r,n){return _(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,j(r))},t.prototype.next=function(e,r){var n,i,s=this,o=r.name,a=[],u=[],f;try{for(var c=b(this.getCandidates(o)),p=c.next();!p.done;p=c.next()){var d=p.value,l=d.cond,h=d.in,v=e.context,m=h?_(h)&&Te(h)?e.matches(Ue(this.getStateNodeById(h).path,this.delimiter)):Ct(Ue(h,this.delimiter),jn(this.path.slice(0,-2))(e.value)):!0,E=!1;try{E=!l||xr(this.machine,l,v,r,e)}catch(T){throw new Error("Unable to evaluate guard '".concat(l.name||l.type,"' in transition for event '").concat(o,"' in state node '").concat(this.id,`':
17
- `).concat(T.message))}if(E&&m){d.target!==void 0&&(u=d.target),a.push.apply(a,P([],A(d.actions),!1)),f=d;break}}}catch(T){n={error:T}}finally{try{p&&!p.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}if(!!f){if(!u.length)return{transitions:[f],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:a};var g=U(u.map(function(T){return s.getRelativeStateNodes(T,e.historyValue)})),w=!!f.internal,O=[];return w||u.forEach(function(T){O.push.apply(O,P([],A(s.getExternalReentryNodes(T)),!1))}),{transitions:[f],entrySet:O,exitSet:w?[]:[this],configuration:g,source:e,actions:a}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=A(e.order>this.order?[e,this]:[this,e],2),i=n[0],s=n[1];i&&i!==s;)r.push(i),i=i.parent;return i!==s?[]:(r.push(s),r)},t.prototype.getActions=function(e,r,n,i,s,o,a){var u,f,c,p,d=this,l=qe([],o?this.getStateNodes(o.value):[this]);try{for(var h=b(e),v=h.next();!v.done;v=h.next()){var m=v.value;(!Be(l,m)||Be(n.entrySet,m.parent))&&n.entrySet.push(m)}}catch(S){u={error:S}}finally{try{v&&!v.done&&(f=h.return)&&f.call(h)}finally{if(u)throw u.error}}try{for(var E=b(l),g=E.next();!g.done;g=E.next()){var m=g.value;(!Be(e,m)||Be(n.exitSet,m.parent))&&n.exitSet.push(m)}}catch(S){c={error:S}}finally{try{g&&!g.done&&(p=E.return)&&p.call(E)}finally{if(c)throw c.error}}var w=U(n.entrySet.map(function(S){var C=[];if(S.type!=="final")return C;var K=S.parent;if(!K.parent)return C;C.push(Qe(S.id,S.doneData),Qe(K.id,S.doneData?Ge(S.doneData,i,s):void 0));var J=K.parent;return J.type==="parallel"&&Me(J).every(function(re){return tt(n.configuration,re)})&&C.push(Qe(J.id)),C}));n.exitSet.sort(function(S,C){return C.order-S.order}),n.entrySet.sort(function(S,C){return S.order-C.order});var O=new Set(n.entrySet),T=new Set(n.exitSet),D=Array.from(O).map(function(S){var C=S.onEntry,K=S.activities.map(function(J){return Zn(J)});return se(a?P(P([],A(C),!1),A(K),!1):P(P([],A(K),!1),A(C),!1),d.machine.options.actions)}).concat([w.map(Gn)]),x=Array.from(T).map(function(S){return se(P(P([],A(S.onExit),!1),A(S.activities.map(function(C){return ei(C)})),!1),d.machine.options.actions)}),R=x.concat([se(n.actions,this.machine.options.actions)]).concat(D);if(r){var I=se(U(P([],A(e),!1).sort(function(S,C){return C.order-S.order}).map(function(S){return S.onExit})),this.machine.options.actions).filter(function(S){return S.type!==he&&(S.type!==pe||!!S.to&&S.to!==ne.Internal)});return R.concat([I])}return R},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var s=j(r),o;if(e instanceof X)o=n===void 0?e:this.resolveState(X.from(e,n));else{var a=_(e)?this.resolve(ze(this.getResolvedPath(e))):this.resolve(e),u=n!=null?n:this.machine.context;o=this.resolveState(X.from(a,u))}if(this.strict&&!this.events.includes(s.name)&&!qn(s.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(s.name,"'"));var f=this._transition(o.value,o,s)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:o,actions:[]},c=qe([],this.getStateNodes(o.value)),p=f.configuration.length?qe(c,f.configuration):c;return f.configuration=P([],A(p),!1),this.resolveTransition(f,o,o.context,i,s)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var s,o=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(s=e.actions).unshift.apply(s,P([],A(o),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,s){var o,a,u,f,c=this;s===void 0&&(s=ge);var p=e.configuration,d=!r||e.transitions.length>0,l=d?e.configuration:r?r.configuration:[],h=tt(l,this),v=d?ci(this.machine,p):void 0,m=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,E=this.getActions(new Set(l),h,e,n,s,r,i),g=r?y({},r.activities):{};try{for(var w=b(E),O=w.next();!O.done;O=w.next()){var T=O.value;try{for(var D=(u=void 0,b(T)),x=D.next();!x.done;x=D.next()){var R=x.value;R.type===_t?g[R.activity.id||R.activity.type]=R:R.type===It&&(g[R.activity.id||R.activity.type]=!1)}}catch(F){u={error:F}}finally{try{x&&!x.done&&(f=D.return)&&f.call(D)}finally{if(u)throw u.error}}}}catch(F){o={error:F}}finally{try{O&&!O.done&&(a=w.return)&&a.call(w)}finally{if(o)throw o.error}}var I=A(Ze(this,r,n,s,E,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),S=I[0],C=I[1],K=A(Fn(S,function(F){return F.type===he||F.type===pe&&F.to===ne.Internal}),2),J=K[0],re=K[1],ke=S.filter(function(F){var Pe;return F.type===_t&&((Pe=F.activity)===null||Pe===void 0?void 0:Pe.type)===Nt}),Mo=ke.reduce(function(F,Pe){return F[Pe.activity.id]=si(Pe.activity,c.machine,C,s),F},r?y({},r.children):{}),xt=new X({value:v||r.value,context:C,_event:s,_sessionid:r?r._sessionid:null,historyValue:v?m?Vn(m,v):void 0:r?r.historyValue:void 0,history:!v||e.source?r:void 0,actions:v?re:[],activities:v?g:r?r.activities:{},events:[],configuration:l,transitions:e.transitions,children:Mo,done:h,tags:Pr(l),machine:this}),Rn=n!==C;xt.changed=s.name===vr||Rn;var Ne=xt.history;Ne&&delete Ne.history;var _n=!h&&(this._transient||p.some(function(F){return F._transient}));if(!d&&(!_n||s.name===it))return xt;var Y=xt;if(!h)for(_n&&(Y=this.resolveRaisedTransition(Y,{type:Nn},s,i));J.length;){var qo=J.shift();Y=this.resolveRaisedTransition(Y,qo._event,s,i)}var Bo=Y.changed||(Ne?!!Y.actions.length||Rn||typeof Ne.value!=typeof Y.value||!Cr(Y.value,Ne.value):void 0);return Y.changed=Bo,Y.history=Ne,Y},t.prototype.getStateNode=function(e){if(Te(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=Te(e)?e.slice(Vt.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"&&Te(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=Dt(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||Se;switch(this.type){case"parallel":return Le(this.initialStateValue,function(s,o){return s?n.getStateNode(o).resolve(e[o]||s):Se});case"compound":if(_(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?Le(e,function(s,o){return s?n.getStateNode(o).resolve(s):Se}):this.initialStateValue||{};default:return e||Se}},t.prototype.getResolvedPath=function(e){if(Te(e)){var r=this.machine.idMap[e.slice(Vt.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Dt(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=Er(this.states,function(n){return n.initialStateValue||Se},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=et(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:P([],A(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r!=null?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;_(r.target)?e=Te(r.target)?ze(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(et(this))return[this];if(this.type==="compound"&&!this.initial)return[this];var r=We(this.initialStateValue);return U(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=A(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 s=this.getStateNode(n);if(s.type==="history")return s.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:Er(this.states,function(r,n){if(!e)return r.historyValue();var i=_(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?U(We(i).map(function(o){return n.getFromRelativePath(o)})):n.initialStateNodes}var s=Mn(n.path,"states")(e).current;return _(s)?[n.getStateNode(s)]:U(We(s).map(function(o){return r.history==="deep"?n.getFromRelativePath(o):[n.states[o[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=U(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 s=this.states,o=new Set(this.ownEvents);if(s)try{for(var a=b(Object.keys(s)),u=a.next();!u.done;u=a.next()){var f=u.value,c=s[f];if(c.states)try{for(var p=(n=void 0,b(c.events)),d=p.next();!d.done;d=p.next()){var l=d.value;o.add("".concat(l))}}catch(h){n={error:h}}finally{try{d&&!d.done&&(i=p.return)&&i.call(p)}finally{if(n)throw n.error}}}}catch(h){e={error:h}}finally{try{u&&!u.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(o)},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(!_(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var s=i?r.key+n:n;if(r.parent)try{var o=r.parent.getStateNodeByPath(s);return o}catch(a){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
18
- `).concat(a.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=zn(e.target),i="internal"in e?e.internal:n?n.some(function(u){return _(u)&&u[0]===r.delimiter}):!0,s=this.machine.options.guards,o=this.resolveTarget(n),a=y(y({},e),{actions:se(z(e.actions)),cond:Ar(e.cond,s),target:o,source:this,internal:i,eventType:e.event,toJSON:function(){return y(y({},a),{target:a.target?a.target.map(function(u){return"#".concat(u.id)}):void 0,source:"#".concat(r.id)})}});return a},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 s=this.config.on,o=Kt,a=s[o],u=a===void 0?[]:a,f=Rt(s,[typeof o=="symbol"?o:o+""]);i=U(Object.keys(f).map(function(g){var w=ye(g,f[g]);return w}).concat(ye(Kt,u)))}var c=this.config.always?ye("",this.config.always):[],p=this.config.onDone?ye(String(Qe(this.id)),this.config.onDone):[],d=U(this.invoke.map(function(g){var w=[];return g.onDone&&w.push.apply(w,P([],A(ye(String(Xe(g.id)),g.onDone)),!1)),g.onError&&w.push.apply(w,P([],A(ye(String(je(g.id)),g.onError)),!1)),w})),l=this.after,h=U(P(P(P(P([],A(p),!1),A(d),!1),A(i),!1),A(c),!1).map(function(g){return z(g).map(function(w){return n.formatTransition(w)})}));try{for(var v=b(l),m=v.next();!m.done;m=v.next()){var E=m.value;h.push(E)}}catch(g){e={error:g}}finally{try{m&&!m.done&&(r=v.return)&&r.call(v)}finally{if(e)throw e.error}}return h},t}(),Ur=!1;function Fe(t,e){return!De&&!t.predictableActionArguments&&!Ur&&(Ur=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new bi(t,e)}var L=ri,W=Mt,Ht={exports:{}},Lr=function(e,r){return function(){for(var i=new Array(arguments.length),s=0;s<i.length;s++)i[s]=arguments[s];return e.apply(r,i)}},Ai=Lr,zt=Object.prototype.toString,Wt=function(t){return function(e){var r=zt.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())}}(Object.create(null));function le(t){return t=t.toLowerCase(),function(r){return Wt(r)===t}}function Gt(t){return Array.isArray(t)}function st(t){return typeof t=="undefined"}function xi(t){return t!==null&&!st(t)&&t.constructor!==null&&!st(t.constructor)&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}var $r=le("ArrayBuffer");function Oi(t){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&$r(t.buffer),e}function Ri(t){return typeof t=="string"}function _i(t){return typeof t=="number"}function jr(t){return t!==null&&typeof t=="object"}function ot(t){if(Wt(t)!=="object")return!1;var e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}var Ii=le("Date"),ki=le("File"),Ni=le("Blob"),Pi=le("FileList");function Jt(t){return zt.call(t)==="[object Function]"}function Ci(t){return jr(t)&&Jt(t.pipe)}function Di(t){var e="[object FormData]";return t&&(typeof FormData=="function"&&t instanceof FormData||zt.call(t)===e||Jt(t.toString)&&t.toString()===e)}var Ui=le("URLSearchParams");function Li(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function $i(){return typeof navigator!="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function Yt(t,e){if(!(t===null||typeof t=="undefined"))if(typeof t!="object"&&(t=[t]),Gt(t))for(var r=0,n=t.length;r<n;r++)e.call(null,t[r],r,t);else for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.call(null,t[i],i,t)}function Qt(){var t={};function e(i,s){ot(t[s])&&ot(i)?t[s]=Qt(t[s],i):ot(i)?t[s]=Qt({},i):Gt(i)?t[s]=i.slice():t[s]=i}for(var r=0,n=arguments.length;r<n;r++)Yt(arguments[r],e);return t}function ji(t,e,r){return Yt(e,function(i,s){r&&typeof i=="function"?t[s]=Ai(i,r):t[s]=i}),t}function Mi(t){return t.charCodeAt(0)===65279&&(t=t.slice(1)),t}function qi(t,e,r,n){t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,r&&Object.assign(t.prototype,r)}function Bi(t,e,r){var n,i,s,o={};e=e||{};do{for(n=Object.getOwnPropertyNames(t),i=n.length;i-- >0;)s=n[i],o[s]||(e[s]=t[s],o[s]=!0);t=Object.getPrototypeOf(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e}function Fi(t,e,r){t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;var n=t.indexOf(e,r);return n!==-1&&n===r}function Vi(t){if(!t)return null;var e=t.length;if(st(e))return null;for(var r=new Array(e);e-- >0;)r[e]=t[e];return r}var Ki=function(t){return function(e){return t&&e instanceof t}}(typeof Uint8Array!="undefined"&&Object.getPrototypeOf(Uint8Array)),q={isArray:Gt,isArrayBuffer:$r,isBuffer:xi,isFormData:Di,isArrayBufferView:Oi,isString:Ri,isNumber:_i,isObject:jr,isPlainObject:ot,isUndefined:st,isDate:Ii,isFile:ki,isBlob:Ni,isFunction:Jt,isStream:Ci,isURLSearchParams:Ui,isStandardBrowserEnv:$i,forEach:Yt,merge:Qt,extend:ji,trim:Li,stripBOM:Mi,inherits:qi,toFlatObject:Bi,kindOf:Wt,kindOfTest:le,endsWith:Fi,toArray:Vi,isTypedArray:Ki,isFileList:Pi},be=q;function Mr(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var qr=function(e,r,n){if(!r)return e;var i;if(n)i=n(r);else if(be.isURLSearchParams(r))i=r.toString();else{var s=[];be.forEach(r,function(u,f){u===null||typeof u=="undefined"||(be.isArray(u)?f=f+"[]":u=[u],be.forEach(u,function(p){be.isDate(p)?p=p.toISOString():be.isObject(p)&&(p=JSON.stringify(p)),s.push(Mr(f)+"="+Mr(p))}))}),i=s.join("&")}if(i){var o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e},Hi=q;function at(){this.handlers=[]}at.prototype.use=function(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1},at.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},at.prototype.forEach=function(e){Hi.forEach(this.handlers,function(n){n!==null&&e(n)})};var zi=at,Wi=q,Gi=function(e,r){Wi.forEach(e,function(i,s){s!==r&&s.toUpperCase()===r.toUpperCase()&&(e[r]=i,delete e[s])})},Br=q;function Ae(t,e,r,n,i){Error.call(this),this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}Br.inherits(Ae,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var Fr=Ae.prototype,Vr={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach(function(t){Vr[t]={value:t}}),Object.defineProperties(Ae,Vr),Object.defineProperty(Fr,"isAxiosError",{value:!0}),Ae.from=function(t,e,r,n,i,s){var o=Object.create(Fr);return Br.toFlatObject(t,o,function(u){return u!==Error.prototype}),Ae.call(o,t.message,e,r,n,i),o.name=t.name,s&&Object.assign(o,s),o};var xe=Ae,Kr={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},G=q;function Ji(t,e){e=e||new FormData;var r=[];function n(s){return s===null?"":G.isDate(s)?s.toISOString():G.isArrayBuffer(s)||G.isTypedArray(s)?typeof Blob=="function"?new Blob([s]):Buffer.from(s):s}function i(s,o){if(G.isPlainObject(s)||G.isArray(s)){if(r.indexOf(s)!==-1)throw Error("Circular reference detected in "+o);r.push(s),G.forEach(s,function(u,f){if(!G.isUndefined(u)){var c=o?o+"."+f:f,p;if(u&&!o&&typeof u=="object"){if(G.endsWith(f,"{}"))u=JSON.stringify(u);else if(G.endsWith(f,"[]")&&(p=G.toArray(u))){p.forEach(function(d){!G.isUndefined(d)&&e.append(c,n(d))});return}}i(u,c)}}),r.pop()}else e.append(o,n(s))}return i(t),e}var Hr=Ji,Xt=xe,Yi=function(e,r,n){var i=n.config.validateStatus;!n.status||!i||i(n.status)?e(n):r(new Xt("Request failed with status code "+n.status,[Xt.ERR_BAD_REQUEST,Xt.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))},ut=q,Qi=ut.isStandardBrowserEnv()?function(){return{write:function(r,n,i,s,o,a){var u=[];u.push(r+"="+encodeURIComponent(n)),ut.isNumber(i)&&u.push("expires="+new Date(i).toGMTString()),ut.isString(s)&&u.push("path="+s),ut.isString(o)&&u.push("domain="+o),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(r){var n=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(r){this.write(r,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),Xi=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},Zi=function(e,r){return r?e.replace(/\/+$/,"")+"/"+r.replace(/^\/+/,""):e},es=Xi,ts=Zi,zr=function(e,r){return e&&!es(r)?ts(e,r):r},Zt=q,rs=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"],ns=function(e){var r={},n,i,s;return e&&Zt.forEach(e.split(`
19
- `),function(a){if(s=a.indexOf(":"),n=Zt.trim(a.substr(0,s)).toLowerCase(),i=Zt.trim(a.substr(s+1)),n){if(r[n]&&rs.indexOf(n)>=0)return;n==="set-cookie"?r[n]=(r[n]?r[n]:[]).concat([i]):r[n]=r[n]?r[n]+", "+i:i}}),r},Wr=q,is=Wr.isStandardBrowserEnv()?function(){var e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){var o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){var a=Wr.isString(o)?i(o):o;return a.protocol===n.protocol&&a.host===n.host}}():function(){return function(){return!0}}(),er=xe,ss=q;function Gr(t){er.call(this,t==null?"canceled":t,er.ERR_CANCELED),this.name="CanceledError"}ss.inherits(Gr,er,{__CANCEL__:!0});var ct=Gr,os=function(e){var r=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return r&&r[1]||""},Ve=q,as=Yi,us=Qi,cs=qr,ls=zr,fs=ns,ds=is,hs=Kr,ee=xe,ps=ct,vs=os,Jr=function(e){return new Promise(function(n,i){var s=e.data,o=e.headers,a=e.responseType,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}Ve.isFormData(s)&&Ve.isStandardBrowserEnv()&&delete o["Content-Type"];var c=new XMLHttpRequest;if(e.auth){var p=e.auth.username||"",d=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";o.Authorization="Basic "+btoa(p+":"+d)}var l=ls(e.baseURL,e.url);c.open(e.method.toUpperCase(),cs(l,e.params,e.paramsSerializer),!0),c.timeout=e.timeout;function h(){if(!!c){var E="getAllResponseHeaders"in c?fs(c.getAllResponseHeaders()):null,g=!a||a==="text"||a==="json"?c.responseText:c.response,w={data:g,status:c.status,statusText:c.statusText,headers:E,config:e,request:c};as(function(T){n(T),f()},function(T){i(T),f()},w),c=null}}if("onloadend"in c?c.onloadend=h:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(h)},c.onabort=function(){!c||(i(new ee("Request aborted",ee.ECONNABORTED,e,c)),c=null)},c.onerror=function(){i(new ee("Network Error",ee.ERR_NETWORK,e,c,c)),c=null},c.ontimeout=function(){var g=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",w=e.transitional||hs;e.timeoutErrorMessage&&(g=e.timeoutErrorMessage),i(new ee(g,w.clarifyTimeoutError?ee.ETIMEDOUT:ee.ECONNABORTED,e,c)),c=null},Ve.isStandardBrowserEnv()){var v=(e.withCredentials||ds(l))&&e.xsrfCookieName?us.read(e.xsrfCookieName):void 0;v&&(o[e.xsrfHeaderName]=v)}"setRequestHeader"in c&&Ve.forEach(o,function(g,w){typeof s=="undefined"&&w.toLowerCase()==="content-type"?delete o[w]:c.setRequestHeader(w,g)}),Ve.isUndefined(e.withCredentials)||(c.withCredentials=!!e.withCredentials),a&&a!=="json"&&(c.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&c.addEventListener("progress",e.onDownloadProgress),typeof e.onUploadProgress=="function"&&c.upload&&c.upload.addEventListener("progress",e.onUploadProgress),(e.cancelToken||e.signal)&&(u=function(E){!c||(i(!E||E&&E.type?new ps:E),c.abort(),c=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u))),s||(s=null);var m=vs(l);if(m&&["http","https","file"].indexOf(m)===-1){i(new ee("Unsupported protocol "+m+":",ee.ERR_BAD_REQUEST,e));return}c.send(s)})},ms=null,$=q,Yr=Gi,Qr=xe,ys=Kr,gs=Hr,Es={"Content-Type":"application/x-www-form-urlencoded"};function Xr(t,e){!$.isUndefined(t)&&$.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}function ws(){var t;return(typeof XMLHttpRequest!="undefined"||typeof process!="undefined"&&Object.prototype.toString.call(process)==="[object process]")&&(t=Jr),t}function Ss(t,e,r){if($.isString(t))try{return(e||JSON.parse)(t),$.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var lt={transitional:ys,adapter:ws(),transformRequest:[function(e,r){if(Yr(r,"Accept"),Yr(r,"Content-Type"),$.isFormData(e)||$.isArrayBuffer(e)||$.isBuffer(e)||$.isStream(e)||$.isFile(e)||$.isBlob(e))return e;if($.isArrayBufferView(e))return e.buffer;if($.isURLSearchParams(e))return Xr(r,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var n=$.isObject(e),i=r&&r["Content-Type"],s;if((s=$.isFileList(e))||n&&i==="multipart/form-data"){var o=this.env&&this.env.FormData;return gs(s?{"files[]":e}:e,o&&new o)}else if(n||i==="application/json")return Xr(r,"application/json"),Ss(e);return e}],transformResponse:[function(e){var r=this.transitional||lt.transitional,n=r&&r.silentJSONParsing,i=r&&r.forcedJSONParsing,s=!n&&this.responseType==="json";if(s||i&&$.isString(e)&&e.length)try{return JSON.parse(e)}catch(o){if(s)throw o.name==="SyntaxError"?Qr.from(o,Qr.ERR_BAD_RESPONSE,this,null,this.response):o}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ms},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};$.forEach(["delete","get","head"],function(e){lt.headers[e]={}}),$.forEach(["post","put","patch"],function(e){lt.headers[e]=$.merge(Es)});var tr=lt,Ts=q,bs=tr,As=function(e,r,n){var i=this||bs;return Ts.forEach(n,function(o){e=o.call(i,e,r)}),e},Zr=function(e){return!!(e&&e.__CANCEL__)},en=q,rr=As,xs=Zr,Os=tr,Rs=ct;function nr(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Rs}var _s=function(e){nr(e),e.headers=e.headers||{},e.data=rr.call(e,e.data,e.headers,e.transformRequest),e.headers=en.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),en.forEach(["delete","get","head","post","put","patch","common"],function(i){delete e.headers[i]});var r=e.adapter||Os.adapter;return r(e).then(function(i){return nr(e),i.data=rr.call(e,i.data,i.headers,e.transformResponse),i},function(i){return xs(i)||(nr(e),i&&i.response&&(i.response.data=rr.call(e,i.response.data,i.response.headers,e.transformResponse))),Promise.reject(i)})},H=q,tn=function(e,r){r=r||{};var n={};function i(c,p){return H.isPlainObject(c)&&H.isPlainObject(p)?H.merge(c,p):H.isPlainObject(p)?H.merge({},p):H.isArray(p)?p.slice():p}function s(c){if(H.isUndefined(r[c])){if(!H.isUndefined(e[c]))return i(void 0,e[c])}else return i(e[c],r[c])}function o(c){if(!H.isUndefined(r[c]))return i(void 0,r[c])}function a(c){if(H.isUndefined(r[c])){if(!H.isUndefined(e[c]))return i(void 0,e[c])}else return i(void 0,r[c])}function u(c){if(c in r)return i(e[c],r[c]);if(c in e)return i(void 0,e[c])}var f={url:o,method:o,data:o,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:u};return H.forEach(Object.keys(e).concat(Object.keys(r)),function(p){var d=f[p]||s,l=d(p);H.isUndefined(l)&&d!==u||(n[p]=l)}),n},rn={version:"0.27.2"},Is=rn.version,oe=xe,ir={};["object","boolean","number","function","string","symbol"].forEach(function(t,e){ir[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var nn={};ir.transitional=function(e,r,n){function i(s,o){return"[Axios v"+Is+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return function(s,o,a){if(e===!1)throw new oe(i(o," has been removed"+(r?" in "+r:"")),oe.ERR_DEPRECATED);return r&&!nn[o]&&(nn[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,a):!0}};function ks(t,e,r){if(typeof t!="object")throw new oe("options must be an object",oe.ERR_BAD_OPTION_VALUE);for(var n=Object.keys(t),i=n.length;i-- >0;){var s=n[i],o=e[s];if(o){var a=t[s],u=a===void 0||o(a,s,t);if(u!==!0)throw new oe("option "+s+" must be "+u,oe.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new oe("Unknown option "+s,oe.ERR_BAD_OPTION)}}var Ns={assertOptions:ks,validators:ir},sn=q,Ps=qr,on=zi,an=_s,ft=tn,Cs=zr,un=Ns,Oe=un.validators;function Re(t){this.defaults=t,this.interceptors={request:new on,response:new on}}Re.prototype.request=function(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=ft(this.defaults,r),r.method?r.method=r.method.toLowerCase():this.defaults.method?r.method=this.defaults.method.toLowerCase():r.method="get";var n=r.transitional;n!==void 0&&un.assertOptions(n,{silentJSONParsing:Oe.transitional(Oe.boolean),forcedJSONParsing:Oe.transitional(Oe.boolean),clarifyTimeoutError:Oe.transitional(Oe.boolean)},!1);var i=[],s=!0;this.interceptors.request.forEach(function(l){typeof l.runWhen=="function"&&l.runWhen(r)===!1||(s=s&&l.synchronous,i.unshift(l.fulfilled,l.rejected))});var o=[];this.interceptors.response.forEach(function(l){o.push(l.fulfilled,l.rejected)});var a;if(!s){var u=[an,void 0];for(Array.prototype.unshift.apply(u,i),u=u.concat(o),a=Promise.resolve(r);u.length;)a=a.then(u.shift(),u.shift());return a}for(var f=r;i.length;){var c=i.shift(),p=i.shift();try{f=c(f)}catch(d){p(d);break}}try{a=an(f)}catch(d){return Promise.reject(d)}for(;o.length;)a=a.then(o.shift(),o.shift());return a},Re.prototype.getUri=function(e){e=ft(this.defaults,e);var r=Cs(e.baseURL,e.url);return Ps(r,e.params,e.paramsSerializer)},sn.forEach(["delete","get","head","options"],function(e){Re.prototype[e]=function(r,n){return this.request(ft(n||{},{method:e,url:r,data:(n||{}).data}))}}),sn.forEach(["post","put","patch"],function(e){function r(n){return function(s,o,a){return this.request(ft(a||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}Re.prototype[e]=r(),Re.prototype[e+"Form"]=r(!0)});var Ds=Re,Us=ct;function _e(t){if(typeof t!="function")throw new TypeError("executor must be a function.");var e;this.promise=new Promise(function(i){e=i});var r=this;this.promise.then(function(n){if(!!r._listeners){var i,s=r._listeners.length;for(i=0;i<s;i++)r._listeners[i](n);r._listeners=null}}),this.promise.then=function(n){var i,s=new Promise(function(o){r.subscribe(o),i=o}).then(n);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i){r.reason||(r.reason=new Us(i),e(r.reason))})}_e.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},_e.prototype.subscribe=function(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]},_e.prototype.unsubscribe=function(e){if(!!this._listeners){var r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}},_e.source=function(){var e,r=new _e(function(i){e=i});return{token:r,cancel:e}};var Ls=_e,$s=function(e){return function(n){return e.apply(null,n)}},js=q,Ms=function(e){return js.isObject(e)&&e.isAxiosError===!0},cn=q,qs=Lr,dt=Ds,Bs=tn,Fs=tr;function ln(t){var e=new dt(t),r=qs(dt.prototype.request,e);return cn.extend(r,dt.prototype,e),cn.extend(r,e),r.create=function(i){return ln(Bs(t,i))},r}var V=ln(Fs);V.Axios=dt,V.CanceledError=ct,V.CancelToken=Ls,V.isCancel=Zr,V.VERSION=rn.version,V.toFormData=Hr,V.AxiosError=xe,V.Cancel=V.CanceledError,V.all=function(e){return Promise.all(e)},V.spread=$s,V.isAxiosError=Ms,Ht.exports=V,Ht.exports.default=V;var ht=Ht.exports;/*! js-cookie v3.0.1 | MIT */function pt(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 Vs={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 sr(t,e){function r(i,s,o){if(typeof document!="undefined"){o=pt({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var u in o)!o[u]||(a+="; "+u,o[u]!==!0&&(a+="="+o[u].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+a}}function n(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},a=0;a<s.length;a++){var u=s[a].split("="),f=u.slice(1).join("=");try{var c=decodeURIComponent(u[0]);if(o[c]=t.read(f,c),i===c)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",pt({},s,{expires:-1}))},withAttributes:function(i){return sr(this.converter,pt({},this.attributes,i))},withConverter:function(i){return sr(pt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var or=sr(Vs,{path:"/"});function Ks(t){return new TextEncoder().encode(t)}function fe(t){const e=new Uint8Array(t);let r="";for(const i of e)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ar(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),s=new ArrayBuffer(i.length),o=new Uint8Array(s);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return s}function fn(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function dn(t){const{id:e}=t;return{...t,id:ar(e),transports:t.transports}}function hn(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class B extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}}function Hs({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 B("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 B("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 B("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new B("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new B("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 B('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new B("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const s=window.location.hostname;if(hn(s)){if(i.rp.id!==s)return new B(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new B(`${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 B("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new B("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class zs{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const vt=new zs;async function pn(t){if(!fn())throw new Error("WebAuthn is not supported in this browser");const r={publicKey:{...t,challenge:ar(t.challenge),user:{...t.user,id:Ks(t.user.id)},excludeCredentials:t.excludeCredentials.map(dn)}};r.signal=vt.createNewAbortSignal();let n;try{n=await navigator.credentials.create(r)}catch(f){throw Hs({error:f,options:r})}finally{vt.reset()}if(!n)throw new Error("Registration was not completed");const{id:i,rawId:s,response:o,type:a}=n,u={id:i,rawId:fe(s),response:{attestationObject:fe(o.attestationObject),clientDataJSON:fe(o.clientDataJSON)},type:a,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:n.authenticatorAttachment};return typeof o.getTransports=="function"&&(u.transports=o.getTransports()),u}function Ws(t){return new TextDecoder("utf-8").decode(t)}async function Gs(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function Js({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 B("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new B("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new B("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(hn(i)){if(n.rpId!==i)return new B(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new B(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new B("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function Ys(t,e=!1){var r,n;if(!fn())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(dn));const s={...t,challenge:ar(t.challenge),allowCredentials:i},o={};if(e){if(!await Gs())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');o.mediation="conditional",s.allowCredentials=[]}o.publicKey=s,o.signal=vt.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(l){throw Js({error:l,options:o})}finally{vt.reset()}if(!a)throw new Error("Authentication was not completed");const{id:u,rawId:f,response:c,type:p}=a;let d;return c.userHandle&&(d=Ws(c.userHandle)),{id:u,rawId:fe(f),response:{authenticatorData:fe(c.authenticatorData),clientDataJSON:fe(c.clientDataJSON),signature:fe(c.signature),userHandle:d},type:p,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:a.authenticatorAttachment}}const mt="nhostRefreshToken",yt="nhostRefreshTokenExpiresAt",Qs=3,Xs=300,Zs=5,vn=0,mn=1,ae=10,gt=20;class Et 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:mn,message:e.message}):(this.name=e.error,this.error=e)}}const ue={status:ae,error:"invalid-email",message:"Email is incorrectly formatted"},ur={status:ae,error:"invalid-password",message:"Password is incorrectly formatted"},yn={status:ae,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},eo={status:ae,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},to={status:ae,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},ro={status:ae,error:"no-refresh-token",message:"No refresh token has been provided"},no={status:gt,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},te={status:gt,error:"already-signed-in",message:"User is already signed in"},io={status:gt,error:"unauthenticated-user",message:"User is not authenticated"},so={status:gt,error:"unverified-user",message:"Email needs verification"},oo={status:ae,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},ao={status:mn,error:"invalid-sign-in-method",message:"Invalid sign-in method"},Ie=t=>{const e=ht.create({baseURL:t});return e.interceptors.response.use(r=>r,r=>{var n,i,s,o,a,u,f,c,p,d,l;return Promise.reject({error:{message:(a=(o=(s=(i=(n=r.response)==null?void 0:n.data)==null?void 0:i.message)!=null?s:r.message)!=null?o:r.request.responseText)!=null?a:JSON.stringify(r),status:(p=(c=(u=r.response)==null?void 0:u.status)!=null?c:(f=r.response)==null?void 0:f.data.statusCode)!=null?p:vn,error:((l=(d=r.response)==null?void 0:d.data)==null?void 0:l.error)||r.request.statusText||"network"}})}),e},wt=typeof window!="undefined",St=new Map,uo=t=>{var e;return wt&&typeof localStorage!="undefined"?localStorage.getItem(t):(e=St.get(t))!=null?e:null},co=(t,e)=>{wt&&typeof localStorage!="undefined"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?St.set(t,e):St.has(t)&&St.delete(t)},lo=(t,e)=>{if(t==="localStorage"||t==="web")return uo;if(t==="cookie")return r=>{var n;return wt&&(n=or.get(r))!=null?n: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}`)},fo=(t,e)=>{if(t==="localStorage"||t==="web")return co;if(t==="cookie")return(r,n)=>{wt&&(n?or.set(r,n,{expires:30}):or.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,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,s;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(s=e.remove)==null?void 0:s.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.deleteItemAsync)==null?void 0:s.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,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},gn=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const s=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(s)}`}).join("&");return r?`${t}?${r}`:t},Z=(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),s=Object.fromEntries(new URLSearchParams(i.search)),o=new URL(r.startsWith("/")?i.origin+r:r),a=new URLSearchParams(o.search);let u=Object.fromEntries(a);r.startsWith("/")&&(u={...s,...u});let f=i.pathname;return o.pathname.length>1&&(f+=o.pathname.slice(1)),{...n,redirectTo:gn(o.origin+f,u)}};function Tt(t,e){var r;if(!e){if(typeof window=="undefined")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 En(t){var e;if(typeof window=="undefined")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 s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const ce=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,}))$/),cr=t=>!!t&&typeof t=="string"&&t.length>=Qs,wn=t=>!!t&&typeof t=="string",ho=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),lr={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}},po=({backendUrl:t,clientUrl:e,interpreter:r})=>{const n=Ie(t);return Fe({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:L({error:i=>ue}),saveRequestError:L({error:(i,{data:{error:s}})=>s}),reportError:W(i=>({type:"ERROR",error:i.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(i,{email:s})=>!ce(s)},services:{requestChange:async(i,{email:s,options:o})=>(await n.post("/user/email/change",{newEmail:s,options:Z(e,o)},{headers:{authorization:`Bearer ${r==null?void 0:r.state.context.accessToken.value}`}})).data}})},vo=({backendUrl:t,interpreter:e})=>{const r=Ie(t);return Fe({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:L({error:n=>ur}),saveRequestError:L({error:(n,{data:{error:i}})=>i}),reportError:W(n=>({type:"ERROR",error:n.error})),reportSuccess:W("SUCCESS")},guards:{invalidPassword:(n,{password:i})=>!cr(i)},services:{requestChange:(n,{password:i,ticket:s})=>r.post("/user/password",{newPassword:i,ticket:s},{headers:{authorization:`Bearer ${e==null?void 0:e.state.context.accessToken.value}`}})}})},mo=({backendUrl:t,clientUrl:e})=>{const r=Ie(t);return Fe({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:L({error:n=>ue}),saveRequestError:L({error:(n,{data:{error:i}})=>i}),reportError:W(n=>({type:"ERROR",error:n.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!ce(i)},services:{requestChange:(n,{email:i,options:s})=>r.post("/user/password/reset",{email:i,options:Z(e,s)})}})},yo=({backendUrl:t,clientUrl:e})=>{const r=Ie(t);return Fe({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:L({error:n=>ue}),saveRequestError:L({error:(n,{data:{error:i}})=>i}),reportError:W(n=>({type:"ERROR",error:n.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!ce(i)},services:{request:async(n,{email:i,options:s})=>(await r.post("/user/email/send-verification-email",{email:i,options:Z(e,s)})).data}})},go=({backendUrl:t,clientUrl:e,clientStorageGetter:r,clientStorageSetter:n,clientStorageType:i="web",clientStorage:s,refreshIntervalTime:o,autoRefreshToken:a=!0,autoSignIn:u=!0})=>{const f=r||lo(i,s),c=n||fo(i,s),p=Ie(t),d=async(l,h,v)=>(await p.post(l,h,v)).data;return Fe({schema:{context:{},events:{},services:{}},tsTypes:{},context:lr,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:L({importTokenAttempts:({importTokenAttempts:l})=>l+1}),clearContext:L(()=>(c(yt,null),c(mt,null),{...lr})),clearContextExceptRefreshToken:L(({refreshToken:{value:l}})=>(c(yt,null),{...lr,refreshToken:{value:l}})),saveSession:L({user:(l,{data:h})=>{var v;return((v=h==null?void 0:h.session)==null?void 0:v.user)||null},accessToken:(l,{data:h})=>{if(h.session){const{accessTokenExpiresIn:v,accessToken:m}=h.session,E=new Date(Date.now()+v*1e3);return c(yt,E.toISOString()),{value:m,expiresAt:E}}return c(yt,null),{value:null,expiresAt:null}},refreshToken:(l,{data:h})=>{var v;const m=((v=h.session)==null?void 0:v.refreshToken)||null;return m&&c(mt,m),{value:m}}}),saveMfaTicket:L({mfa:(l,h)=>{var v;return(v=h.data)==null?void 0:v.mfa}}),resetTimer:L({refreshTimer:l=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:L({refreshTimer:(l,h)=>({startedAt:l.refreshTimer.startedAt,attempts:l.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:L({errors:({errors:l},{data:{error:h}})=>({...l,authentication:h})}),resetErrors:L({errors:l=>({}),importTokenAttempts:l=>0}),saveRegistrationError:L({errors:({errors:l},{data:{error:h}})=>({...l,registration:h})}),destroyRefreshToken:L({refreshToken:l=>(c(mt,null),{value:null})}),cleanUrl:()=>{u&&Tt("refreshToken")&&(En("refreshToken"),En("type"))},broadcastToken:l=>{if(u)try{new BroadcastChannel("nhost").postMessage(l.refreshToken.value)}catch{}}},guards:{isAnonymous:(l,h)=>{var v;return!!((v=l.user)!=null&&v.isAnonymous)},isSignedIn:l=>!!l.user&&!!l.refreshToken.value&&!!l.accessToken.value,noToken:l=>!l.refreshToken.value,hasRefreshToken:l=>!!l.refreshToken.value,isAutoRefreshDisabled:()=>!a,refreshTimerShouldRefresh:l=>{const{expiresAt:h}=l.accessToken;return h?l.refreshTimer.lastAttempt?Date.now()-l.refreshTimer.lastAttempt.getTime()>Zs*1e3:o&&Date.now()-l.refreshTimer.startedAt.getTime()>o*1e3?!0:h.getTime()-Date.now()-1e3*Xs<=0:!1},shouldRetryImportToken:(l,h)=>h.data.error.status===vn||h.data.error.status>=500,unverified:(l,{data:{error:h}})=>h.status===401&&(h.message==="Email is not verified"||h.error==="unverified-user"),hasSession:(l,h)=>{var v;return!!((v=h.data)!=null&&v.session)},hasMfaTicket:(l,h)=>{var v;return!!((v=h.data)!=null&&v.mfa)}},services:{signInPassword:(l,{email:h,password:v})=>ce(h)?cr(v)?d("/signin/email-password",{email:h,password:v}):Promise.reject({error:ur}):Promise.reject({error:ue}),passwordlessSms:(l,{phoneNumber:h,options:v})=>{var m;return wn(h)?(m=l.user)!=null&&m.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),d("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:h,options:Z(e,v)},{headers:{authorization:`Bearer ${l.accessToken.value}`}})):d("/signin/passwordless/sms",{phoneNumber:h,options:Z(e,v)}):Promise.reject({error:yn})},passwordlessSmsOtp:(l,{phoneNumber:h,otp:v})=>wn(h)?d("/signin/passwordless/sms/otp",{phoneNumber:h,otp:v}):Promise.reject({error:yn}),passwordlessEmail:(l,{email:h,options:v})=>{var m;return ce(h)?(m=l.user)!=null&&m.isAnonymous?d("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:h,options:Z(e,v)},{headers:{authorization:`Bearer ${l.accessToken.value}`}}):d("/signin/passwordless/email",{email:h,options:Z(e,v)}):Promise.reject({error:ue})},signInAnonymous:l=>d("/signin/anonymous"),signInMfaTotp:(l,h)=>{var v;const m=h.ticket||((v=l.mfa)==null?void 0:v.ticket);return m?ho(m)?d("/signin/mfa/totp",{ticket:m,otp:h.otp}):Promise.reject({error:eo}):Promise.reject({error:to})},signInSecurityKeyEmail:async(l,{email:h})=>{if(!ce(h))throw new Et(ue);const v=await d("/signin/webauthn",{email:h});let m;try{m=await Ys(v)}catch(E){throw new Et(E)}return d("/signin/webauthn/verify",{email:h,credential:m})},refreshToken:async(l,h)=>{const v=h.type==="TRY_TOKEN"?h.token:l.refreshToken.value;return{session:await d("/token",{refreshToken:v}),error:null}},signout:(l,h)=>d("/signout",{refreshToken:l.refreshToken.value,all:!!h.all}),signUpEmailPassword:async(l,{email:h,password:v,options:m})=>{var E;return ce(h)?cr(v)?(E=l.user)!=null&&E.isAnonymous?d("/user/deanonymize",{signInMethod:"email-password",email:h,password:v,options:Z(e,m)},{headers:{authorization:`Bearer ${l.accessToken.value}`}}):d("/signup/email-password",{email:h,password:v,options:Z(e,m)}):Promise.reject({error:ur}):Promise.reject({error:ue})},signUpSecurityKey:async(l,{email:h,options:v})=>{if(!ce(h))return Promise.reject({error:ue});const m=v==null?void 0:v.nickname;m&&delete v.nickname;const E=await d("/signup/webauthn",{email:h,options:v});let g;try{g=await pn(E)}catch(w){throw new Et(w)}return d("/signup/webauthn/verify",{credential:g,options:{redirectTo:v==null?void 0:v.redirectTo,nickname:m}})},importRefreshToken:async()=>{let l=null;if(u){const v=Tt("refreshToken")||null;if(v)try{return{session:await d("/token",{refreshToken:v}),error:null}}catch(m){l=m.error}else{const m=Tt("error");if(m)return Promise.reject({session:null,error:{status:ae,error:m,message:Tt("errorDescription")||m}})}}const h=await f(mt);if(h)try{return{session:await d("/token",{refreshToken:h}),error:null}}catch(v){l=v.error}return l?Promise.reject({error:l,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:l})=>l<5?1e3:5e3}})};class Eo{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,devTools:a,...u}){if(this._subscriptions=new Set,this.backendUrl=s,this.clientUrl=o,this.machine=go({...u,backendUrl:s,clientUrl:o,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&(this.interpreter=we(this.machine,{devTools:a}),this.interpreter.start()),typeof window!="undefined"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",f=>{var c;const p=(c=this.interpreter)==null?void 0:c.state.context.refreshToken.value;this.interpreter&&f.data!==p&&this.interpreter.send("TRY_TOKEN",{token:f.data})})}catch{}}get interpreter(){return this._interpreter}set interpreter(e){this._interpreter=e,e&&this._subscriptions.forEach(r=>r(this))}onStart(e){this.interpreter?e(this):this._subscriptions.add(e)}}const wo=async({backendUrl:t,interpreter:e},r)=>{const n=Ie(t);try{const{data:i}=await n.post("/user/webauthn/add",{},{headers:{authorization:`Bearer ${e==null?void 0:e.state.context.accessToken.value}`}});let s;try{s=await pn(i)}catch(a){throw new Et(a)}const{data:o}=await n.post("/user/webauthn/verify",{credential:s,nickname:r},{headers:{authorization:`Bearer ${e==null?void 0:e.state.context.accessToken.value}`}});return{key:o,isError:!1,error:null,isSuccess:!0}}catch(i){const{error:s}=i;return{isError:!0,error:s,isSuccess:!1}}},So=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})})}),To=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})})}),bo=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})})}),Ao=(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})})}),xo=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:te,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})})}),Oo=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:s.accessToken.value,error:te,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:o.context.mfa,user:null}):o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.context.user})})}),Sn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:te,isError:!0,isSuccess:!1});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({error:s.context.errors.registration||null,isError:!0,isSuccess:!1}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),Ro=(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:te,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:"signedIn"})&&r({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})}),_o=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:s.accessToken.value,error:te,isError:!0,isSuccess:!1,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:o.context.user})})}),Tn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:te,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(s=>{s.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):s.matches("registration.incomplete.failed")&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Io=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:te,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),ko=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:io});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})})}),bn=(t,e,r,n)=>new Promise(i=>{const{changed:s,context:o}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!s)return i({error:te,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(a=>{a.matches("registration.incomplete.failed")?i({accessToken:null,error:a.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):a.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):a.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:a.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:a.context.user})})}),No=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:te,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({accessToken:null,error:o.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),Po=()=>typeof window!="undefined",bt=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},de=({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};class Co{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,autoLogin:i,clientStorage:s,clientStorageType:o,clientStorageGetter:a,clientStorageSetter:u,refreshIntervalTime:f,start:c=!0}){var p;this.url=e,this._client=new Eo({backendUrl:e,clientUrl:typeof window!="undefined"&&((p=window.location)==null?void 0:p.origin)||"",autoRefreshToken:r,autoSignIn:typeof i=="boolean"?i:n,start:c,clientStorage:s,clientStorageType:o,clientStorageGetter:a,clientStorageSetter:u,refreshIntervalTime:f})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?de(await No(r,n,i)):de(await bn(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await xo(r);return{...de(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=gn(`${this._client.backendUrl}/signin/provider/${n}`,Z(this._client.clientUrl,i));return Po()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await Oo(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:so}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...de(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await Ro(r,e.email);return{...de(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:s}=await Sn(r,n,i);return{session:null,mfa:null,error:s}}if("phoneNumber"in e&&"otp"in e){const n=await Io(r,e.phoneNumber,e.otp);return{...de(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await Tn(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await _o(r,e.otp,e.ticket);return{...de(n),mfa:null}}return{error:ao,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await ko(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=we(mo(this._client)).start(),{error:i}=await bo(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=we(vo(this._client)).start(),{error:i}=await To(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=we(yo(this._client)).start(),{error:i}=await Ao(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=we(po(this._client)).start(),{error:i}=await So(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 Sn(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await Tn(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await bn(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await wo(this._client,e);return{error:r,key:n}}onTokenChanged(e){const r=n=>n.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(bt(s))});if(this._client.interpreter){const n=r(this._client.interpreter);return()=>n.stop()}else return this._client.onStart(n=>{r(n.interpreter)}),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}onAuthStateChanged(e){const r=n=>n.onTransition(({event:i,context:s})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,bt(s))});if(this._client.interpreter){const n=r(this._client.interpreter);return()=>n.stop()}else return this._client.onStart(n=>{r(n.interpreter)}),()=>{console.log("onAuthStateChanged was added before the interpreter started. Cannot unsubscribe listener.")}}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.state.matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).state.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}}getJWTToken(){return this.getAccessToken()}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.state.context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?kn(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.state.context.refreshToken.value;if(!i)return n({session:null,error:ro});const{changed:s}=r.send("TRY_TOKEN",{token:i});if(!s)return n({session:null,error:no});r.onTransition(o=>{o.matches({token:{idle:"error"}})?n({session:null,error:oo}):o.event.type==="TOKEN_CHANGED"&&n({session:bt(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return bt((r=(e=this._client.interpreter)==null?void 0:e.state)==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.state)==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const r=this._client.interpreter;if(!r)throw Error("Auth interpreter not set");return r.state.hasTag("loading")?new Promise((n,i)=>{let s=setTimeout(()=>i(`The state machine is not yet ready after ${15} seconds.`),15e3);r.onTransition(o=>{if(!o.hasTag("loading"))return clearTimeout(s),n(r)})}):Promise.resolve(r)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.state)!=null&&r.hasTag("loading"))}get client(){return this._client}}var Do=typeof self=="object"?self.FormData:window.FormData;class Uo{constructor({url:e}){this.url=e,this.httpClient=ht.create({baseURL:this.url})}async upload(e){const{formData:r}=e;try{return{fileMetadata:(await this.httpClient.post("/files",r,{headers:{...this.generateUploadHeaders(e),...this.generateAuthHeaders(),"Content-Type":"multipart/form-data"}})).data,error:null}}catch(n){return{fileMetadata:null,error:n}}}async getPresignedUrl(e){try{const{fileId:r}=e;return{presignedUrl:(await this.httpClient.get(`/files/${r}/presignedurl`,{headers:{...this.generateAuthHeaders()}})).data,error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e;return await this.httpClient.delete(`/files/${r}`,{headers:{...this.generateAuthHeaders()}}),{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateUploadHeaders(e){const{bucketId:r,name:n,id:i}=e,s={};return r&&(s["x-nhost-bucket-id"]=r),i&&(s["x-nhost-file-id"]=i),n&&(s["x-nhost-file-name"]=n),s}generateAuthHeaders(){return!this.adminSecret&&!this.accessToken?null:this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}class Lo{constructor({url:e,adminSecret:r}){this.url=e,this.api=new Uo({url:e}),this.setAdminSecret(r)}async upload(e){let r;"file"in e?(r=new Do,r.append("file",e.file)):r=e.formData;const{fileMetadata:n,error:i}=await this.api.upload({...e,formData:r});return i?{fileMetadata:null,error:i}:n?{fileMetadata:n,error:null}:{fileMetadata:null,error:new Error("Invalid file returned")}}getUrl(e){return this.getPublicUrl(e)}getPublicUrl(e){const{fileId:r}=e;return`${this.url}/files/${r}`}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}}class An{constructor(e){const{url:r,adminSecret:n}=e;this.accessToken=null,this.adminSecret=n,this.instance=ht.create({baseURL:r})}async call(e,r,n){const i={...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};let s;try{s=await this.instance.post(e,r,{...n,headers:i})}catch(o){if(o instanceof Error)return{res:null,error:o}}return s?{res:s,error:null}:{res:null,error:new Error("Unable to make post request to funtion")}}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}`}:{}}}class xn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n,this.instance=ht.create({baseURL:r})}async request(e,r,n){const i={...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};try{const s="",a=(await this.instance.post("",{operationName:s||void 0,query:typeof e=="string"?e:Ce.print(e),variables:r},{...n,headers:i})).data,{data:u}=a;return a.errors?{data:null,error:a.errors}:typeof u!="object"||Array.isArray(u)||u===null?{data:null,error:new Error("incorrect response data from GraphQL server")}:{data:u,error:null}}catch(s){return s instanceof Error?{data:null,error:s}:(console.error(s),{data:null,error:new Error("Unable to get do GraphQL request")})}}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}`}:{}}}const $o=/^localhost(:\d+)*$/g;function At(t,e){const{backendUrl:r,subdomain:n,region:i}=t;if(!r&&!n)throw new Error("Either `backendUrl` or `subdomain` must be set.");if(r)return`${r}/v1/${e}`;if(!n)throw new Error("`subdomain` must be set if `backendUrl` is not set.");const s=n.match($o);if(s&&s.length>0){const o=s[0];return o==="localhost"?`http://localhost:1337/v1/${e}`:`http://${o}/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`}class On{constructor({refreshIntervalTime:e,clientStorageGetter:r,clientStorageSetter:n,clientStorage:i,clientStorageType:s,autoRefreshToken:o,autoSignIn:a,adminSecret:u,devTools:f,start:c=!0,...p}){var d;this.auth=new Co({url:At(p,"auth"),refreshIntervalTime:e,clientStorageGetter:r,clientStorageSetter:n,clientStorage:i,clientStorageType:s,autoRefreshToken:o,autoSignIn:a,start:c}),this.storage=new Lo({url:At(p,"storage"),adminSecret:u}),this.functions=new An({url:At(p,"functions"),adminSecret:u}),this.graphql=new xn({url:At(p,"graphql"),adminSecret:u}),this.storage.setAccessToken(this.auth.getAccessToken()),this.functions.setAccessToken(this.auth.getAccessToken()),this.graphql.setAccessToken(this.auth.getAccessToken()),(d=this.auth.client)==null||d.onStart(()=>{this.auth.onAuthStateChanged((l,h)=>{l==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(l=>{this.storage.setAccessToken(l==null?void 0:l.accessToken),this.functions.setAccessToken(l==null?void 0:l.accessToken),this.graphql.setAccessToken(l==null?void 0:l.accessToken)})}),this._adminSecret=u,this.devTools=f}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}const jo=t=>new On(t);Q.NhostClient=On,Q.NhostFunctionsClient=An,Q.NhostGraphqlClient=xn,Q.createClient=jo,Object.defineProperties(Q,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
14
+ ***************************************************************************** */var w=function(){return w=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},w.apply(this,arguments)};function Rt(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 b(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 x(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function D(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}var C;(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"})(C||(C={}));var ce;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(ce||(ce={}));var Nt=C.Start,It=C.Stop,Ee=C.Raise,Se=C.Send,cr=C.Cancel,_n=C.NullEvent,Pt=C.Assign;C.After,C.DoneState;var ur=C.Log,jn=C.Init,Ct=C.Invoke;C.ErrorExecution;var lr=C.ErrorPlatform,Ln=C.ErrorCustom,fr=C.Update,Mn=C.Choose,Fn=C.Pure,dr=".",hr={},Ut="xstate.guard",$n="",M=process.env.NODE_ENV==="production",Xe;function Dt(t,e,r){r===void 0&&(r=dr);var n=Le(t,r),i=Le(e,r);return O(i)?O(n)?i===n:!1:O(n)?n in i:Object.keys(n).every(function(s){return s in i?Dt(n[s],i[s]):!1})}function pr(t){try{return O(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 qn(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function Le(t,e){if(qn(t))return t.value;if(Te(t))return Ze(t);if(typeof t!="string")return t;var r=_t(t,e);return Ze(r)}function Ze(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 Me(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var s=n[i];r[s]=e(t[s],s,t,i)}return r}function vr(t,e,r){var n,i,s={};try{for(var o=b(Object.keys(t)),a=o.next();!a.done;a=o.next()){var u=a.value,c=t[u];!r(c)||(s[u]=e(c,u,t))}}catch(d){n={error:d}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}var Bn=function(t){return function(e){var r,n,i=e;try{for(var s=b(t),o=s.next();!o.done;o=s.next()){var a=o.value;i=i[a]}}catch(u){r={error:u}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}};function zn(t,e){return function(r){var n,i,s=r;try{for(var o=b(t),a=o.next();!a.done;a=o.next()){var u=a.value;s=s[e][u]}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}}function et(t){if(!t)return[[]];if(O(t))return[[t]];var e=L(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:et(t[r]).map(function(i){return[r].concat(i)})}));return e}function L(t){var e;return(e=[]).concat.apply(e,D([],x(t),!1))}function mr(t){return Te(t)?t:[t]}function Q(t){return t===void 0?[]:mr(t)}function tt(t,e,r){var n,i;if(U(t))return t(e,r.data);var s={};try{for(var o=b(Object.keys(t)),a=o.next();!a.done;a=o.next()){var u=a.value,c=t[u];U(c)?s[u]=c(e,r.data):s[u]=c}}catch(d){n={error:d}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}function Vn(t){return/^(done|error)\./.test(t)}function yr(t){return!!(t instanceof Promise||t!==null&&(U(t)||typeof t=="object")&&U(t.then))}function Kn(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function Hn(t,e){var r,n,i=x([[],[]],2),s=i[0],o=i[1];try{for(var a=b(t),u=a.next();!u.done;u=a.next()){var c=u.value;e(c)?s.push(c):o.push(c)}}catch(d){r={error:d}}finally{try{u&&!u.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return[s,o]}function gr(t,e){return Me(t.states,function(r,n){if(!!r){var i=(O(e)?void 0:e[n])||(r?r.current:void 0);if(!!i)return{current:i,states:gr(r,i)}}})}function Jn(t,e){return{current:e,states:gr(t,e)}}function wr(t,e,r,n){M||B(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(s,o){var a,u,c=o.assignment,d={state:n,action:o,_event:e},v={};if(U(c))v=c(s,e.data,d);else try{for(var h=b(Object.keys(c)),l=h.next();!l.done;l=h.next()){var f=l.value,p=c[f];v[f]=U(p)?p(s,e.data,d):p}}catch(y){a={error:y}}finally{try{l&&!l.done&&(u=h.return)&&u.call(h)}finally{if(a)throw a.error}}return Object.assign({},s,v)},t);return i}var B=function(){};M||(B=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 U(t){return typeof t=="function"}function O(t){return typeof t=="string"}function Er(t,e){if(!!t)return O(t)?{type:Ut,name:t,predicate:e?e[t]:void 0}:U(t)?{type:Ut,name:t.name,predicate:t}:t}function Gn(t){try{return"subscribe"in t&&U(t.subscribe)}catch{return!1}}var ue=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();Xe={},Xe[ue]=function(){return this},Xe[Symbol.observable]=function(){return this};function ve(t){return!!t&&"__xstatenode"in t}function Wn(t){return!!t&&typeof t.send=="function"}function jt(t,e){return O(t)||typeof t=="number"?w({type:t},e):t}function z(t,e){if(!O(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=jt(t);return w({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function be(t,e){var r=mr(e).map(function(n){return typeof n>"u"||typeof n=="string"||ve(n)?{target:n,event:t}:w(w({},n),{event:t})});return r}function Yn(t){if(!(t===void 0||t===$n))return Q(t)}function Qn(t,e,r){if(!M){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 Sr(t,e,r,n,i){var s=t.options.guards,o={state:i,cond:e,_event:n};if(e.type===Ut)return((s==null?void 0:s[e.name])||e.predicate)(r,n.data,o);var a=s==null?void 0:s[e.type];if(!a)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return a(r,n.data,o)}function Tr(t){return typeof t=="string"?{type:t}:t}function rt(t,e,r){var n=function(){},i=typeof t=="object",s=i?t:null;return{next:((i?t.next:t)||n).bind(s),error:((i?t.error:e)||n).bind(s),complete:((i?t.complete:r)||n).bind(s)}}function nt(t,e){return"".concat(t,":invocation[").concat(e,"]")}var xe=z({type:jn});function Lt(t,e){return e&&e[t]||void 0}function Fe(t,e){var r;if(O(t)||typeof t=="number"){var n=Lt(t,e);U(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(U(t))r={type:t.name||t.toString(),exec:t};else{var n=Lt(t.type,e);if(U(n))r=w(w({},t),{exec:n});else if(n){var i=n.type||t.type;r=w(w(w({},n),t),{type:i})}else r=t}return r}var le=function(t,e){if(!t)return[];var r=Te(t)?t:[t];return r.map(function(n){return Fe(n,e)})};function Mt(t){var e=Fe(t);return w(w({id:O(t)?t:e.id},e),{type:e.type})}function Xn(t){return O(t)?{type:Ee,event:t}:Ft(t,{to:ce.Internal})}function Zn(t){return{type:Ee,_event:z(t.event)}}function Ft(t,e){return{to:e?e.to:void 0,type:Se,event:U(t)?t:jt(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:U(t)?t.name:pr(t)}}function ei(t,e,r,n){var i={_event:r},s=z(U(t.event)?t.event(e,r.data,i):t.event),o;if(O(t.delay)){var a=n&&n[t.delay];o=U(a)?a(e,r.data,i):a}else o=U(t.delay)?t.delay(e,r.data,i):t.delay;var u=U(t.to)?t.to(e,r.data,i):t.to;return w(w({},t),{to:u,_event:s,event:s.data,delay:o})}var ti=function(t,e,r){return w(w({},t),{value:O(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},ri=function(t){return{type:cr,sendId:t}};function ni(t){var e=Mt(t);return{type:C.Start,activity:e,exec:void 0}}function ii(t){var e=U(t)?t:Mt(t);return{type:C.Stop,activity:e,exec:void 0}}function si(t,e,r){var n=U(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,s={type:C.Stop,activity:i};return s}var oi=function(t){return{type:Pt,assignment:t}};function ai(t,e){var r=e?"#".concat(e):"";return"".concat(C.After,"(").concat(t,")").concat(r)}function it(t,e){var r="".concat(C.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function st(t,e){var r="".concat(C.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function $e(t,e){var r="".concat(C.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}var ci=function(t){var e,r,n=[];try{for(var i=b(t),s=i.next();!s.done;s=i.next())for(var o=s.value,a=0;a<o.length;){if(o[a].type===Pt){n.push(o[a]),o.splice(a,1);continue}a++}}catch(u){e={error:u}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function ot(t,e,r,n,i,s,o){o===void 0&&(o=!1);var a=o?[]:ci(i),u=a.length?wr(r,n,a,e):r,c=o?[r]:void 0,d=[];function v(f){var p;switch(f.type){case Ee:return Zn(f);case Se:var y=ei(f,u,n,t.options.delays);return M||B(!O(f.delay)||typeof y.delay=="number","No delay reference for delay expression '".concat(f.delay,"' was found on machine '").concat(t.id,"'")),s&&y.to!==ce.Internal&&d.push(y),y;case ur:{var E=ti(f,u,n);return s==null||s(E,u,n),E}case Mn:{var g=f,S=(p=g.conds.find(function(Z){var ae=Er(Z.cond,t.options.guards);return!ae||Sr(t,ae,u,n,s?void 0:e)}))===null||p===void 0?void 0:p.actions;if(!S)return[];var N=x(ot(t,e,u,n,[le(Q(S),t.options.actions)],s,o),2),A=N[0],j=N[1];return u=j,c==null||c.push(u),A}case Fn:{var S=f.get(u,n.data);if(!S)return[];var k=x(ot(t,e,u,n,[le(Q(S),t.options.actions)],s,o),2),I=k[0],P=k[1];return u=P,c==null||c.push(u),I}case It:{var E=si(f,u,n);return s==null||s(E,r,n),E}case Pt:{u=wr(u,n,[f],s?void 0:e),c==null||c.push(u);break}default:var T=Fe(f,t.options.actions),_=T.exec;if(s)s(T,u,n);else if(_&&c){var G=c.length-1;T=w(w({},T),{exec:function(Z){for(var ae=[],De=1;De<arguments.length;De++)ae[De-1]=arguments[De];_.apply(void 0,D([c[G]],x(ae),!1))}})}return T}}function h(f){var p,y,E=[];try{for(var g=b(f),S=g.next();!S.done;S=g.next()){var N=S.value,A=v(N);A&&(E=E.concat(A))}}catch(j){p={error:j}}finally{try{S&&!S.done&&(y=g.return)&&y.call(g)}finally{if(p)throw p.error}}return d.forEach(function(j){s(j,u,n)}),d.length=0,E}var l=L(i.map(h));return[l,u]}var Ae=function(t,e){var r=e(t);return r};function br(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[ue]=function(){return this},e}function ui(t,e,r,n){var i,s=Tr(t.src),o=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[s.type],a=t.data?tt(t.data,r,n):void 0,u=o?xr(o,t.id,a):br(t.id);return u.meta=t,u}function xr(t,e,r){var n=br(e);if(n.deferred=!0,ve(t)){var i=n.state=Ae(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function li(t){try{return typeof t.send=="function"}catch{return!1}}function fi(t){return li(t)&&"id"in t}function di(t){var e;return w((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[ue]=function(){return this},e),t)}var at=function(t){return t.type==="atomic"||t.type==="final"};function Ar(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function qe(t){return Ar(t).filter(function(e){return e.type!=="history"})}function kr(t){var e=[t];return at(t)?e:e.concat(L(qe(t).map(kr)))}function Be(t,e){var r,n,i,s,o,a,u,c,d=new Set(t),v=$t(d),h=new Set(e);try{for(var l=b(h),f=l.next();!f.done;f=l.next())for(var p=f.value,y=p.parent;y&&!h.has(y);)h.add(y),y=y.parent}catch(P){r={error:P}}finally{try{f&&!f.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}var E=$t(h);try{for(var g=b(h),S=g.next();!S.done;S=g.next()){var p=S.value;if(p.type==="compound"&&(!E.get(p)||!E.get(p).length))v.get(p)?v.get(p).forEach(function(T){return h.add(T)}):p.initialStateNodes.forEach(function(T){return h.add(T)});else if(p.type==="parallel")try{for(var N=(o=void 0,b(qe(p))),A=N.next();!A.done;A=N.next()){var j=A.value;h.has(j)||(h.add(j),v.get(j)?v.get(j).forEach(function(T){return h.add(T)}):j.initialStateNodes.forEach(function(T){return h.add(T)}))}}catch(T){o={error:T}}finally{try{A&&!A.done&&(a=N.return)&&a.call(N)}finally{if(o)throw o.error}}}}catch(P){i={error:P}}finally{try{S&&!S.done&&(s=g.return)&&s.call(g)}finally{if(i)throw i.error}}try{for(var k=b(h),I=k.next();!I.done;I=k.next())for(var p=I.value,y=p.parent;y&&!h.has(y);)h.add(y),y=y.parent}catch(P){u={error:P}}finally{try{I&&!I.done&&(c=k.return)&&c.call(k)}finally{if(u)throw u.error}}return h}function Or(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(at(n))return n.key}else return{}}var i={};return r.forEach(function(s){i[s.key]=Or(s,e)}),i}function $t(t){var e,r,n=new Map;try{for(var i=b(t),s=i.next();!s.done;s=i.next()){var o=s.value;n.has(o)||n.set(o,[]),o.parent&&(n.has(o.parent)||n.set(o.parent,[]),n.get(o.parent).push(o))}}catch(a){e={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function hi(t,e){var r=Be([t],e);return Or(t,$t(r))}function ze(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function pi(t){return D([],x(new Set(L(D([],x(t.map(function(e){return e.ownEvents})),!1)))),!1)}function ct(t,e){return e.type==="compound"?qe(e).some(function(r){return r.type==="final"&&ze(t,r)}):e.type==="parallel"?qe(e).every(function(r){return ct(t,r)}):!1}function vi(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Rr(t){return new Set(L(t.map(function(e){return e.tags})))}function Nr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(O(t)||O(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Nr(t[i],e[i])})}function mi(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function yi(t,e){var r=t.exec,n=w(w({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var te=function(){function t(e){var r=this,n;this.actions=[],this.activities=hr,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||hr,this.meta=vi(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 pi(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=xe;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=xe;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="."),O(e))return[e];var i=Object.keys(e);return i.concat.apply(i,D([],x(i.map(function(s){return n.toStrings(e[s],r).map(function(o){return s+r+o})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=Rt(e,["configuration","transitions","tags","machine"]);return w(w({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Dt(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;M&&B(!!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}(),gi={deferEvents:!1},Ir=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=w(w({},gi),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}(),qt=new Map,wi=0,ut={bookId:function(){return"x:".concat(wi++)},register:function(t,e){return qt.set(t,e),t},get:function(t){return qt.get(t)},free:function(t){qt.delete(t)}};function Bt(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;M||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 Ei(){var t=Bt();if(t&&"__xstate__"in t)return t.__xstate__}function Si(t){if(!!Bt()){var e=Ei();e&&e.register(t)}}function Ti(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],s=!1,o=function(){if(!s){for(s=!0;i.length>0;){var c=i.shift();r=t.transition(r,c,u),n.forEach(function(d){return d.next(r)})}s=!1}},a=di({id:e.id,send:function(c){i.push(c),o()},getSnapshot:function(){return r},subscribe:function(c,d,v){var h=rt(c,d,v);return n.add(h),h.next(r),{unsubscribe:function(){n.delete(h)}}}}),u={parent:e.parent,self:a,id:e.id||"anonymous",observers:n};return r=t.start?t.start(u):r,a}var bi={sync:!1,autoForward:!1},q;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(q||(q={}));var xi=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=q.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(d,v){if(Te(d))return n.batch(d),n.state;var h=z(jt(d,v));if(n.status===q.Stopped)return M||B(!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
+ Event: `).concat(JSON.stringify(h.data))),n.state;if(n.status!==q.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 l=n._nextState(h);n.update(l,h)}),n._state},this.sendTo=function(d,v,h){var l=n.parent&&(v===ce.Parent||n.parent.id===v),f=l?n.parent:O(v)?n.children.get(v)||ut.get(v):Wn(v)?v:void 0;if(!f){if(!l)throw new Error("Unable to send event to child '".concat(v,"' from service '").concat(n.id,"'."));M||B(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(d.type));return}if("machine"in f){if(n.status!==q.Stopped||n.parent!==f||n.state.done){var p=w(w({},d),{name:d.name===Ln?"".concat($e(n.id)):d.name,origin:n.sessionId});!h&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([f,p]):f.send(p)}}else!h&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([f,d.data]):f.send(d.data)},this._exec=function(d,v,h,l){l===void 0&&(l=n.machine.options.actions);var f=d.exec||Lt(d.type,l),p=U(f)?f:f?f.exec:d.exec;if(p)try{return p(v,h.data,n.machine.config.predictableActionArguments?{action:d,_event:h}:{action:d,state:n.state,_event:h})}catch(G){throw n.parent&&n.parent.send({type:"xstate.error",data:G}),G}switch(d.type){case Se:var y=d;if(typeof y.delay=="number"){n.defer(y);return}else y.to?n.sendTo(y._event,y.to,h===xe):n.send(y._event);break;case cr:n.cancel(d.sendId);break;case Nt:{if(n.status!==q.Running)return;var E=d.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[E.id||E.type])break;if(E.type===C.Invoke){var g=Tr(E.src),S=n.machine.options.services?n.machine.options.services[g.type]:void 0,N=E.id,A=E.data;M||B(!("forward"in E),"`forward` property is deprecated (found in invocation of '".concat(E.src,"' in in machine '").concat(n.machine.id,"'). ")+"Please use `autoForward` instead.");var j="autoForward"in E?E.autoForward:!!E.forward;if(!S){M||B(!1,"No service found for invocation '".concat(E.src,"' in machine '").concat(n.machine.id,"'."));return}var k=A?tt(A,v,h):void 0;if(typeof S=="string")return;var I=U(S)?S(v,h.data,{data:k,src:g,meta:E.meta}):S;if(!I)return;var P=void 0;ve(I)&&(I=k?I.withContext(k):I,P={autoForward:j}),n.spawn(I,N,P)}else n.spawnActivity(E);break}case It:{n.stopChild(d.activity.id);break}case ur:var T=d.label,_=d.value;T?n.logger(T,_):n.logger(_);break;default:M||B(!1,"No implementation found for action type '".concat(d.type,"'"));break}};var i=w(w({},t.defaultOptions),r),s=i.clock,o=i.logger,a=i.parent,u=i.id,c=u!==void 0?u:e.id;this.id=c,this.logger=o,this.clock=s,this.parent=a,this.options=i,this.scheduler=new Ir({deferEvents:this.options.deferEvents}),this.sessionId=ut.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:Ae(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return M||B(this.status!==q.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 s=b(e.actions),o=s.next();!o.done;o=s.next()){var a=o.value;this.exec(a,e,r)}}catch(u){n={error:u}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,s,o,a,u,c,d,v=this;if(e._sessionid=this.sessionId,this._state=e,(!this.machine.config.predictableActionArguments||r===xe)&&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(P){v.state.children[P.id]=P}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var l=b(this.eventListeners),f=l.next();!f.done;f=l.next()){var p=f.value;p(e.event)}}catch(P){n={error:P}}finally{try{f&&!f.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}try{for(var y=b(this.listeners),E=y.next();!E.done;E=y.next()){var p=E.value;p(e,e.event)}}catch(P){s={error:P}}finally{try{E&&!E.done&&(o=y.return)&&o.call(y)}finally{if(s)throw s.error}}try{for(var g=b(this.contextListeners),S=g.next();!S.done;S=g.next()){var N=S.value;N(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(P){a={error:P}}finally{try{S&&!S.done&&(u=g.return)&&u.call(g)}finally{if(a)throw a.error}}if(this.state.done){var A=e.configuration.find(function(P){return P.type==="final"&&P.parent===v.machine}),j=A&&A.doneData?tt(A.doneData,e.context,r):void 0;try{for(var k=b(this.doneListeners),I=k.next();!I.done;I=k.next()){var p=I.value;p(st(this.id,j))}}catch(P){c={error:P}}finally{try{I&&!I.done&&(d=k.return)&&d.call(k)}finally{if(c)throw c.error}}this._stop(),this._stopChildren()}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===q.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this,s=rt(e,r,n);this.listeners.add(s.next),this.status!==q.NotStarted&&s.next(this.state);var o=function(){i.doneListeners.delete(o),i.stopListeners.delete(o),s.complete()};return this.status===q.Stopped?s.complete():(this.onDone(o),this.onStop(o)),{unsubscribe:function(){i.listeners.delete(s.next),i.doneListeners.delete(o),i.stopListeners.delete(o)}}},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===q.Running)return this;this.machine._init(),ut.register(this.sessionId,this),this.initialized=!0,this.status=q.Running;var n=e===void 0?this.initialState:Ae(this,function(){return mi(e)?r.machine.resolveState(e):r.machine.resolveState(te.from(e,r.machine.context))});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(function(){r.update(n,xe)}),this},t.prototype._stopChildren=function(){this.children.forEach(function(e){U(e.stop)&&e.stop()}),this.children.clear()},t.prototype._stop=function(){var e,r,n,i,s,o,a,u,c,d;try{for(var v=b(this.listeners),h=v.next();!h.done;h=v.next()){var l=h.value;this.listeners.delete(l)}}catch(k){e={error:k}}finally{try{h&&!h.done&&(r=v.return)&&r.call(v)}finally{if(e)throw e.error}}try{for(var f=b(this.stopListeners),p=f.next();!p.done;p=f.next()){var l=p.value;l(),this.stopListeners.delete(l)}}catch(k){n={error:k}}finally{try{p&&!p.done&&(i=f.return)&&i.call(f)}finally{if(n)throw n.error}}try{for(var y=b(this.contextListeners),E=y.next();!E.done;E=y.next()){var l=E.value;this.contextListeners.delete(l)}}catch(k){s={error:k}}finally{try{E&&!E.done&&(o=y.return)&&o.call(y)}finally{if(s)throw s.error}}try{for(var g=b(this.doneListeners),S=g.next();!S.done;S=g.next()){var l=S.value;this.doneListeners.delete(l)}}catch(k){a={error:k}}finally{try{S&&!S.done&&(u=g.return)&&u.call(g)}finally{if(a)throw a.error}}if(!this.initialized)return this;this.initialized=!1,this.status=q.Stopped,this._initialState=void 0;try{for(var N=b(Object.keys(this.delayedEventsMap)),A=N.next();!A.done;A=N.next()){var j=A.value;this.clock.clearTimeout(this.delayedEventsMap[j])}}catch(k){c={error:k}}finally{try{A&&!A.done&&(d=N.return)&&d.call(N)}finally{if(c)throw c.error}}this.scheduler.clear(),this.scheduler=new Ir({deferEvents:this.options.deferEvents})},t.prototype.stop=function(){var e=this,r=this.scheduler;return this._stop(),r.schedule(function(){var n=z({type:"xstate.stop"}),i=Ae(e,function(){var s=L(D([],x(e.state.configuration),!1).sort(function(d,v){return v.order-d.order}).map(function(d){return le(d.onExit,e.machine.options.actions)})),o=x(ot(e.machine,e.state,e.state.context,n,[s],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),a=o[0],u=o[1],c=new te({value:e.state.value,context:u,_event:n,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:a.filter(function(d){return d.type!==Ee&&(d.type!==Se||!!d.to&&d.to!==ce.Internal)}),activities:{},events:[],configuration:[],transitions:[],children:{},done:e.state.done,tags:e.state.tags,machine:e.machine});return c.changed=!0,c});e.update(i,n),e._stopChildren(),ut.free(e.sessionId)}),this},t.prototype.batch=function(e){var r=this;if(this.status===q.NotStarted&&this.options.deferEvents)M||B(!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!==q.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,s,o=r.state,a=!1,u=[],c=function(l){var f=z(l);r.forward(f),o=Ae(r,function(){return r.machine.transition(o,f,void 0,n||void 0)}),u.push.apply(u,D([],x(r.machine.config.predictableActionArguments?o.actions:o.actions.map(function(p){return yi(p,o)})),!1)),a=a||!!o.changed};try{for(var d=b(e),v=d.next();!v.done;v=d.next()){var h=v.value;c(h)}}catch(l){i={error:l}}finally{try{v&&!v.done&&(s=d.return)&&s.call(d)}finally{if(i)throw i.error}}o.changed=a,o.actions=u,r.update(o,z(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=z(e);if(i.name.indexOf(lr)===0&&!this.state.nextEvents.some(function(o){return o.indexOf(lr)===0}))throw i.data.data;var s=Ae(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return s},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=b(this.forwardTo),s=i.next();!s.done;s=i.next()){var o=s.value,a=this.children.get(o);if(!a)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(o,"'."));a.send(e)}}catch(u){r={error:u}}finally{try{s&&!s.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),U(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==q.Running)return xr(e,r);if(yr(e))return this.spawnPromise(Promise.resolve(e),r);if(U(e))return this.spawnCallback(e,r);if(fi(e))return this.spawnActor(e,r);if(Gn(e))return this.spawnObservable(e,r);if(ve(e))return this.spawnMachine(e,w(w({},n),{id:r}));if(Kn(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,w(w({},this.options),{parent:this,id:r.id||e.id})),s=w(w({},bi),r);s.sync&&i.onTransition(function(a){n.send(fr,{state:a,id:i.id})});var o=i;return this.children.set(i.id,o),s.autoForward&&this.forwardTo.add(i.id),i.onDone(function(a){n.removeChild(i.id),n.send(z(a,{origin:i.id}))}).start(),o},t.prototype.spawnBehavior=function(e,r){var n=Ti(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,s=!1,o;e.then(function(u){s||(o=u,i.removeChild(r),i.send(z(st(r,u),{origin:r})))},function(u){if(!s){i.removeChild(r);var c=$e(r,u);try{i.send(z(c,{origin:r}))}catch(d){Qn(u,d,r),i.devTools&&i.devTools.send(c,i.state),i.machine.strict&&i.stop()}}});var a=(n={id:r,send:function(){},subscribe:function(u,c,d){var v=rt(u,c,d),h=!1;return e.then(function(l){h||(v.next(l),!h&&v.complete())},function(l){h||v.error(l)}),{unsubscribe:function(){return h=!0}}},stop:function(){s=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return o}},n[ue]=function(){return this},n);return this.children.set(r,a),a},t.prototype.spawnCallback=function(e,r){var n,i=this,s=!1,o=new Set,a=new Set,u,c=function(h){u=h,a.forEach(function(l){return l(h)}),!s&&i.send(z(h,{origin:r}))},d;try{d=e(c,function(h){o.add(h)})}catch(h){this.send($e(r,h))}if(yr(d))return this.spawnPromise(d,r);var v=(n={id:r,send:function(h){return o.forEach(function(l){return l(h)})},subscribe:function(h){var l=rt(h);return a.add(l.next),{unsubscribe:function(){a.delete(l.next)}}},stop:function(){s=!0,U(d)&&d()},toJSON:function(){return{id:r}},getSnapshot:function(){return u}},n[ue]=function(){return this},n);return this.children.set(r,v),v},t.prototype.spawnObservable=function(e,r){var n,i=this,s,o=e.subscribe(function(u){s=u,i.send(z(u,{origin:r}))},function(u){i.removeChild(r),i.send(z($e(r,u),{origin:r}))},function(){i.removeChild(r),i.send(z(st(r),{origin:r}))}),a=(n={id:r,send:function(){},subscribe:function(u,c,d){return e.subscribe(u,c,d)},stop:function(){return o.unsubscribe()},getSnapshot:function(){return s},toJSON:function(){return{id:r}}},n[ue]=function(){return this},n);return this.children.set(r,a),a},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){M||B(!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[ue]=function(){return this},n))},t.prototype.attachDev=function(){var e=Bt();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(w(w({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:w({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Si(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[ue]=function(){return this},t.prototype.getSnapshot=function(){return this.status===q.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=ke,t}();function ke(t,e){var r=new xi(t,e);return r}function Ai(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function lt(t){return w(w({type:Ct},t),{toJSON:function(){t.onDone,t.onError;var e=Rt(t,["onDone","onError"]);return w(w({},e),{type:Ct,src:Ai(t.src)})}})}var Oe="",zt="#",Ve="*",Re={},Ne=function(t){return t[0]===zt},ki=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},Oi=function(t,e,r){var n=r.slice(0,-1).some(function(s){return!("cond"in s)&&!("in"in s)&&(O(s.target)||ve(s.target))}),i=e===Oe?"the transient event":"event '".concat(e,"'");B(!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.")},Ri=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var s=this,o;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(ki(),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:dr),this.id=this.config.id||D([this.machine.key],x(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:(o=this.config.schema)!==null&&o!==void 0?o:{},this.description=this.config.description,M||B(!("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?Me(this.config.states,function(c,d){var v,h=new t(c,{},void 0,{parent:s,key:d});return Object.assign(s.idMap,w((v={},v[h.id]=h,v),h.idMap)),h}):Re;var a=0;function u(c){var d,v;c.order=a++;try{for(var h=b(Ar(c)),l=h.next();!l.done;l=h.next()){var f=l.value;u(f)}}catch(p){d={error:p}}finally{try{l&&!l.done&&(v=h.return)&&v.call(h)}finally{if(d)throw d.error}}}u(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(c){var d=c.event;return d===Oe}):Oe in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=Q(this.config.entry||this.config.onEntry).map(function(c){return Fe(c)}),this.onExit=Q(this.config.exit||this.config.onExit).map(function(c){return Fe(c)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=Q(this.config.invoke).map(function(c,d){var v,h;if(ve(c)){var l=nt(s.id,d);return s.machine.options.services=w((v={},v[l]=c,v),s.machine.options.services),lt({src:l,id:l})}else if(O(c.src)){var l=c.id||nt(s.id,d);return lt(w(w({},c),{id:l,src:c.src}))}else if(ve(c.src)||U(c.src)){var l=c.id||nt(s.id,d);return s.machine.options.services=w((h={},h[l]=c.src,h),s.machine.options.services),lt(w(w({id:l},c),{src:l}))}else{var f=c.src;return lt(w(w({id:nt(s.id,d)},c),{src:f}))}}),this.activities=Q(this.config.activities).concat(this.invoke).map(function(c){return Mt(c)}),this.transition=this.transition.bind(this),this.tags=Q(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||kr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,s=n.activities,o=n.guards,a=n.services,u=n.delays;return new t(this.config,{actions:w(w({},i),e.actions),activities:w(w({},s),e.activities),guards:w(w({},o),e.guards),services:w(w({},a),e.services),delays:w(w({},u),e.delays)},r!=null?r:this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return U(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:Me(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===Oe,n=this.transitions.filter(function(i){var s=i.eventType===e;return r?s:s||i.eventType===Ve});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(s,o){var a=U(s)?"".concat(e.id,":delay[").concat(o,"]"):s,u=ai(a,e.id);return e.onEntry.push(Ft(u,{delay:s})),e.onExit.push(ri(u)),u},i=Te(r)?r.map(function(s,o){var a=n(s.delay,o);return w(w({},s),{event:a})}):L(Object.keys(r).map(function(s,o){var a=r[s],u=O(a)?{target:a}:a,c=isNaN(+s)?s:+s,d=n(c,o);return Q(u).map(function(v){return w(w({},v),{event:d,delay:c})})}));return i.map(function(s){var o=s.delay;return w(w({},e.formatTransition(s)),{delay:o})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof te?e.value:Le(e,this.delimiter);if(O(i)){var s=this.getStateNode(i).initial;return s!==void 0?this.getStateNodes((r={},r[i]=s,r)):[this,this.states[i]]}var o=Object.keys(i),a=[this];return a.push.apply(a,D([],x(L(o.map(function(u){return n.getStateNode(u).getStateNodes(i[u])}))),!1)),a},t.prototype.handles=function(e){var r=pr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof te?e:te.create(e),n=Array.from(Be([],this.getStateNodes(r.value)));return new te(w(w({},r),{value:this.resolve(r.value),configuration:n,done:ct(n,this),tags:Rr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),s=i.next(r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),s=this.getStateNode(i[0]),o=s._transition(e[i[0]],r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionParallelNode=function(e,r,n){var i,s,o={};try{for(var a=b(Object.keys(e)),u=a.next();!u.done;u=a.next()){var c=u.value,d=e[c];if(!!d){var v=this.getStateNode(c),h=v._transition(d,r,n);h&&(o[c]=h)}}}catch(g){i={error:g}}finally{try{u&&!u.done&&(s=a.return)&&s.call(a)}finally{if(i)throw i.error}}var l=Object.keys(o).map(function(g){return o[g]}),f=L(l.map(function(g){return g.transitions})),p=l.some(function(g){return g.transitions.length>0});if(!p)return this.next(r,n);var y=L(l.map(function(g){return g.entrySet})),E=L(Object.keys(o).map(function(g){return o[g].configuration}));return{transitions:f,entrySet:y,exitSet:L(l.map(function(g){return g.exitSet})),configuration:E,source:r,actions:L(Object.keys(o).map(function(g){return o[g].actions}))}},t.prototype._transition=function(e,r,n){return O(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,z(r))},t.prototype.next=function(e,r){var n,i,s=this,o=r.name,a=[],u=[],c;try{for(var d=b(this.getCandidates(o)),v=d.next();!v.done;v=d.next()){var h=v.value,l=h.cond,f=h.in,p=e.context,y=f?O(f)&&Ne(f)?e.matches(Le(this.getStateNodeById(f).path,this.delimiter)):Dt(Le(f,this.delimiter),Bn(this.path.slice(0,-2))(e.value)):!0,E=!1;try{E=!l||Sr(this.machine,l,p,r,e)}catch(A){throw new Error("Unable to evaluate guard '".concat(l.name||l.type,"' in transition for event '").concat(o,"' in state node '").concat(this.id,`':
18
+ `).concat(A.message))}if(E&&y){h.target!==void 0&&(u=h.target),a.push.apply(a,D([],x(h.actions),!1)),c=h;break}}}catch(A){n={error:A}}finally{try{v&&!v.done&&(i=d.return)&&i.call(d)}finally{if(n)throw n.error}}if(!!c){if(!u.length)return{transitions:[c],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:a};var g=L(u.map(function(A){return s.getRelativeStateNodes(A,e.historyValue)})),S=!!c.internal,N=[];return S||u.forEach(function(A){N.push.apply(N,D([],x(s.getExternalReentryNodes(A)),!1))}),{transitions:[c],entrySet:N,exitSet:S?[]:[this],configuration:g,source:e,actions:a}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=x(e.order>this.order?[e,this]:[this,e],2),i=n[0],s=n[1];i&&i!==s;)r.push(i),i=i.parent;return i!==s?[]:(r.push(s),r)},t.prototype.getActions=function(e,r,n,i,s,o,a){var u,c,d,v,h=this,l=Be([],o?this.getStateNodes(o.value):[this]);try{for(var f=b(e),p=f.next();!p.done;p=f.next()){var y=p.value;(!ze(l,y)||ze(n.entrySet,y.parent))&&n.entrySet.push(y)}}catch(T){u={error:T}}finally{try{p&&!p.done&&(c=f.return)&&c.call(f)}finally{if(u)throw u.error}}try{for(var E=b(l),g=E.next();!g.done;g=E.next()){var y=g.value;(!ze(e,y)||ze(n.exitSet,y.parent))&&n.exitSet.push(y)}}catch(T){d={error:T}}finally{try{g&&!g.done&&(v=E.return)&&v.call(E)}finally{if(d)throw d.error}}var S=L(n.entrySet.map(function(T){var _=[];if(T.type!=="final")return _;var G=T.parent;if(!G.parent)return _;_.push(it(T.id,T.doneData),it(G.id,T.doneData?tt(T.doneData,i,s):void 0));var Z=G.parent;return Z.type==="parallel"&&qe(Z).every(function(ae){return ct(n.configuration,ae)})&&_.push(it(Z.id)),_}));n.exitSet.sort(function(T,_){return _.order-T.order}),n.entrySet.sort(function(T,_){return T.order-_.order});var N=new Set(n.entrySet),A=new Set(n.exitSet),j=Array.from(N).map(function(T){var _=T.onEntry,G=T.activities.map(function(Z){return ni(Z)});return le(a?D(D([],x(_),!1),x(G),!1):D(D([],x(G),!1),x(_),!1),h.machine.options.actions)}).concat([S.map(Xn)]),k=Array.from(A).map(function(T){return le(D(D([],x(T.onExit),!1),x(T.activities.map(function(_){return ii(_)})),!1),h.machine.options.actions)}),I=k.concat([le(n.actions,this.machine.options.actions)]).concat(j);if(r){var P=le(L(D([],x(e),!1).sort(function(T,_){return _.order-T.order}).map(function(T){return T.onExit})),this.machine.options.actions).filter(function(T){return T.type!==Ee&&(T.type!==Se||!!T.to&&T.to!==ce.Internal)});return I.concat([P])}return I},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var s=z(r),o;if(e instanceof te)o=n===void 0?e:this.resolveState(te.from(e,n));else{var a=O(e)?this.resolve(Ze(this.getResolvedPath(e))):this.resolve(e),u=n!=null?n:this.machine.context;o=this.resolveState(te.from(a,u))}if(!M&&s.name===Ve)throw new Error("An event cannot have the wildcard type ('".concat(Ve,"')"));if(this.strict&&!this.events.includes(s.name)&&!Vn(s.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(s.name,"'"));var c=this._transition(o.value,o,s)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:o,actions:[]},d=Be([],this.getStateNodes(o.value)),v=c.configuration.length?Be(d,c.configuration):d;return c.configuration=D([],x(v),!1),this.resolveTransition(c,o,o.context,i,s)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var s,o=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(s=e.actions).unshift.apply(s,D([],x(o),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,s){var o,a,u,c,d=this;s===void 0&&(s=xe);var v=e.configuration,h=!r||e.transitions.length>0,l=h?e.configuration:r?r.configuration:[],f=ct(l,this),p=h?hi(this.machine,v):void 0,y=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,E=this.getActions(new Set(l),f,e,n,s,r,i),g=r?w({},r.activities):{};try{for(var S=b(E),N=S.next();!N.done;N=S.next()){var A=N.value;try{for(var j=(u=void 0,b(A)),k=j.next();!k.done;k=j.next()){var I=k.value;I.type===Nt?g[I.activity.id||I.activity.type]=I:I.type===It&&(g[I.activity.id||I.activity.type]=!1)}}catch(H){u={error:H}}finally{try{k&&!k.done&&(c=j.return)&&c.call(j)}finally{if(u)throw u.error}}}}catch(H){o={error:H}}finally{try{N&&!N.done&&(a=S.return)&&a.call(S)}finally{if(o)throw o.error}}var P=x(ot(this,r,n,s,E,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),T=P[0],_=P[1],G=x(Hn(T,function(H){return H.type===Ee||H.type===Se&&H.to===ce.Internal}),2),Z=G[0],ae=G[1],De=T.filter(function(H){var je;return H.type===Nt&&((je=H.activity)===null||je===void 0?void 0:je.type)===Ct}),Po=De.reduce(function(H,je){return H[je.activity.id]=ui(je.activity,d.machine,_,s),H},r?w({},r.children):{}),Ot=new te({value:p||r.value,context:_,_event:s,_sessionid:r?r._sessionid:null,historyValue:p?y?Jn(y,p):void 0:r?r.historyValue:void 0,history:!p||e.source?r:void 0,actions:p?ae:[],activities:p?g:r?r.activities:{},events:[],configuration:l,transitions:e.transitions,children:Po,done:f,tags:Rr(l),machine:this}),Pn=n!==_;Ot.changed=s.name===fr||Pn;var _e=Ot.history;_e&&delete _e.history;var Cn=!f&&(this._transient||v.some(function(H){return H._transient}));if(!h&&(!Cn||s.name===Oe))return Ot;var ee=Ot;if(!f)for(Cn&&(ee=this.resolveRaisedTransition(ee,{type:_n},s,i));Z.length;){var Co=Z.shift();ee=this.resolveRaisedTransition(ee,Co._event,s,i)}var Uo=ee.changed||(_e?!!ee.actions.length||Pn||typeof _e.value!=typeof ee.value||!Nr(ee.value,_e.value):void 0);return ee.changed=Uo,ee.history=_e,ee},t.prototype.getStateNode=function(e){if(Ne(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=Ne(e)?e.slice(zt.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"&&Ne(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 Me(this.initialStateValue,function(s,o){return s?n.getStateNode(o).resolve(e[o]||s):Re});case"compound":if(O(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?Me(e,function(s,o){return s?n.getStateNode(o).resolve(s):Re}):this.initialStateValue||{};default:return e||Re}},t.prototype.getResolvedPath=function(e){if(Ne(e)){var r=this.machine.idMap[e.slice(zt.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=vr(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=at(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:D([],x(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r!=null?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;O(r.target)?e=Ne(r.target)?Ze(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(at(this))return[this];if(this.type==="compound"&&!this.initial)return M||B(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=et(this.initialStateValue);return L(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=x(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 s=this.getStateNode(n);if(s.type==="history")return s.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:vr(this.states,function(r,n){if(!e)return r.historyValue();var i=O(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?L(et(i).map(function(o){return n.getFromRelativePath(o)})):n.initialStateNodes}var s=zn(n.path,"states")(e).current;return O(s)?[n.getStateNode(s)]:L(et(s).map(function(o){return r.history==="deep"?n.getFromRelativePath(o):[n.states[o[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=L(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 s=this.states,o=new Set(this.ownEvents);if(s)try{for(var a=b(Object.keys(s)),u=a.next();!u.done;u=a.next()){var c=u.value,d=s[c];if(d.states)try{for(var v=(n=void 0,b(d.events)),h=v.next();!h.done;h=v.next()){var l=h.value;o.add("".concat(l))}}catch(f){n={error:f}}finally{try{h&&!h.done&&(i=v.return)&&i.call(v)}finally{if(n)throw n.error}}}}catch(f){e={error:f}}finally{try{u&&!u.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(o)},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(!O(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var s=i?r.key+n:n;if(r.parent)try{var o=r.parent.getStateNodeByPath(s);return o}catch(a){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
19
+ `).concat(a.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=Yn(e.target),i="internal"in e?e.internal:n?n.some(function(u){return O(u)&&u[0]===r.delimiter}):!0,s=this.machine.options.guards,o=this.resolveTarget(n),a=w(w({},e),{actions:le(Q(e.actions)),cond:Er(e.cond,s),target:o,source:this,internal:i,eventType:e.event,toJSON:function(){return w(w({},a),{target:a.target?a.target.map(function(u){return"#".concat(u.id)}):void 0,source:"#".concat(r.id)})}});return a},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 s=this.config.on,o=Ve,a=s[o],u=a===void 0?[]:a,c=Rt(s,[typeof o=="symbol"?o:o+""]);i=L(Object.keys(c).map(function(g){!M&&g===Oe&&B(!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 S=be(g,c[g]);return M||Oi(n,g,S),S}).concat(be(Ve,u)))}var d=this.config.always?be("",this.config.always):[],v=this.config.onDone?be(String(it(this.id)),this.config.onDone):[];M||B(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var h=L(this.invoke.map(function(g){var S=[];return g.onDone&&S.push.apply(S,D([],x(be(String(st(g.id)),g.onDone)),!1)),g.onError&&S.push.apply(S,D([],x(be(String($e(g.id)),g.onError)),!1)),S})),l=this.after,f=L(D(D(D(D([],x(v),!1),x(h),!1),x(i),!1),x(d),!1).map(function(g){return Q(g).map(function(S){return n.formatTransition(S)})}));try{for(var p=b(l),y=p.next();!y.done;y=p.next()){var E=y.value;f.push(E)}}catch(g){e={error:g}}finally{try{y&&!y.done&&(r=p.return)&&r.call(p)}finally{if(e)throw e.error}}return f},t}(),Pr=!1;function Ke(t,e){return!M&&!t.predictableActionArguments&&!Pr&&(Pr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new Ri(t,e)}var $=oi,X=Ft;function Cr(t,e){return function(){return t.apply(e,arguments)}}const{toString:Ur}=Object.prototype,{getPrototypeOf:Vt}=Object,Kt=(t=>e=>{const r=Ur.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),ie=t=>(t=t.toLowerCase(),e=>Kt(e)===t),ft=t=>e=>typeof e===t,{isArray:He}=Array,Ht=ft("undefined");function Ni(t){return t!==null&&!Ht(t)&&t.constructor!==null&&!Ht(t.constructor)&&Ie(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const Dr=ie("ArrayBuffer");function Ii(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Dr(t.buffer),e}const Pi=ft("string"),Ie=ft("function"),_r=ft("number"),jr=t=>t!==null&&typeof t=="object",Ci=t=>t===!0||t===!1,dt=t=>{if(Kt(t)!=="object")return!1;const e=Vt(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Ui=ie("Date"),Di=ie("File"),_i=ie("Blob"),ji=ie("FileList"),Li=t=>jr(t)&&Ie(t.pipe),Mi=t=>{const e="[object FormData]";return t&&(typeof FormData=="function"&&t instanceof FormData||Ur.call(t)===e||Ie(t.toString)&&t.toString()===e)},Fi=ie("URLSearchParams"),$i=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ht(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),He(t))for(n=0,i=t.length;n<i;n++)e.call(null,t[n],n,t);else{const s=r?Object.getOwnPropertyNames(t):Object.keys(t),o=s.length;let a;for(n=0;n<o;n++)a=s[n],e.call(null,t[a],a,t)}}function Jt(){const t={},e=(r,n)=>{dt(t[n])&&dt(r)?t[n]=Jt(t[n],r):dt(r)?t[n]=Jt({},r):He(r)?t[n]=r.slice():t[n]=r};for(let r=0,n=arguments.length;r<n;r++)arguments[r]&&ht(arguments[r],e);return t}const qi=(t,e,r,{allOwnKeys:n}={})=>(ht(e,(i,s)=>{r&&Ie(i)?t[s]=Cr(i,r):t[s]=i},{allOwnKeys:n}),t),Bi=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),zi=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},Vi=(t,e,r,n)=>{let i,s,o;const a={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!a[o]&&(e[o]=t[o],a[o]=!0);t=r!==!1&&Vt(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},Ki=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;const n=t.indexOf(e,r);return n!==-1&&n===r},Hi=t=>{if(!t)return null;if(He(t))return t;let e=t.length;if(!_r(e))return null;const r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},Ji=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Vt(Uint8Array)),Gi=(t,e)=>{const n=(t&&t[Symbol.iterator]).call(t);let i;for(;(i=n.next())&&!i.done;){const s=i.value;e.call(t,s[0],s[1])}},Wi=(t,e)=>{let r;const n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},Yi=ie("HTMLFormElement"),Qi=t=>t.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),Lr=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),Xi=ie("RegExp"),Mr=(t,e)=>{const r=Object.getOwnPropertyDescriptors(t),n={};ht(r,(i,s)=>{e(i,s,t)!==!1&&(n[s]=i)}),Object.defineProperties(t,n)},m={isArray:He,isArrayBuffer:Dr,isBuffer:Ni,isFormData:Mi,isArrayBufferView:Ii,isString:Pi,isNumber:_r,isBoolean:Ci,isObject:jr,isPlainObject:dt,isUndefined:Ht,isDate:Ui,isFile:Di,isBlob:_i,isRegExp:Xi,isFunction:Ie,isStream:Li,isURLSearchParams:Fi,isTypedArray:Ji,isFileList:ji,forEach:ht,merge:Jt,extend:qi,trim:$i,stripBOM:Bi,inherits:zi,toFlatObject:Vi,kindOf:Kt,kindOfTest:ie,endsWith:Ki,toArray:Hi,forEachEntry:Gi,matchAll:Wi,isHTMLForm:Yi,hasOwnProperty:Lr,hasOwnProp:Lr,reduceDescriptors:Mr,freezeMethods:t=>{Mr(t,(e,r)=>{const n=t[r];if(!!Ie(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not read-only method '"+r+"'")})}})},toObjectSet:(t,e)=>{const r={},n=i=>{i.forEach(s=>{r[s]=!0})};return He(t)?n(t):n(String(t).split(e)),r},toCamelCase:Qi,noop:()=>{},toFiniteNumber:(t,e)=>(t=+t,Number.isFinite(t)?t:e)};function R(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}m.inherits(R,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const Fr=R.prototype,$r={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{$r[t]={value:t}}),Object.defineProperties(R,$r),Object.defineProperty(Fr,"isAxiosError",{value:!0}),R.from=(t,e,r,n,i,s)=>{const o=Object.create(Fr);return m.toFlatObject(t,o,function(u){return u!==Error.prototype},a=>a!=="isAxiosError"),R.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var qr=typeof self=="object"?self.FormData:window.FormData;function Gt(t){return m.isPlainObject(t)||m.isArray(t)}function Br(t){return m.endsWith(t,"[]")?t.slice(0,-2):t}function zr(t,e,r){return t?t.concat(e).map(function(i,s){return i=Br(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function Zi(t){return m.isArray(t)&&!t.some(Gt)}const es=m.toFlatObject(m,{},null,function(e){return/^is[A-Z]/.test(e)});function ts(t){return t&&m.isFunction(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator]}function pt(t,e,r){if(!m.isObject(t))throw new TypeError("target must be an object");e=e||new(qr||FormData),r=m.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(p,y){return!m.isUndefined(y[p])});const n=r.metaTokens,i=r.visitor||d,s=r.dots,o=r.indexes,u=(r.Blob||typeof Blob<"u"&&Blob)&&ts(e);if(!m.isFunction(i))throw new TypeError("visitor must be a function");function c(f){if(f===null)return"";if(m.isDate(f))return f.toISOString();if(!u&&m.isBlob(f))throw new R("Blob is not supported. Use a Buffer instead.");return m.isArrayBuffer(f)||m.isTypedArray(f)?u&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function d(f,p,y){let E=f;if(f&&!y&&typeof f=="object"){if(m.endsWith(p,"{}"))p=n?p:p.slice(0,-2),f=JSON.stringify(f);else if(m.isArray(f)&&Zi(f)||m.isFileList(f)||m.endsWith(p,"[]")&&(E=m.toArray(f)))return p=Br(p),E.forEach(function(S,N){!(m.isUndefined(S)||S===null)&&e.append(o===!0?zr([p],N,s):o===null?p:p+"[]",c(S))}),!1}return Gt(f)?!0:(e.append(zr(y,p,s),c(f)),!1)}const v=[],h=Object.assign(es,{defaultVisitor:d,convertValue:c,isVisitable:Gt});function l(f,p){if(!m.isUndefined(f)){if(v.indexOf(f)!==-1)throw Error("Circular reference detected in "+p.join("."));v.push(f),m.forEach(f,function(E,g){(!(m.isUndefined(E)||E===null)&&i.call(e,E,m.isString(g)?g.trim():g,p,h))===!0&&l(E,p?p.concat(g):[g])}),v.pop()}}if(!m.isObject(t))throw new TypeError("data must be an object");return l(t),e}function Vr(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function Wt(t,e){this._pairs=[],t&&pt(t,this,e)}const Kr=Wt.prototype;Kr.append=function(e,r){this._pairs.push([e,r])},Kr.toString=function(e){const r=e?function(n){return e.call(this,n,Vr)}:Vr;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function rs(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Hr(t,e,r){if(!e)return t;const n=r&&r.encode||rs,i=r&&r.serialize;let s;if(i?s=i(e,r):s=m.isURLSearchParams(e)?e.toString():new Wt(e,r).toString(n),s){const o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}class Jr{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){m.forEach(this.handlers,function(n){n!==null&&e(n)})}}const Gr={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ns=typeof URLSearchParams<"u"?URLSearchParams:Wt,is=FormData,ss=(()=>{let t;return typeof navigator<"u"&&((t=navigator.product)==="ReactNative"||t==="NativeScript"||t==="NS")?!1:typeof window<"u"&&typeof document<"u"})(),se={isBrowser:!0,classes:{URLSearchParams:ns,FormData:is,Blob},isStandardBrowserEnv:ss,protocols:["http","https","file","blob","url","data"]};function os(t,e){return pt(t,new se.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return se.isNode&&m.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function as(t){return m.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function cs(t){const e={},r=Object.keys(t);let n;const i=r.length;let s;for(n=0;n<i;n++)s=r[n],e[s]=t[s];return e}function Wr(t){function e(r,n,i,s){let o=r[s++];const a=Number.isFinite(+o),u=s>=r.length;return o=!o&&m.isArray(i)?i.length:o,u?(m.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!a):((!i[o]||!m.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&m.isArray(i[o])&&(i[o]=cs(i[o])),!a)}if(m.isFormData(t)&&m.isFunction(t.entries)){const r={};return m.forEachEntry(t,(n,i)=>{e(as(n),i,r,0)}),r}return null}function us(t,e,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new R("Request failed with status code "+r.status,[R.ERR_BAD_REQUEST,R.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}const ls=se.isStandardBrowserEnv?function(){return{write:function(r,n,i,s,o,a){const u=[];u.push(r+"="+encodeURIComponent(n)),m.isNumber(i)&&u.push("expires="+new Date(i).toGMTString()),m.isString(s)&&u.push("path="+s),m.isString(o)&&u.push("domain="+o),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(r){const n=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(r){this.write(r,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}();function fs(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function ds(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}function Yr(t,e){return t&&!fs(e)?ds(t,e):e}const hs=se.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");let n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){const a=m.isString(o)?i(o):o;return a.protocol===n.protocol&&a.host===n.host}}():function(){return function(){return!0}}();function Je(t,e,r){R.call(this,t==null?"canceled":t,R.ERR_CANCELED,e,r),this.name="CanceledError"}m.inherits(Je,R,{__CANCEL__:!0});function ps(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}const vs=m.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ms=t=>{const e={};let r,n,i;return t&&t.split(`
20
+ `).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||e[r]&&vs[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},Qr=Symbol("internals"),Xr=Symbol("defaults");function Ge(t){return t&&String(t).trim().toLowerCase()}function vt(t){return t===!1||t==null?t:m.isArray(t)?t.map(vt):String(t)}function ys(t){const e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}function Zr(t,e,r,n){if(m.isFunction(n))return n.call(this,e,r);if(!!m.isString(e)){if(m.isString(n))return e.indexOf(n)!==-1;if(m.isRegExp(n))return n.test(e)}}function gs(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function ws(t,e){const r=m.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(i,s,o){return this[n].call(this,e,i,s,o)},configurable:!0})})}function We(t,e){e=e.toLowerCase();const r=Object.keys(t);let n=r.length,i;for(;n-- >0;)if(i=r[n],e===i.toLowerCase())return i;return null}function Y(t,e){t&&this.set(t),this[Xr]=e||null}Object.assign(Y.prototype,{set:function(t,e,r){const n=this;function i(s,o,a){const u=Ge(o);if(!u)throw new Error("header name must be a non-empty string");const c=We(n,u);c&&a!==!0&&(n[c]===!1||a===!1)||(n[c||o]=vt(s))}return m.isPlainObject(t)?m.forEach(t,(s,o)=>{i(s,o,e)}):i(e,t,r),this},get:function(t,e){if(t=Ge(t),!t)return;const r=We(this,t);if(r){const n=this[r];if(!e)return n;if(e===!0)return ys(n);if(m.isFunction(e))return e.call(this,n,r);if(m.isRegExp(e))return e.exec(n);throw new TypeError("parser must be boolean|regexp|function")}},has:function(t,e){if(t=Ge(t),t){const r=We(this,t);return!!(r&&(!e||Zr(this,this[r],r,e)))}return!1},delete:function(t,e){const r=this;let n=!1;function i(s){if(s=Ge(s),s){const o=We(r,s);o&&(!e||Zr(r,r[o],o,e))&&(delete r[o],n=!0)}}return m.isArray(t)?t.forEach(i):i(t),n},clear:function(){return Object.keys(this).forEach(this.delete.bind(this))},normalize:function(t){const e=this,r={};return m.forEach(this,(n,i)=>{const s=We(r,i);if(s){e[s]=vt(n),delete e[i];return}const o=t?gs(i):String(i).trim();o!==i&&delete e[i],e[o]=vt(n),r[o]=!0}),this},toJSON:function(t){const e=Object.create(null);return m.forEach(Object.assign({},this[Xr]||null,this),(r,n)=>{r==null||r===!1||(e[n]=t&&m.isArray(r)?r.join(", "):r)}),e}}),Object.assign(Y,{from:function(t){return m.isString(t)?new this(ms(t)):t instanceof this?t:new this(t)},accessor:function(t){const r=(this[Qr]=this[Qr]={accessors:{}}).accessors,n=this.prototype;function i(s){const o=Ge(s);r[o]||(ws(n,s),r[o]=!0)}return m.isArray(t)?t.forEach(i):i(t),this}}),Y.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),m.freezeMethods(Y.prototype),m.freezeMethods(Y);function Es(t,e){t=t||10;const r=new Array(t),n=new Array(t);let i=0,s=0,o;return e=e!==void 0?e:1e3,function(u){const c=Date.now(),d=n[s];o||(o=c),r[i]=u,n[i]=c;let v=s,h=0;for(;v!==i;)h+=r[v++],v=v%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o<e)return;const l=d&&c-d;return l?Math.round(h*1e3/l):void 0}}function en(t,e){let r=0;const n=Es(50,250);return i=>{const s=i.loaded,o=i.lengthComputable?i.total:void 0,a=s-r,u=n(a),c=s<=o;r=s;const d={loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:u||void 0,estimated:u&&o&&c?(o-s)/u:void 0};d[e?"download":"upload"]=!0,t(d)}}function tn(t){return new Promise(function(r,n){let i=t.data;const s=Y.from(t.headers).normalize(),o=t.responseType;let a;function u(){t.cancelToken&&t.cancelToken.unsubscribe(a),t.signal&&t.signal.removeEventListener("abort",a)}m.isFormData(i)&&se.isStandardBrowserEnv&&s.setContentType(!1);let c=new XMLHttpRequest;if(t.auth){const l=t.auth.username||"",f=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(l+":"+f))}const d=Yr(t.baseURL,t.url);c.open(t.method.toUpperCase(),Hr(d,t.params,t.paramsSerializer),!0),c.timeout=t.timeout;function v(){if(!c)return;const l=Y.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),p={data:!o||o==="text"||o==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:l,config:t,request:c};us(function(E){r(E),u()},function(E){n(E),u()},p),c=null}if("onloadend"in c?c.onloadend=v:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(v)},c.onabort=function(){!c||(n(new R("Request aborted",R.ECONNABORTED,t,c)),c=null)},c.onerror=function(){n(new R("Network Error",R.ERR_NETWORK,t,c)),c=null},c.ontimeout=function(){let f=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded";const p=t.transitional||Gr;t.timeoutErrorMessage&&(f=t.timeoutErrorMessage),n(new R(f,p.clarifyTimeoutError?R.ETIMEDOUT:R.ECONNABORTED,t,c)),c=null},se.isStandardBrowserEnv){const l=(t.withCredentials||hs(d))&&t.xsrfCookieName&&ls.read(t.xsrfCookieName);l&&s.set(t.xsrfHeaderName,l)}i===void 0&&s.setContentType(null),"setRequestHeader"in c&&m.forEach(s.toJSON(),function(f,p){c.setRequestHeader(p,f)}),m.isUndefined(t.withCredentials)||(c.withCredentials=!!t.withCredentials),o&&o!=="json"&&(c.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&c.addEventListener("progress",en(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&c.upload&&c.upload.addEventListener("progress",en(t.onUploadProgress)),(t.cancelToken||t.signal)&&(a=l=>{!c||(n(!l||l.type?new Je(null,t,c):l),c.abort(),c=null)},t.cancelToken&&t.cancelToken.subscribe(a),t.signal&&(t.signal.aborted?a():t.signal.addEventListener("abort",a)));const h=ps(d);if(h&&se.protocols.indexOf(h)===-1){n(new R("Unsupported protocol "+h+":",R.ERR_BAD_REQUEST,t));return}c.send(i||null)})}const rn={http:tn,xhr:tn},nn={getAdapter:t=>{if(m.isString(t)){const e=rn[t];if(!t)throw Error(m.hasOwnProp(t)?`Adapter '${t}' is not available in the build`:`Can not resolve adapter '${t}'`);return e}if(!m.isFunction(t))throw new TypeError("adapter is not a function");return t},adapters:rn},Ss={"Content-Type":"application/x-www-form-urlencoded"};function Ts(){let t;return typeof XMLHttpRequest<"u"?t=nn.getAdapter("xhr"):typeof process<"u"&&m.kindOf(process)==="process"&&(t=nn.getAdapter("http")),t}function bs(t,e,r){if(m.isString(t))try{return(e||JSON.parse)(t),m.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}const Pe={transitional:Gr,adapter:Ts(),transformRequest:[function(e,r){const n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=m.isObject(e);if(s&&m.isHTMLForm(e)&&(e=new FormData(e)),m.isFormData(e))return i&&i?JSON.stringify(Wr(e)):e;if(m.isArrayBuffer(e)||m.isBuffer(e)||m.isStream(e)||m.isFile(e)||m.isBlob(e))return e;if(m.isArrayBufferView(e))return e.buffer;if(m.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return os(e,this.formSerializer).toString();if((a=m.isFileList(e))||n.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return pt(a?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),bs(e)):e}],transformResponse:[function(e){const r=this.transitional||Pe.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&m.isString(e)&&(n&&!this.responseType||i)){const o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(a){if(o)throw a.name==="SyntaxError"?R.from(a,R.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:se.classes.FormData,Blob:se.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};m.forEach(["delete","get","head"],function(e){Pe.headers[e]={}}),m.forEach(["post","put","patch"],function(e){Pe.headers[e]=m.merge(Ss)});function Yt(t,e){const r=this||Pe,n=e||r,i=Y.from(n.headers);let s=n.data;return m.forEach(t,function(a){s=a.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function sn(t){return!!(t&&t.__CANCEL__)}function Qt(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Je}function on(t){return Qt(t),t.headers=Y.from(t.headers),t.data=Yt.call(t,t.transformRequest),(t.adapter||Pe.adapter)(t).then(function(n){return Qt(t),n.data=Yt.call(t,t.transformResponse,n),n.headers=Y.from(n.headers),n},function(n){return sn(n)||(Qt(t),n&&n.response&&(n.response.data=Yt.call(t,t.transformResponse,n.response),n.response.headers=Y.from(n.response.headers))),Promise.reject(n)})}function Ye(t,e){e=e||{};const r={};function n(c,d){return m.isPlainObject(c)&&m.isPlainObject(d)?m.merge(c,d):m.isPlainObject(d)?m.merge({},d):m.isArray(d)?d.slice():d}function i(c){if(m.isUndefined(e[c])){if(!m.isUndefined(t[c]))return n(void 0,t[c])}else return n(t[c],e[c])}function s(c){if(!m.isUndefined(e[c]))return n(void 0,e[c])}function o(c){if(m.isUndefined(e[c])){if(!m.isUndefined(t[c]))return n(void 0,t[c])}else return n(void 0,e[c])}function a(c){if(c in e)return n(t[c],e[c]);if(c in t)return n(void 0,t[c])}const u={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a};return m.forEach(Object.keys(t).concat(Object.keys(e)),function(d){const v=u[d]||i,h=v(d);m.isUndefined(h)&&v!==a||(r[d]=h)}),r}const an="1.1.3",Xt={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Xt[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});const cn={};Xt.transitional=function(e,r,n){function i(s,o){return"[Axios v"+an+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,a)=>{if(e===!1)throw new R(i(o," has been removed"+(r?" in "+r:"")),R.ERR_DEPRECATED);return r&&!cn[o]&&(cn[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,a):!0}};function xs(t,e,r){if(typeof t!="object")throw new R("options must be an object",R.ERR_BAD_OPTION_VALUE);const n=Object.keys(t);let i=n.length;for(;i-- >0;){const s=n[i],o=e[s];if(o){const a=t[s],u=a===void 0||o(a,s,t);if(u!==!0)throw new R("option "+s+" must be "+u,R.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new R("Unknown option "+s,R.ERR_BAD_OPTION)}}const Zt={assertOptions:xs,validators:Xt},fe=Zt.validators;class me{constructor(e){this.defaults=e,this.interceptors={request:new Jr,response:new Jr}}request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Ye(this.defaults,r);const{transitional:n,paramsSerializer:i}=r;n!==void 0&&Zt.assertOptions(n,{silentJSONParsing:fe.transitional(fe.boolean),forcedJSONParsing:fe.transitional(fe.boolean),clarifyTimeoutError:fe.transitional(fe.boolean)},!1),i!==void 0&&Zt.assertOptions(i,{encode:fe.function,serialize:fe.function},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();const s=r.headers&&m.merge(r.headers.common,r.headers[r.method]);s&&m.forEach(["delete","get","head","post","put","patch","common"],function(f){delete r.headers[f]}),r.headers=new Y(r.headers,s);const o=[];let a=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(r)===!1||(a=a&&f.synchronous,o.unshift(f.fulfilled,f.rejected))});const u=[];this.interceptors.response.forEach(function(f){u.push(f.fulfilled,f.rejected)});let c,d=0,v;if(!a){const l=[on.bind(this),void 0];for(l.unshift.apply(l,o),l.push.apply(l,u),v=l.length,c=Promise.resolve(r);d<v;)c=c.then(l[d++],l[d++]);return c}v=o.length;let h=r;for(d=0;d<v;){const l=o[d++],f=o[d++];try{h=l(h)}catch(p){f.call(this,p);break}}try{c=on.call(this,h)}catch(l){return Promise.reject(l)}for(d=0,v=u.length;d<v;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=Ye(this.defaults,e);const r=Yr(e.baseURL,e.url);return Hr(r,e.params,e.paramsSerializer)}}m.forEach(["delete","get","head","options"],function(e){me.prototype[e]=function(r,n){return this.request(Ye(n||{},{method:e,url:r,data:(n||{}).data}))}}),m.forEach(["post","put","patch"],function(e){function r(n){return function(s,o,a){return this.request(Ye(a||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}me.prototype[e]=r(),me.prototype[e+"Form"]=r(!0)});class er{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(s){r=s});const n=this;this.promise.then(i=>{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s;const o=new Promise(a=>{n.subscribe(a),s=a}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,a){n.reason||(n.reason=new Je(s,o,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new er(function(i){e=i}),cancel:e}}}function As(t){return function(r){return t.apply(null,r)}}function ks(t){return m.isObject(t)&&t.isAxiosError===!0}function un(t){const e=new me(t),r=Cr(me.prototype.request,e);return m.extend(r,me.prototype,e,{allOwnKeys:!0}),m.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return un(Ye(t,i))},r}const V=un(Pe);V.Axios=me,V.CanceledError=Je,V.CancelToken=er,V.isCancel=sn,V.VERSION=an,V.toFormData=pt,V.AxiosError=R,V.Cancel=V.CanceledError,V.all=function(e){return Promise.all(e)},V.spread=As,V.isAxiosError=ks,V.formToJSON=t=>Wr(m.isHTMLForm(t)?new FormData(t):t);/*! js-cookie v3.0.1 | MIT */function mt(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 Os={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 tr(t,e){function r(i,s,o){if(!(typeof document>"u")){o=mt({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var u in o)!o[u]||(a+="; "+u,o[u]!==!0&&(a+="="+o[u].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+a}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},a=0;a<s.length;a++){var u=s[a].split("="),c=u.slice(1).join("=");try{var d=decodeURIComponent(u[0]);if(o[d]=t.read(c,d),i===d)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",mt({},s,{expires:-1}))},withAttributes:function(i){return tr(this.converter,mt({},this.attributes,i))},withConverter:function(i){return tr(mt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var rr=tr(Os,{path:"/"}),Rs=Object.defineProperty,Ns=(t,e,r)=>e in t?Rs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ye=(t,e,r)=>(Ns(t,typeof e!="symbol"?e+"":e,r),r);function Is(t){return new TextEncoder().encode(t)}function ge(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 nr(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),s=new ArrayBuffer(i.length),o=new Uint8Array(s);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return s}function ln(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function fn(t){const{id:e}=t;return{...t,id:nr(e),transports:t.transports}}function dn(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class K extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}}function Ps({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 K("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 K("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 K("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new K("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new K("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(s=>s.type==="public-key").length===0?new K('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new K("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const s=window.location.hostname;if(dn(s)){if(i.rp.id!==s)return new K(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new K(`${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 K("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new K("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class Cs{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const yt=new Cs;async function hn(t){if(!ln())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:nr(t.challenge),user:{...t.user,id:Is(t.user.id)},excludeCredentials:t.excludeCredentials.map(fn)}};e.signal=yt.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(u){throw Ps({error:u,options:e})}finally{yt.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:s,type:o}=r,a={id:n,rawId:ge(i),response:{attestationObject:ge(s.attestationObject),clientDataJSON:ge(s.clientDataJSON)},type:o,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof s.getTransports=="function"&&(a.transports=s.getTransports()),a}function Us(t){return new TextDecoder("utf-8").decode(t)}async function Ds(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function _s({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 K("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new K("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new K("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(dn(i)){if(n.rpId!==i)return new K(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new K(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new K("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function js(t,e=!1){var r,n;if(!ln())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(fn));const s={...t,challenge:nr(t.challenge),allowCredentials:i},o={};if(e){if(!await Ds())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');o.mediation="conditional",s.allowCredentials=[]}o.publicKey=s,o.signal=yt.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(l){throw _s({error:l,options:o})}finally{yt.reset()}if(!a)throw new Error("Authentication was not completed");const{id:u,rawId:c,response:d,type:v}=a;let h;return d.userHandle&&(h=Us(d.userHandle)),{id:u,rawId:ge(c),response:{authenticatorData:ge(d.authenticatorData),clientDataJSON:ge(d.clientDataJSON),signature:ge(d.signature),userHandle:h},type:v,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:a.authenticatorAttachment}}const gt="nhostRefreshToken",wt="nhostRefreshTokenExpiresAt",Ls=3,Ms=300,Fs=5,pn=0,vn=1,de=10,Et=20;class St extends Error{constructor(e){super(e.message),ye(this,"error"),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:vn,message:e.message}):(this.name=e.error,this.error=e)}}const he={status:de,error:"invalid-email",message:"Email is incorrectly formatted"},ir={status:de,error:"invalid-password",message:"Password is incorrectly formatted"},mn={status:de,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},$s={status:de,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},qs={status:de,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Bs={status:de,error:"no-refresh-token",message:"No refresh token has been provided"},zs={status:Et,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},oe={status:Et,error:"already-signed-in",message:"User is already signed in"},Vs={status:Et,error:"unauthenticated-user",message:"User is not authenticated"},Ks={status:Et,error:"unverified-user",message:"Email needs verification"},Hs={status:de,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},Js={status:vn,error:"invalid-sign-in-method",message:"Invalid sign-in method"},Ce=t=>{const e=V.create({baseURL:t});return e.interceptors.response.use(r=>r,r=>{var n,i,s,o,a,u,c,d,v,h,l,f;return Promise.reject({error:{message:(a=(o=(s=(i=(n=r.response)==null?void 0:n.data)==null?void 0:i.message)!=null?s:r.message)!=null?o:r.request.responseText)!=null?a:JSON.stringify(r),status:(h=(v=(u=r.response)==null?void 0:u.status)!=null?v:(d=(c=r.response)==null?void 0:c.data)==null?void 0:d.statusCode)!=null?h:pn,error:((f=(l=r.response)==null?void 0:l.data)==null?void 0:f.error)||r.request.statusText||"network"}})}),e},Tt=typeof window<"u",bt=new Map,Gs=t=>{var e;return Tt&&typeof localStorage<"u"?localStorage.getItem(t):(e=bt.get(t))!=null?e:null},Ws=(t,e)=>{Tt&&typeof localStorage<"u"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?bt.set(t,e):bt.has(t)&&bt.delete(t)},Ys=(t,e)=>{if(t==="localStorage"||t==="web")return Gs;if(t==="cookie")return r=>{var n;return Tt&&(n=rr.get(r))!=null?n: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}`)},Qs=(t,e)=>{if(t==="localStorage"||t==="web")return Ws;if(t==="cookie")return(r,n)=>{Tt&&(n?rr.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):rr.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,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,s;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(s=e.remove)==null?void 0:s.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.deleteItemAsync)==null?void 0:s.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,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},yn=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const s=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(s)}`}).join("&");return r?`${t}?${r}`:t},re=(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),s=Object.fromEntries(new URLSearchParams(i.search)),o=new URL(r.startsWith("/")?i.origin+r:r),a=new URLSearchParams(o.search);let u=Object.fromEntries(a);r.startsWith("/")&&(u={...s,...u});let c=i.pathname;return o.pathname.length>1&&(c+=o.pathname.slice(1)),{...n,redirectTo:yn(o.origin+c,u)}};function xt(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 gn(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 s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const pe=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,}))$/),sr=t=>!!t&&typeof t=="string"&&t.length>=Ls,wn=t=>!!t&&typeof t=="string",Xs=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),or={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}},Zs=({backendUrl:t,clientUrl:e,interpreter:r})=>{const n=Ce(t);return Ke({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:$({error:i=>he}),saveRequestError:$({error:(i,{data:{error:s}})=>s}),reportError:X(i=>({type:"ERROR",error:i.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(i,{email:s})=>!pe(s)},services:{requestChange:async(i,{email:s,options:o})=>(await n.post("/user/email/change",{newEmail:s,options:re(e,o)},{headers:{authorization:`Bearer ${r==null?void 0:r.state.context.accessToken.value}`}})).data}})},eo=({backendUrl:t,interpreter:e})=>{const r=Ce(t);return Ke({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:$({error:n=>ir}),saveRequestError:$({error:(n,{data:{error:i}})=>i}),reportError:X(n=>({type:"ERROR",error:n.error})),reportSuccess:X("SUCCESS")},guards:{invalidPassword:(n,{password:i})=>!sr(i)},services:{requestChange:(n,{password:i,ticket:s})=>r.post("/user/password",{newPassword:i,ticket:s},{headers:{authorization:`Bearer ${e==null?void 0:e.state.context.accessToken.value}`}})}})},to=({backendUrl:t,clientUrl:e})=>{const r=Ce(t);return Ke({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:$({error:n=>he}),saveRequestError:$({error:(n,{data:{error:i}})=>i}),reportError:X(n=>({type:"ERROR",error:n.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!pe(i)},services:{requestChange:(n,{email:i,options:s})=>r.post("/user/password/reset",{email:i,options:re(e,s)})}})},ro=({backendUrl:t,clientUrl:e})=>{const r=Ce(t);return Ke({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:$({error:n=>he}),saveRequestError:$({error:(n,{data:{error:i}})=>i}),reportError:X(n=>({type:"ERROR",error:n.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!pe(i)},services:{request:async(n,{email:i,options:s})=>(await r.post("/user/email/send-verification-email",{email:i,options:re(e,s)})).data}})},no=({backendUrl:t,clientUrl:e,clientStorageGetter:r,clientStorageSetter:n,clientStorageType:i="web",clientStorage:s,refreshIntervalTime:o,autoRefreshToken:a=!0,autoSignIn:u=!0})=>{const c=r||Ys(i,s),d=n||Qs(i,s),v=Ce(t),h=async(l,f,p)=>(await v.post(l,f,p)).data;return Ke({schema:{context:{},events:{},services:{}},tsTypes:{},context:or,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:X("SIGNED_IN"),reportSignedOut:X("SIGNED_OUT"),reportTokenChanged:X("TOKEN_CHANGED"),incrementTokenImportAttempts:$({importTokenAttempts:({importTokenAttempts:l})=>l+1}),clearContext:$(()=>(d(wt,null),d(gt,null),{...or})),clearContextExceptRefreshToken:$(({refreshToken:{value:l}})=>(d(wt,null),{...or,refreshToken:{value:l}})),saveSession:$({user:(l,{data:f})=>{var p;return((p=f==null?void 0:f.session)==null?void 0:p.user)||null},accessToken:(l,{data:f})=>{if(f.session){const{accessTokenExpiresIn:p,accessToken:y}=f.session,E=new Date(Date.now()+p*1e3);return d(wt,E.toISOString()),{value:y,expiresAt:E}}return d(wt,null),{value:null,expiresAt:null}},refreshToken:(l,{data:f})=>{var p;const y=((p=f.session)==null?void 0:p.refreshToken)||null;return y&&d(gt,y),{value:y}}}),saveMfaTicket:$({mfa:(l,f)=>{var p;return(p=f.data)==null?void 0:p.mfa}}),resetTimer:$({refreshTimer:l=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:$({refreshTimer:(l,f)=>({startedAt:l.refreshTimer.startedAt,attempts:l.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:$({errors:({errors:l},{data:{error:f}})=>({...l,authentication:f})}),resetErrors:$({errors:l=>({}),importTokenAttempts:l=>0}),saveRegistrationError:$({errors:({errors:l},{data:{error:f}})=>({...l,registration:f})}),destroyRefreshToken:$({refreshToken:l=>(d(gt,null),{value:null})}),cleanUrl:()=>{u&&xt("refreshToken")&&(gn("refreshToken"),gn("type"))},broadcastToken:l=>{if(u)try{new BroadcastChannel("nhost").postMessage(l.refreshToken.value)}catch{}}},guards:{isAnonymous:(l,f)=>{var p;return!!((p=l.user)!=null&&p.isAnonymous)},isSignedIn:l=>!!l.user&&!!l.refreshToken.value&&!!l.accessToken.value,noToken:l=>!l.refreshToken.value,hasRefreshToken:l=>!!l.refreshToken.value,isAutoRefreshDisabled:()=>!a,refreshTimerShouldRefresh:l=>{const{expiresAt:f}=l.accessToken;return f?l.refreshTimer.lastAttempt?Date.now()-l.refreshTimer.lastAttempt.getTime()>Fs*1e3:o&&Date.now()-l.refreshTimer.startedAt.getTime()>o*1e3?!0:f.getTime()-Date.now()-1e3*Ms<=0:!1},shouldRetryImportToken:(l,f)=>f.data.error.status===pn||f.data.error.status>=500,unverified:(l,{data:{error:f}})=>f.status===401&&(f.message==="Email is not verified"||f.error==="unverified-user"),hasSession:(l,f)=>{var p;return!!((p=f.data)!=null&&p.session)},hasMfaTicket:(l,f)=>{var p;return!!((p=f.data)!=null&&p.mfa)}},services:{signInPassword:(l,{email:f,password:p})=>pe(f)?sr(p)?h("/signin/email-password",{email:f,password:p}):Promise.reject({error:ir}):Promise.reject({error:he}),passwordlessSms:(l,{phoneNumber:f,options:p})=>{var y;return wn(f)?(y=l.user)!=null&&y.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),h("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:f,options:re(e,p)},{headers:{authorization:`Bearer ${l.accessToken.value}`}})):h("/signin/passwordless/sms",{phoneNumber:f,options:re(e,p)}):Promise.reject({error:mn})},passwordlessSmsOtp:(l,{phoneNumber:f,otp:p})=>wn(f)?h("/signin/passwordless/sms/otp",{phoneNumber:f,otp:p}):Promise.reject({error:mn}),passwordlessEmail:(l,{email:f,options:p})=>{var y;return pe(f)?(y=l.user)!=null&&y.isAnonymous?h("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:f,options:re(e,p)},{headers:{authorization:`Bearer ${l.accessToken.value}`}}):h("/signin/passwordless/email",{email:f,options:re(e,p)}):Promise.reject({error:he})},signInAnonymous:l=>h("/signin/anonymous"),signInMfaTotp:(l,f)=>{var p;const y=f.ticket||((p=l.mfa)==null?void 0:p.ticket);return y?Xs(y)?h("/signin/mfa/totp",{ticket:y,otp:f.otp}):Promise.reject({error:$s}):Promise.reject({error:qs})},signInSecurityKeyEmail:async(l,{email:f})=>{if(!pe(f))throw new St(he);const p=await h("/signin/webauthn",{email:f});let y;try{y=await js(p)}catch(E){throw new St(E)}return h("/signin/webauthn/verify",{email:f,credential:y})},refreshToken:async(l,f)=>{const p=f.type==="TRY_TOKEN"?f.token:l.refreshToken.value;return{session:await h("/token",{refreshToken:p}),error:null}},signout:(l,f)=>h("/signout",{refreshToken:l.refreshToken.value,all:!!f.all}),signUpEmailPassword:async(l,{email:f,password:p,options:y})=>{var E;return pe(f)?sr(p)?(E=l.user)!=null&&E.isAnonymous?h("/user/deanonymize",{signInMethod:"email-password",email:f,password:p,options:re(e,y)},{headers:{authorization:`Bearer ${l.accessToken.value}`}}):h("/signup/email-password",{email:f,password:p,options:re(e,y)}):Promise.reject({error:ir}):Promise.reject({error:he})},signUpSecurityKey:async(l,{email:f,options:p})=>{if(!pe(f))return Promise.reject({error:he});const y=p==null?void 0:p.nickname;y&&delete p.nickname;const E=await h("/signup/webauthn",{email:f,options:p});let g;try{g=await hn(E)}catch(S){throw new St(S)}return h("/signup/webauthn/verify",{credential:g,options:{redirectTo:p==null?void 0:p.redirectTo,nickname:y}})},importRefreshToken:async()=>{let l=null;if(u){const p=xt("refreshToken")||null;if(p)try{return{session:await h("/token",{refreshToken:p}),error:null}}catch(y){l=y.error}else{const y=xt("error");if(y)return Promise.reject({session:null,error:{status:de,error:y,message:xt("errorDescription")||y}})}}const f=await c(gt);if(f)try{return{session:await h("/token",{refreshToken:f}),error:null}}catch(p){l=p.error}return l?Promise.reject({error:l,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:l})=>l<5?1e3:5e3}})};class io{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,devTools:a,...u}){if(ye(this,"backendUrl"),ye(this,"clientUrl"),ye(this,"machine"),ye(this,"_interpreter"),ye(this,"_channel"),ye(this,"_subscriptions",new Set),this.backendUrl=s,this.clientUrl=o,this.machine=no({...u,backendUrl:s,clientUrl:o,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&(this.interpreter=ke(this.machine,{devTools:a}),this.interpreter.start()),typeof window<"u"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",c=>{var d;const v=(d=this.interpreter)==null?void 0:d.state.context.refreshToken.value;this.interpreter&&c.data!==v&&this.interpreter.send("TRY_TOKEN",{token:c.data})})}catch{}}get interpreter(){return this._interpreter}set interpreter(e){this._interpreter=e,e&&this._subscriptions.forEach(r=>r(this))}onStart(e){this.interpreter?e(this):this._subscriptions.add(e)}}const so=async({backendUrl:t,interpreter:e},r)=>{const n=Ce(t);try{const{data:i}=await n.post("/user/webauthn/add",{},{headers:{authorization:`Bearer ${e==null?void 0:e.state.context.accessToken.value}`}});let s;try{s=await hn(i)}catch(a){throw new St(a)}const{data:o}=await n.post("/user/webauthn/verify",{credential:s,nickname:r},{headers:{authorization:`Bearer ${e==null?void 0:e.state.context.accessToken.value}`}});return{key:o,isError:!1,error:null,isSuccess:!0}}catch(i){const{error:s}=i;return{isError:!0,error:s,isSuccess:!1}}},oo=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})})}),ao=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})})}),co=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})})}),uo=(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})})}),lo=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:oe,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})})}),fo=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:s.accessToken.value,error:oe,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:o.context.mfa,user:null}):o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.context.user})})}),En=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:oe,isError:!0,isSuccess:!1});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({error:s.context.errors.registration||null,isError:!0,isSuccess:!1}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),ho=(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:oe,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:"signedIn"})&&r({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})}),po=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:s.accessToken.value,error:oe,isError:!0,isSuccess:!1,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:o.context.user})})}),Sn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:oe,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(s=>{s.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):s.matches("registration.incomplete.failed")&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),vo=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:oe,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),mo=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:Vs});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})})}),Tn=(t,e,r,n)=>new Promise(i=>{const{changed:s,context:o}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!s)return i({error:oe,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(a=>{a.matches("registration.incomplete.failed")?i({accessToken:null,error:a.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):a.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):a.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:a.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:a.context.user})})}),yo=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:oe,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({accessToken:null,error:o.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})});var go=Object.defineProperty,wo=(t,e,r)=>e in t?go(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bn=(t,e,r)=>(wo(t,typeof e!="symbol"?e+"":e,r),r);const Eo=()=>typeof window<"u",At=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},we=({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};class So{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,autoLogin:i,clientStorage:s,clientStorageType:o,clientStorageGetter:a,clientStorageSetter:u,refreshIntervalTime:c,start:d=!0}){bn(this,"_client"),bn(this,"url");var v;this.url=e,this._client=new io({backendUrl:e,clientUrl:typeof window<"u"&&((v=window.location)==null?void 0:v.origin)||"",autoRefreshToken:r,autoSignIn:typeof i=="boolean"?i:n,start:d,clientStorage:s,clientStorageType:o,clientStorageGetter:a,clientStorageSetter:u,refreshIntervalTime:c})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?we(await yo(r,n,i)):we(await Tn(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await lo(r);return{...we(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=yn(`${this._client.backendUrl}/signin/provider/${n}`,re(this._client.clientUrl,i));return Eo()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await fo(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:Ks}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...we(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await ho(r,e.email);return{...we(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:s}=await En(r,n,i);return{session:null,mfa:null,error:s}}if("phoneNumber"in e&&"otp"in e){const n=await vo(r,e.phoneNumber,e.otp);return{...we(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await Sn(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await po(r,e.otp,e.ticket);return{...we(n),mfa:null}}return{error:Js,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await mo(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=ke(to(this._client)).start(),{error:i}=await co(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=ke(eo(this._client)).start(),{error:i}=await ao(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=ke(ro(this._client)).start(),{error:i}=await uo(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=ke(Zs(this._client)).start(),{error:i}=await oo(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 En(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await Sn(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await Tn(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await so(this._client,e);return{error:r,key:n}}onTokenChanged(e){const r=n=>n.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(At(s))});if(this._client.interpreter){const n=r(this._client.interpreter);return()=>n.stop()}else return this._client.onStart(n=>{r(n.interpreter)}),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}onAuthStateChanged(e){const r=n=>n.onTransition(({event:i,context:s})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,At(s))});if(this._client.interpreter){const n=r(this._client.interpreter);return()=>n.stop()}else return this._client.onStart(n=>{r(n.interpreter)}),()=>{console.log("onAuthStateChanged was added before the interpreter started. Cannot unsubscribe listener.")}}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.state.matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).state.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}}getJWTToken(){return this.getAccessToken()}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.state.context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Dn(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.state.context.refreshToken.value;if(!i)return n({session:null,error:Bs});const{changed:s}=r.send("TRY_TOKEN",{token:i});if(!s)return n({session:null,error:zs});r.onTransition(o=>{o.matches({token:{idle:"error"}})?n({session:null,error:Hs}):o.event.type==="TOKEN_CHANGED"&&n({session:At(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return At((r=(e=this._client.interpreter)==null?void 0:e.state)==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.state)==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.state.hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n(`The state machine is not yet ready after ${15} seconds.`),15e3);e.onTransition(s=>{if(!s.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.state)!=null&&r.hasTag("loading"))}get client(){return this._client}}const To=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>\d+))?$/;function kt(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 s=n.match(To);if(s!=null&&s.groups){const{protocol:o="http",host:a,port:u=1337}=s.groups,c=Ao(e);return c||`${o}://${a}:${u}/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 bo(){return typeof window<"u"}function xo(){return typeof process<"u"&&process.env}function Ao(t){return bo()||!xo()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function xn(t){const e="subdomain"in t||"backendUrl"in t?kt(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new So({url:e,...t})}function An(t){const e="subdomain"in t||"backendUrl"in t?kt(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new kn({url:e,...t})}class kn{constructor(e){J(this,"url");J(this,"instance");J(this,"accessToken");J(this,"adminSecret");const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n,this.instance=V.create({baseURL:r})}async call(e,r,n){const i={...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};let s;try{s=await this.instance.post(e,r,{...n,headers:i})}catch(o){if(o instanceof Error)return{res:null,error:o}}return s?{res:s,error:null}:{res:null,error:new Error("Unable to make post request to funtion")}}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 On(t){const e="subdomain"in t||"backendUrl"in t?kt(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new Rn({url:e,...t})}class Rn{constructor(e){J(this,"url");J(this,"instance");J(this,"accessToken");J(this,"adminSecret");const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n,this.instance=V.create({baseURL:r})}async request(e,r,n){const i={...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};try{const s="",a=(await this.instance.post("",{operationName:s||void 0,query:typeof e=="string"?e:W.print(e),variables:r},{...n,headers:i})).data,{data:u}=a;return a.errors?{data:null,error:a.errors}:typeof u!="object"||Array.isArray(u)||u===null?{data:null,error:new Error("incorrect response data from GraphQL server")}:{data:u,error:null}}catch(s){return s instanceof Error?{data:null,error:s}:(console.error(s),{data:null,error:new Error("Unable to get do GraphQL request")})}}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}`}:{}}}var ko=Object.defineProperty,Oo=(t,e,r)=>e in t?ko(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ue=(t,e,r)=>(Oo(t,typeof e!="symbol"?e+"":e,r),r);class Ro{constructor({url:e}){Ue(this,"url"),Ue(this,"httpClient"),Ue(this,"accessToken"),Ue(this,"adminSecret"),this.url=e,this.httpClient=V.create({baseURL:this.url})}async upload(e){const{formData:r}=e;try{return{fileMetadata:(await this.httpClient.post("/files",r,{headers:{...this.generateUploadHeaders(e),...this.generateAuthHeaders(),"Content-Type":"multipart/form-data"}})).data,error:null}}catch(n){return{fileMetadata:null,error:n}}}async getPresignedUrl(e){try{const{fileId:r}=e;return{presignedUrl:(await this.httpClient.get(`/files/${r}/presignedurl`,{headers:{...this.generateAuthHeaders()}})).data,error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e;return await this.httpClient.delete(`/files/${r}`,{headers:{...this.generateAuthHeaders()}}),{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateUploadHeaders(e){const{bucketId:r,name:n,id:i}=e,s={};return r&&(s["x-nhost-bucket-id"]=r),i&&(s["x-nhost-file-id"]=i),n&&(s["x-nhost-file-name"]=n),s}generateAuthHeaders(){return!this.adminSecret&&!this.accessToken?null:this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}class No{constructor({url:e,adminSecret:r}){Ue(this,"url"),Ue(this,"api"),this.url=e,this.api=new Ro({url:e}),this.setAdminSecret(r)}async upload(e){let r;"file"in e?(r=new qr,r.append("file",e.file)):r=e.formData;const{fileMetadata:n,error:i}=await this.api.upload({...e,formData:r});return i?{fileMetadata:null,error:i}:n?{fileMetadata:n,error:null}:{fileMetadata:null,error:new Error("Invalid file returned")}}getUrl(e){return this.getPublicUrl(e)}getPublicUrl(e){const{fileId:r}=e;return`${this.url}/files/${r}`}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}}function Nn(t){const e="subdomain"in t||"backendUrl"in t?kt(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new No({url:e,...t})}const Io=t=>new In(t);class In{constructor({refreshIntervalTime:e,clientStorageGetter:r,clientStorageSetter:n,clientStorage:i,clientStorageType:s,autoRefreshToken:o,autoSignIn:a,adminSecret:u,devTools:c,start:d=!0,...v}){J(this,"auth");J(this,"storage");J(this,"functions");J(this,"graphql");J(this,"_adminSecret");J(this,"devTools");var h;this.auth=xn({refreshIntervalTime:e,clientStorageGetter:r,clientStorageSetter:n,clientStorage:i,clientStorageType:s,autoRefreshToken:o,autoSignIn:a,start:d,...v}),this.storage=Nn({adminSecret:u,...v}),this.functions=An({adminSecret:u,...v}),this.graphql=On({adminSecret:u,...v}),this.storage.setAccessToken(this.auth.getAccessToken()),this.functions.setAccessToken(this.auth.getAccessToken()),this.graphql.setAccessToken(this.auth.getAccessToken()),(h=this.auth.client)==null||h.onStart(()=>{this.auth.onAuthStateChanged((l,f)=>{l==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(l=>{this.storage.setAccessToken(l==null?void 0:l.accessToken),this.functions.setAccessToken(l==null?void 0:l.accessToken),this.graphql.setAccessToken(l==null?void 0:l.accessToken)})}),this._adminSecret=u,this.devTools=c}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}F.NhostClient=In,F.NhostFunctionsClient=kn,F.NhostGraphqlClient=Rn,F.createAuthClient=xn,F.createFunctionsClient=An,F.createGraphqlClient=On,F.createNhostClient=Io,F.createStorageClient=Nn,Object.defineProperties(F,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
20
21
  //# sourceMappingURL=nhost-js.umd.js.map