@clicktap/state 0.12.14 → 0.12.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +1 -1
- package/index.mjs +4 -4
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
${i.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function Ue(t){const e=Ie(t.config.target);return e?{target:e.map(n=>typeof n=="string"?it(t.parent,n):n)}:t.parent.initial}function D(t){return t.type==="history"}function ee(t){const e=je(t);for(const n of e)for(const s of G(n,t))e.add(s);return e}function je(t){const e=new Set;function n(s){if(!e.has(s)){if(e.add(s),s.type==="compound")n(s.initial.target[0]);else if(s.type==="parallel")for(const r of B(s))n(r)}}return n(t),e}function F(t,e){if(ct(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const n=t.states[e];if(!n)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return n}function it(t,e){if(typeof e=="string"&&ct(e))try{return t.machine.getStateNodeById(e)}catch{}const n=It(e).slice();let s=t;for(;n.length;){const r=n.shift();if(!r.length)break;s=F(s,r)}return s}function ot(t,e){if(typeof e=="string"){const r=t.states[e];if(!r)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,r]}const n=Object.keys(e),s=n.map(r=>F(t,r)).filter(Boolean);return[t.machine.root,t].concat(s,n.reduce((r,i)=>{const o=F(t,i);if(!o)return r;const a=ot(o,e[i]);return r.concat(a)},[]))}function Bn(t,e,n,s){const i=F(t,e).next(n,s);return!i||!i.length?t.next(n,s):i}function Fn(t,e,n,s){const r=Object.keys(e),i=F(t,r[0]),o=jt(i,e[r[0]],n,s);return!o||!o.length?t.next(n,s):o}function Hn(t,e,n,s){const r=[];for(const i of Object.keys(e)){const o=e[i];if(!o)continue;const a=F(t,i),u=jt(a,o,n,s);u&&r.push(...u)}return r.length?r:t.next(n,s)}function jt(t,e,n,s){return typeof e=="string"?Bn(t,e,n,s):Object.keys(e).length===1?Fn(t,e,n,s):Hn(t,e,n,s)}function qn(t){return Object.keys(t.states).map(e=>t.states[e]).filter(e=>e.type==="history")}function C(t,e){let n=t;for(;n.parent&&n.parent!==e;)n=n.parent;return n.parent===e}function zn(t,e){const n=new Set(t),s=new Set(e);for(const r of n)if(s.has(r))return!0;for(const r of s)if(n.has(r))return!0;return!1}function Ne(t,e,n){const s=new Set;for(const r of t){let i=!1;const o=new Set;for(const a of s)if(zn(vt([r],e,n),vt([a],e,n)))if(C(r.source,a.source))o.add(a);else{i=!0;break}if(!i){for(const a of o)s.delete(a);s.add(r)}}return Array.from(s)}function Jn(t){const[e,...n]=t;for(const s of G(e,void 0))if(n.every(r=>C(r,s)))return s}function Nt(t,e){if(!t.target)return[];const n=new Set;for(const s of t.target)if(D(s))if(e[s.id])for(const r of e[s.id])n.add(r);else for(const r of Nt(Ue(s),e))n.add(r);else n.add(s);return[...n]}function $e(t,e){const n=Nt(t,e);if(!n)return;if(!t.reenter&&n.every(r=>r===t.source||C(r,t.source)))return t.source;const s=Jn(n.concat(t.source));if(s)return s;if(!t.reenter)return t.source.machine.root}function vt(t,e,n){var r;const s=new Set;for(const i of t)if((r=i.target)!=null&&r.length){const o=$e(i,n);i.reenter&&i.source===o&&s.add(o);for(const a of e)C(a,o)&&s.add(a)}return[...s]}function Wn(t,e){if(t.length!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0}function bt(t,e,n,s,r,i){if(!t.length)return e;const o=new Set(e._nodes);let a=e.historyValue;const u=Ne(t,o,a);let c=e;r||([c,a]=Xn(c,s,n,u,o,a,i)),c=H(c,s,n,u.flatMap(f=>f.actions),i),c=Vn(c,s,n,u,o,i,a,r);const l=[...o];c.status==="done"&&(c=H(c,s,n,l.sort((f,p)=>p.order-f.order).flatMap(f=>f.exit),i));try{return a===e.historyValue&&Wn(e._nodes,o)?c:U(c,{_nodes:l,historyValue:a})}catch(f){throw f}}function Kn(t,e,n,s,r){if(s.output===void 0)return;const i=_t(r.id,r.output!==void 0&&r.parent?Tt(r.output,t.context,e,n.self):void 0);return Tt(s.output,t.context,i,n.self)}function Vn(t,e,n,s,r,i,o,a){let u=t;const c=new Set,l=new Set;Gn(s,o,l,c),a&&l.add(t.machine.root);const f=new Set;for(const p of[...c].sort((y,h)=>y.order-h.order)){r.add(p);const y=[];y.push(...p.entry);for(const h of p.invoke)y.push(Pn(h.src,{...h,syncSnapshot:!!h.onSnapshot}));if(l.has(p)){const h=p.initial.actions;y.push(...h)}if(u=H(u,e,n,y,i,p.invoke.map(h=>h.id)),p.type==="final"){const h=p.parent;let m=(h==null?void 0:h.type)==="parallel"?h:h==null?void 0:h.parent,S=m||p;for((h==null?void 0:h.type)==="compound"&&i.push(_t(h.id,p.output!==void 0?Tt(p.output,u.context,e,n.self):void 0));(m==null?void 0:m.type)==="parallel"&&!f.has(m)&&Ut(r,m);)f.add(m),i.push(_t(m.id)),S=m,m=m.parent;if(m)continue;u=U(u,{status:"done",output:Kn(u,e,n,u.machine.root,S)})}}return u}function Gn(t,e,n,s){for(const r of t){const i=$e(r,e);for(const a of r.target||[])!D(a)&&(r.source!==a||r.source!==i||r.reenter)&&(s.add(a),n.add(a)),$(a,e,n,s);const o=Nt(r,e);for(const a of o){const u=G(a,i);(i==null?void 0:i.type)==="parallel"&&u.push(i),Le(s,e,n,u,!r.source.parent&&r.reenter?void 0:i)}}}function $(t,e,n,s){var r;if(D(t))if(e[t.id]){const i=e[t.id];for(const o of i)s.add(o),$(o,e,n,s);for(const o of i)pt(o,t.parent,s,e,n)}else{const i=Ue(t);for(const o of i.target)s.add(o),i===((r=t.parent)==null?void 0:r.initial)&&n.add(t.parent),$(o,e,n,s);for(const o of i.target)pt(o,t.parent,s,e,n)}else if(t.type==="compound"){const[i]=t.initial.target;D(i)||(s.add(i),n.add(i)),$(i,e,n,s),pt(i,t,s,e,n)}else if(t.type==="parallel")for(const i of B(t).filter(o=>!D(o)))[...s].some(o=>C(o,i))||(D(i)||(s.add(i),n.add(i)),$(i,e,n,s))}function Le(t,e,n,s,r){for(const i of s)if((!r||C(i,r))&&t.add(i),i.type==="parallel")for(const o of B(i).filter(a=>!D(a)))[...t].some(a=>C(a,o))||(t.add(o),$(o,e,n,t))}function pt(t,e,n,s,r){Le(n,s,r,G(t,e))}function Xn(t,e,n,s,r,i,o){let a=t;const u=vt(s,r,i);u.sort((l,f)=>f.order-l.order);let c;for(const l of u)for(const f of qn(l)){let p;f.history==="deep"?p=y=>Mt(y)&&C(y,l):p=y=>y.parent===l,c??(c={...i}),c[f.id]=Array.from(r).filter(p)}for(const l of u)a=H(a,e,n,[...l.exit,...l.invoke.map(f=>Ce(f.id))],o),r.delete(l);return[a,c||i]}function Be(t,e,n,s,r,i){const{machine:o}=t;let a=t;for(const u of s){let y=function(){n.system._sendInspectionEvent({type:"@xstate.action",actorRef:n.self,action:{type:typeof u=="string"?u:typeof u=="object"?u.type:u.name||"(anonymous)",params:p}}),l(f,p)};const c=typeof u=="function",l=c?u:o.implementations.actions[typeof u=="string"?u:u.type];if(!l)continue;const f={context:a.context,event:e,self:n.self,system:n.system},p=c||typeof u=="string"?void 0:"params"in u?typeof u.params=="function"?u.params({context:a.context,event:e}):u.params:void 0;if(!("resolve"in l)){n.self._processingStatus===_.Running?y():n.defer(()=>{y()});continue}const h=l,[m,S,E]=h.resolve(n,a,f,p,l,r);a=m,"retryResolve"in h&&(i==null||i.push([h,S])),"execute"in h&&(n.self._processingStatus===_.Running?h.execute(n,S):n.defer(h.execute.bind(null,n,S))),E&&(a=Be(a,e,n,E,r,i))}return a}function H(t,e,n,s,r,i){const o=i?[]:void 0,a=Be(t,e,n,s,{internalQueue:r,deferredActorIds:i},o);return o==null||o.forEach(([u,c])=>{u.retryResolve(n,a,c)}),a}function yt(t,e,n,s=[]){let r=t;const i=[];function o(c,l,f){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:l,snapshot:c,_transitions:f}),i.push(c)}if(e.type===K)return r=U(ne(r,e,n),{status:"stopped"}),o(r,e,[]),{snapshot:r,microstates:i};let a=e;if(a.type!==be){const c=a,l=bn(c),f=se(c,r);if(l&&!f.length)return r=U(t,{status:"error",error:c.error}),o(r,c,[]),{snapshot:r,microstates:i};r=bt(f,t,n,a,!1,s),o(r,c,f)}let u=!0;for(;r.status==="active";){let c=u?Yn(r,a):[];const l=c.length?r:void 0;if(!c.length){if(!s.length)break;a=s.shift(),c=se(a,r)}r=bt(c,r,n,a,!1,s),u=r!==l,o(r,a,c)}return r.status!=="active"&&ne(r,a,n),{snapshot:r,microstates:i}}function ne(t,e,n){return H(t,e,n,Object.values(t.children).map(s=>Ce(s)),[])}function se(t,e){return e.machine.getTransitionData(e,t)}function Yn(t,e){const n=new Set,s=t._nodes.filter(Mt);for(const r of s)t:for(const i of[r].concat(G(r,void 0)))if(i.always){for(const o of i.always)if(o.guard===void 0||Dt(o.guard,t.context,e,t)){n.add(o);break t}}return Ne(Array.from(n),new Set(t._nodes),t.historyValue)}function Zn(t,e){const n=rt(ot(t,e));return Me(t,[...n])}function Qn(t){return!!t&&typeof t=="object"&&"machine"in t&&"value"in t}const ts=function(e){return Re(e,this.value)},es=function(e){return this.tags.has(e)},ns=function(e){const n=this.machine.getTransitionData(this,e);return!!(n!=null&&n.length)&&n.some(s=>s.target!==void 0||s.actions.length)},ss=function(){const{_nodes:e,tags:n,machine:s,getMeta:r,toJSON:i,can:o,hasTag:a,matches:u,...c}=this;return{...c,tags:Array.from(n)}},rs=function(){return this._nodes.reduce((e,n)=>(n.meta!==void 0&&(e[n.id]=n.meta),e),{})};function Q(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:Me(e.root,t._nodes),tags:new Set(t._nodes.flatMap(n=>n.tags)),children:t.children,historyValue:t.historyValue||{},matches:ts,hasTag:es,can:ns,getMeta:rs,toJSON:ss}}function U(t,e={}){return Q({...t,...e},t.machine)}function is(t,e){const{_nodes:n,tags:s,machine:r,children:i,context:o,can:a,hasTag:u,matches:c,getMeta:l,toJSON:f,...p}=t,y={};for(const m in i){const S=i[m];y[m]={snapshot:S.getPersistedSnapshot(e),src:S.src,systemId:S._systemId,syncSnapshot:S._syncSnapshot}}return{...p,context:Fe(o),children:y}}function Fe(t){let e;for(const n in t){const s=t[n];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)e??(e=Array.isArray(t)?t.slice():{...t}),e[n]={xstate$$type:Pt,id:s.id};else{const r=Fe(s);r!==s&&(e??(e=Array.isArray(t)?t.slice():{...t}),e[n]=r)}}return e??t}function os(t,e,n,s,{event:r,id:i,delay:o},{internalQueue:a}){const u=e.machine.implementations.delays;if(typeof r=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${r}" }) instead`);const c=typeof r=="function"?r(n,s):r;let l;if(typeof o=="string"){const f=u&&u[o];l=typeof f=="function"?f(n,s):f}else l=typeof o=="function"?o(n,s):o;return typeof l!="number"&&a.push(c),[e,{event:c,id:i,delay:l}]}function as(t,e){const{event:n,delay:s,id:r}=e;if(typeof s=="number"){t.defer(()=>{const i=t.self;t.system.scheduler.schedule(i,i,n,s,r)});return}}function cs(t,e){function n(s,r){}return n.type="xstate.raise",n.event=t,n.id=e==null?void 0:e.id,n.delay=e==null?void 0:e.delay,n.resolve=os,n.execute=as,n}const re=new WeakMap;function us(t){return{config:t,start:(n,s)=>{const{self:r,system:i}=s,o={receivers:void 0,dispose:void 0};re.set(r,o),o.dispose=t({input:n.input,system:i,self:r,sendBack:a=>{r.getSnapshot().status!=="stopped"&&r._parent&&i._relay(r,r._parent,a)},receive:a=>{o.receivers??(o.receivers=new Set),o.receivers.add(a)}})},transition:(n,s,r)=>{var o,a;const i=re.get(r.self);return s.type===K?(n={...n,status:"stopped",error:void 0},(o=i.dispose)==null||o.call(i),n):((a=i.receivers)==null||a.forEach(u=>u(s)),n)},getInitialSnapshot:(n,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}const ie="xstate.promise.resolve",oe="xstate.promise.reject";function mt(t){return{config:t,transition:(n,s)=>{if(n.status!=="active")return n;switch(s.type){case ie:{const r=s.data;return{...n,status:"done",output:r,input:void 0}}case oe:return{...n,status:"error",error:s.data,input:void 0};case K:return{...n,status:"stopped",input:void 0};default:return n}},start:(n,{self:s,system:r})=>{if(n.status!=="active")return;Promise.resolve(t({input:n.input,system:r,self:s})).then(o=>{s.getSnapshot().status==="active"&&r._relay(s,s,{type:ie,data:o})},o=>{s.getSnapshot().status==="active"&&r._relay(s,s,{type:oe,data:o})})},getInitialSnapshot:(n,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}function fs(t,{machine:e,context:n},s,r){const i=(o,a={})=>{const{systemId:u,input:c}=a;if(typeof o=="string"){const l=Ct(e,o);if(!l)throw new Error(`Actor logic '${o}' not implemented in machine '${e.id}'`);const f=L(l,{id:a.id,parent:t.self,syncSnapshot:a.syncSnapshot,input:typeof c=="function"?c({context:n,event:s,self:t.self}):c,src:o,systemId:u});return r[f.id]=f,f}else return L(o,{id:a.id,parent:t.self,syncSnapshot:a.syncSnapshot,input:a.input,src:o,systemId:u})};return(o,a)=>{const u=i(o,a);return r[u.id]=u,t.defer(()=>{u._processingStatus!==_.Stopped&&u.start()}),u}}function ls(t,e,n,s,{assignment:r}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},o={context:e.context,event:n.event,spawn:fs(t,e,n.event,i),self:t.self,system:t.system};let a={};if(typeof r=="function")a=r(o,s);else for(const c of Object.keys(r)){const l=r[c];a[c]=typeof l=="function"?l(o,s):l}const u=Object.assign({},e.context,a);return[U(e,{context:u,children:Object.keys(i).length?{...e.children,...i}:e.children})]}function v(t){function e(n,s){}return e.type="xstate.assign",e.assignment=t,e.resolve=ls,e}let ae=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function ds(t,e,n,s,{to:r,event:i,id:o,delay:a},u){var h;const c=e.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const l=typeof i=="function"?i(n,s):i;let f;if(typeof a=="string"){const m=c&&c[a];f=typeof m=="function"?m(n,s):m}else f=typeof a=="function"?a(n,s):a;const p=typeof r=="function"?r(n,s):r;let y;if(typeof p=="string"){if(p===ae.Parent?y=t.self._parent:p===ae.Internal?y=t.self:p.startsWith("#_")?y=e.children[p.slice(2)]:y=(h=u.deferredActorIds)!=null&&h.includes(p)?p:e.children[p],!y)throw new Error(`Unable to send event to actor '${p}' from machine '${e.machine.id}'.`)}else y=p||t.self;return[e,{to:y,event:l,id:o,delay:f}]}function hs(t,e,n){typeof n.to=="string"&&(n.to=e.children[n.to])}function ps(t,e){t.defer(()=>{const{to:n,event:s,delay:r,id:i}=e;if(typeof r=="number"){t.system.scheduler.schedule(t.self,n,s,r,i);return}t.system._relay(t.self,n,s.type===gn?Ae(t.self.id,s.data):s)})}function ce(t,e,n){function s(r,i){}return s.type="xsnapshot.sendTo",s.to=t,s.event=e,s.id=n==null?void 0:n.id,s.delay=n==null?void 0:n.delay,s.resolve=ds,s.retryResolve=hs,s.execute=ps,s}const ue=new WeakMap;function j(t,e,n){let s=ue.get(t);return s?e in s||(s[e]=n()):(s={[e]:n()},ue.set(t,s)),s[e]}const ys={},J=t=>typeof t=="string"?{type:t}:typeof t=="function"?"resolve"in t?{type:t.type}:{type:t.name}:t;class $t{constructor(e,n){if(this.config=e,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(Te),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?Zt(this.config.states,(s,r)=>new $t(s,{_parent:this,_key:r,_machine:this.machine})):ys,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=I(this.config.entry).slice(),this.exit=I(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=I(e.tags).slice()}_initialize(){this.transitions=Nn(this),this.config.always&&(this.always=N(this.config.always).map(e=>P(this,ve,e))),Object.keys(this.states).forEach(e=>{this.states[e]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(J),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(J),eventType:null})}:void 0,history:this.history,states:Zt(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(J)})),entry:this.entry.map(J),exit:this.exit.map(J),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return j(this,"invoke",()=>I(this.config.invoke).map((e,n)=>{const{src:s,systemId:r}=e,i=e.id??te(this.id,n),o=typeof s=="string"?s:`xstate.invoke.${te(this.id,n)}`;return{...e,src:o,id:i,systemId:r,toJSON(){const{onDone:a,onError:u,...c}=e;return{...c,type:"xstate.invoke",src:o,id:i}}}}))}get on(){return j(this,"on",()=>[...this.transitions].flatMap(([n,s])=>s.map(r=>[n,r])).reduce((n,[s,r])=>(n[s]=n[s]||[],n[s].push(r),n),{}))}get after(){return j(this,"delayedTransitions",()=>jn(this))}get initial(){return j(this,"initial",()=>$n(this,this.config.initial))}next(e,n){const s=n.type,r=[];let i;const o=j(this,`candidates-${s}`,()=>Un(this,s));for(const a of o){const{guard:u}=a,c=e.context;let l=!1;try{l=!u||Dt(u,c,n,e)}catch(f){const p=typeof u=="string"?u:typeof u=="object"?u.type:void 0;throw new Error(`Unable to evaluate guard ${p?`'${p}' `:""}in transition for event '${s}' in state node '${this.id}':
|
|
3
3
|
${f.message}`)}if(l){r.push(...a.actions),i=a;break}}return i?[i]:void 0}get events(){return j(this,"events",()=>{const{states:e}=this,n=new Set(this.ownEvents);if(e)for(const s of Object.keys(e)){const r=e[s];if(r.states)for(const i of r.events)n.add(`${i}`)}return Array.from(n)})}get ownEvents(){const e=new Set([...this.transitions.keys()].filter(n=>this.transitions.get(n).some(s=>!(!s.target&&!s.actions.length&&!s.reenter))));return Array.from(e)}}const ms="#";class Lt{constructor(e,n){this.config=e,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.__TResolvedTypesMeta=void 0,this.id=e.id||"(machine)",this.implementations={actors:(n==null?void 0:n.actors)??{},actions:(n==null?void 0:n.actions)??{},delays:(n==null?void 0:n.delays)??{},guards:(n==null?void 0:n.guards)??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new $t(e,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(e){const{actions:n,guards:s,actors:r,delays:i}=this.implementations;return new Lt(this.config,{actions:{...n,...e.actions},guards:{...s,...e.guards},actors:{...r,...e.actors},delays:{...i,...e.delays}})}resolveState(e){const n=Zn(this.root,e.value),s=rt(ot(this.root,n));return Q({_nodes:[...s],context:e.context||{},children:{},status:Ut(s,this.root)?"done":e.status||"active",output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,n,s){return yt(e,n,s).snapshot}microstep(e,n,s){return yt(e,n,s).microstates}getTransitionData(e,n){return jt(this.root,e.value,e,n)||[]}getPreInitialState(e,n,s){const{context:r}=this.config,i=Q({context:typeof r!="function"&&r?r:{},_nodes:[this.root],children:{},status:"active"},this);return typeof r=="function"?H(i,n,e,[v(({spawn:a,event:u,self:c})=>r({spawn:a,input:u.input,self:c}))],s):i}getInitialSnapshot(e,n){const s=xe(n),r=[],i=this.getPreInitialState(e,s,r),o=bt([{target:[...je(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],i,e,s,!0,r),{snapshot:a}=yt(o,s,e,r);return a}start(e){Object.values(e.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(e){const n=It(e),s=n.slice(1),r=ct(n[0])?n[0].slice(ms.length):n[0],i=this.idMap.get(r);if(!i)throw new Error(`Child state node '#${r}' does not exist on machine '${this.id}'`);return it(i,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(e,n){return is(e,n)}restoreSnapshot(e,n){const s={},r=e.children;Object.keys(r).forEach(u=>{const c=r[u],l=c.snapshot,f=c.src,p=typeof f=="string"?Ct(this,f):f;if(!p)return;const y=L(p,{id:u,parent:n.self,syncSnapshot:c.syncSnapshot,snapshot:l,src:f,systemId:c.systemId});s[u]=y});const i=Q({...e,children:s,_nodes:Array.from(rt(ot(this.root,e.value)))},this);let o=new Set;function a(u,c){if(!o.has(u)){o.add(u);for(let l in u){const f=u[l];if(f&&typeof f=="object"){if("xstate$$type"in f&&f.xstate$$type===Pt){u[l]=c[f.id];continue}a(f,c)}}}}return a(i.context,s),i}}function gs(t,e){return new Lt(t,e)}function Bt({schemas:t,actors:e,actions:n,guards:s,delays:r}){return{createMachine:i=>gs({...i,schemas:t},{actors:e,actions:n,guards:s,delays:r})}}function He(t,e){return function(){return t.apply(e,arguments)}}const{toString:Ss}=Object.prototype,{getPrototypeOf:Ft}=Object,ut=(t=>e=>{const n=Ss.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),A=t=>(t=t.toLowerCase(),e=>ut(e)===t),ft=t=>e=>typeof e===t,{isArray:z}=Array,V=ft("undefined");function Es(t){return t!==null&&!V(t)&&t.constructor!==null&&!V(t.constructor)&&T(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const qe=A("ArrayBuffer");function ws(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&qe(t.buffer),e}const _s=ft("string"),T=ft("function"),ze=ft("number"),lt=t=>t!==null&&typeof t=="object",Ts=t=>t===!0||t===!1,tt=t=>{if(ut(t)!=="object")return!1;const e=Ft(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},vs=A("Date"),bs=A("File"),As=A("Blob"),xs=A("FileList"),Rs=t=>lt(t)&&T(t.pipe),Os=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||T(t.append)&&((e=ut(t))==="formdata"||e==="object"&&T(t.toString)&&t.toString()==="[object FormData]"))},ks=A("URLSearchParams"),Is=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function X(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let s,r;if(typeof t!="object"&&(t=[t]),z(t))for(s=0,r=t.length;s<r;s++)e.call(null,t[s],s,t);else{const i=n?Object.getOwnPropertyNames(t):Object.keys(t),o=i.length;let a;for(s=0;s<o;s++)a=i[s],e.call(null,t[a],a,t)}}function Je(t,e){e=e.toLowerCase();const n=Object.keys(t);let s=n.length,r;for(;s-- >0;)if(r=n[s],e===r.toLowerCase())return r;return null}const We=(()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global)(),Ke=t=>!V(t)&&t!==We;function At(){const{caseless:t}=Ke(this)&&this||{},e={},n=(s,r)=>{const i=t&&Je(e,r)||r;tt(e[i])&&tt(s)?e[i]=At(e[i],s):tt(s)?e[i]=At({},s):z(s)?e[i]=s.slice():e[i]=s};for(let s=0,r=arguments.length;s<r;s++)arguments[s]&&X(arguments[s],n);return e}const Cs=(t,e,n,{allOwnKeys:s}={})=>(X(e,(r,i)=>{n&&T(r)?t[i]=He(r,n):t[i]=r},{allOwnKeys:s}),t),Ps=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Ds=(t,e,n,s)=>{t.prototype=Object.create(e.prototype,s),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},Ms=(t,e,n,s)=>{let r,i,o;const a={};if(e=e||{},t==null)return e;do{for(r=Object.getOwnPropertyNames(t),i=r.length;i-- >0;)o=r[i],(!s||s(o,t,e))&&!a[o]&&(e[o]=t[o],a[o]=!0);t=n!==!1&&Ft(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},Us=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const s=t.indexOf(e,n);return s!==-1&&s===n},js=t=>{if(!t)return null;if(z(t))return t;let e=t.length;if(!ze(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},Ns=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Ft(Uint8Array)),$s=(t,e)=>{const s=(t&&t[Symbol.iterator]).call(t);let r;for(;(r=s.next())&&!r.done;){const i=r.value;e.call(t,i[0],i[1])}},Ls=(t,e)=>{let n;const s=[];for(;(n=t.exec(e))!==null;)s.push(n);return s},Bs=A("HTMLFormElement"),Fs=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,s,r){return s.toUpperCase()+r}),fe=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Hs=A("RegExp"),Ve=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),s={};X(n,(r,i)=>{let o;(o=e(r,i,t))!==!1&&(s[i]=o||r)}),Object.defineProperties(t,s)},qs=t=>{Ve(t,(e,n)=>{if(T(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const s=t[n];if(T(s)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},zs=(t,e)=>{const n={},s=r=>{r.forEach(i=>{n[i]=!0})};return z(t)?s(t):s(String(t).split(e)),n},Js=()=>{},Ws=(t,e)=>(t=+t,Number.isFinite(t)?t:e),gt="abcdefghijklmnopqrstuvwxyz",le="0123456789",Ge={DIGIT:le,ALPHA:gt,ALPHA_DIGIT:gt+gt.toUpperCase()+le},Ks=(t=16,e=Ge.ALPHA_DIGIT)=>{let n="";const{length:s}=e;for(;t--;)n+=e[Math.random()*s|0];return n};function Vs(t){return!!(t&&T(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}const Gs=t=>{const e=new Array(10),n=(s,r)=>{if(lt(s)){if(e.indexOf(s)>=0)return;if(!("toJSON"in s)){e[r]=s;const i=z(s)?[]:{};return X(s,(o,a)=>{const u=n(o,r+1);!V(u)&&(i[a]=u)}),e[r]=void 0,i}}return s};return n(t,0)},Xs=A("AsyncFunction"),Ys=t=>t&&(lt(t)||T(t))&&T(t.then)&&T(t.catch),d={isArray:z,isArrayBuffer:qe,isBuffer:Es,isFormData:Os,isArrayBufferView:ws,isString:_s,isNumber:ze,isBoolean:Ts,isObject:lt,isPlainObject:tt,isUndefined:V,isDate:vs,isFile:bs,isBlob:As,isRegExp:Hs,isFunction:T,isStream:Rs,isURLSearchParams:ks,isTypedArray:Ns,isFileList:xs,forEach:X,merge:At,extend:Cs,trim:Is,stripBOM:Ps,inherits:Ds,toFlatObject:Ms,kindOf:ut,kindOfTest:A,endsWith:Us,toArray:js,forEachEntry:$s,matchAll:Ls,isHTMLForm:Bs,hasOwnProperty:fe,hasOwnProp:fe,reduceDescriptors:Ve,freezeMethods:qs,toObjectSet:zs,toCamelCase:Fs,noop:Js,toFiniteNumber:Ws,findKey:Je,global:We,isContextDefined:Ke,ALPHABET:Ge,generateString:Ks,isSpecCompliantForm:Vs,toJSONObject:Gs,isAsyncFn:Xs,isThenable:Ys};function g(t,e,n,s,r){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),n&&(this.config=n),s&&(this.request=s),r&&(this.response=r)}d.inherits(g,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:d.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const Xe=g.prototype,Ye={};["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=>{Ye[t]={value:t}});Object.defineProperties(g,Ye);Object.defineProperty(Xe,"isAxiosError",{value:!0});g.from=(t,e,n,s,r,i)=>{const o=Object.create(Xe);return d.toFlatObject(t,o,function(u){return u!==Error.prototype},a=>a!=="isAxiosError"),g.call(o,t.message,e,n,s,r),o.cause=t,o.name=t.name,i&&Object.assign(o,i),o};const Zs=null;function xt(t){return d.isPlainObject(t)||d.isArray(t)}function Ze(t){return d.endsWith(t,"[]")?t.slice(0,-2):t}function de(t,e,n){return t?t.concat(e).map(function(r,i){return r=Ze(r),!n&&i?"["+r+"]":r}).join(n?".":""):e}function Qs(t){return d.isArray(t)&&!t.some(xt)}const tr=d.toFlatObject(d,{},null,function(e){return/^is[A-Z]/.test(e)});function dt(t,e,n){if(!d.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=d.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,S){return!d.isUndefined(S[m])});const s=n.metaTokens,r=n.visitor||l,i=n.dots,o=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&d.isSpecCompliantForm(e);if(!d.isFunction(r))throw new TypeError("visitor must be a function");function c(h){if(h===null)return"";if(d.isDate(h))return h.toISOString();if(!u&&d.isBlob(h))throw new g("Blob is not supported. Use a Buffer instead.");return d.isArrayBuffer(h)||d.isTypedArray(h)?u&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function l(h,m,S){let E=h;if(h&&!S&&typeof h=="object"){if(d.endsWith(m,"{}"))m=s?m:m.slice(0,-2),h=JSON.stringify(h);else if(d.isArray(h)&&Qs(h)||(d.isFileList(h)||d.endsWith(m,"[]"))&&(E=d.toArray(h)))return m=Ze(m),E.forEach(function(Z,fn){!(d.isUndefined(Z)||Z===null)&&e.append(o===!0?de([m],fn,i):o===null?m:m+"[]",c(Z))}),!1}return xt(h)?!0:(e.append(de(S,m,i),c(h)),!1)}const f=[],p=Object.assign(tr,{defaultVisitor:l,convertValue:c,isVisitable:xt});function y(h,m){if(!d.isUndefined(h)){if(f.indexOf(h)!==-1)throw Error("Circular reference detected in "+m.join("."));f.push(h),d.forEach(h,function(E,O){(!(d.isUndefined(E)||E===null)&&r.call(e,E,d.isString(O)?O.trim():O,m,p))===!0&&y(E,m?m.concat(O):[O])}),f.pop()}}if(!d.isObject(t))throw new TypeError("data must be an object");return y(t),e}function he(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(s){return e[s]})}function Ht(t,e){this._pairs=[],t&&dt(t,this,e)}const Qe=Ht.prototype;Qe.append=function(e,n){this._pairs.push([e,n])};Qe.toString=function(e){const n=e?function(s){return e.call(this,s,he)}:he;return this._pairs.map(function(r){return n(r[0])+"="+n(r[1])},"").join("&")};function er(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function tn(t,e,n){if(!e)return t;const s=n&&n.encode||er,r=n&&n.serialize;let i;if(r?i=r(e,n):i=d.isURLSearchParams(e)?e.toString():new Ht(e,n).toString(s),i){const o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+i}return t}class nr{constructor(){this.handlers=[]}use(e,n,s){return this.handlers.push({fulfilled:e,rejected:n,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){d.forEach(this.handlers,function(s){s!==null&&e(s)})}}const pe=nr,en={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},sr=typeof URLSearchParams<"u"?URLSearchParams:Ht,rr=typeof FormData<"u"?FormData:null,ir=typeof Blob<"u"?Blob:null,or=(()=>{let t;return typeof navigator<"u"&&((t=navigator.product)==="ReactNative"||t==="NativeScript"||t==="NS")?!1:typeof window<"u"&&typeof document<"u"})(),ar=(()=>typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function")(),b={isBrowser:!0,classes:{URLSearchParams:sr,FormData:rr,Blob:ir},isStandardBrowserEnv:or,isStandardBrowserWebWorkerEnv:ar,protocols:["http","https","file","blob","url","data"]};function cr(t,e){return dt(t,new b.classes.URLSearchParams,Object.assign({visitor:function(n,s,r,i){return b.isNode&&d.isBuffer(n)?(this.append(s,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},e))}function ur(t){return d.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function fr(t){const e={},n=Object.keys(t);let s;const r=n.length;let i;for(s=0;s<r;s++)i=n[s],e[i]=t[i];return e}function nn(t){function e(n,s,r,i){let o=n[i++];const a=Number.isFinite(+o),u=i>=n.length;return o=!o&&d.isArray(r)?r.length:o,u?(d.hasOwnProp(r,o)?r[o]=[r[o],s]:r[o]=s,!a):((!r[o]||!d.isObject(r[o]))&&(r[o]=[]),e(n,s,r[o],i)&&d.isArray(r[o])&&(r[o]=fr(r[o])),!a)}if(d.isFormData(t)&&d.isFunction(t.entries)){const n={};return d.forEachEntry(t,(s,r)=>{e(ur(s),r,n,0)}),n}return null}function lr(t,e,n){if(d.isString(t))try{return(e||JSON.parse)(t),d.trim(t)}catch(s){if(s.name!=="SyntaxError")throw s}return(n||JSON.stringify)(t)}const qt={transitional:en,adapter:b.isNode?"http":"xhr",transformRequest:[function(e,n){const s=n.getContentType()||"",r=s.indexOf("application/json")>-1,i=d.isObject(e);if(i&&d.isHTMLForm(e)&&(e=new FormData(e)),d.isFormData(e))return r&&r?JSON.stringify(nn(e)):e;if(d.isArrayBuffer(e)||d.isBuffer(e)||d.isStream(e)||d.isFile(e)||d.isBlob(e))return e;if(d.isArrayBufferView(e))return e.buffer;if(d.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(i){if(s.indexOf("application/x-www-form-urlencoded")>-1)return cr(e,this.formSerializer).toString();if((a=d.isFileList(e))||s.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return dt(a?{"files[]":e}:e,u&&new u,this.formSerializer)}}return i||r?(n.setContentType("application/json",!1),lr(e)):e}],transformResponse:[function(e){const n=this.transitional||qt.transitional,s=n&&n.forcedJSONParsing,r=this.responseType==="json";if(e&&d.isString(e)&&(s&&!this.responseType||r)){const o=!(n&&n.silentJSONParsing)&&r;try{return JSON.parse(e)}catch(a){if(o)throw a.name==="SyntaxError"?g.from(a,g.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:b.classes.FormData,Blob:b.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};d.forEach(["delete","get","head","post","put","patch"],t=>{qt.headers[t]={}});const zt=qt,dr=d.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"]),hr=t=>{const e={};let n,s,r;return t&&t.split(`
|
|
4
4
|
`).forEach(function(o){r=o.indexOf(":"),n=o.substring(0,r).trim().toLowerCase(),s=o.substring(r+1).trim(),!(!n||e[n]&&dr[n])&&(n==="set-cookie"?e[n]?e[n].push(s):e[n]=[s]:e[n]=e[n]?e[n]+", "+s:s)}),e},ye=Symbol("internals");function W(t){return t&&String(t).trim().toLowerCase()}function et(t){return t===!1||t==null?t:d.isArray(t)?t.map(et):String(t)}function pr(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=n.exec(t);)e[s[1]]=s[2];return e}const yr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function St(t,e,n,s,r){if(d.isFunction(s))return s.call(this,e,n);if(r&&(e=n),!!d.isString(e)){if(d.isString(s))return e.indexOf(s)!==-1;if(d.isRegExp(s))return s.test(e)}}function mr(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,s)=>n.toUpperCase()+s)}function gr(t,e){const n=d.toCamelCase(" "+e);["get","set","has"].forEach(s=>{Object.defineProperty(t,s+n,{value:function(r,i,o){return this[s].call(this,e,r,i,o)},configurable:!0})})}class ht{constructor(e){e&&this.set(e)}set(e,n,s){const r=this;function i(a,u,c){const l=W(u);if(!l)throw new Error("header name must be a non-empty string");const f=d.findKey(r,l);(!f||r[f]===void 0||c===!0||c===void 0&&r[f]!==!1)&&(r[f||u]=et(a))}const o=(a,u)=>d.forEach(a,(c,l)=>i(c,l,u));return d.isPlainObject(e)||e instanceof this.constructor?o(e,n):d.isString(e)&&(e=e.trim())&&!yr(e)?o(hr(e),n):e!=null&&i(n,e,s),this}get(e,n){if(e=W(e),e){const s=d.findKey(this,e);if(s){const r=this[s];if(!n)return r;if(n===!0)return pr(r);if(d.isFunction(n))return n.call(this,r,s);if(d.isRegExp(n))return n.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=W(e),e){const s=d.findKey(this,e);return!!(s&&this[s]!==void 0&&(!n||St(this,this[s],s,n)))}return!1}delete(e,n){const s=this;let r=!1;function i(o){if(o=W(o),o){const a=d.findKey(s,o);a&&(!n||St(s,s[a],a,n))&&(delete s[a],r=!0)}}return d.isArray(e)?e.forEach(i):i(e),r}clear(e){const n=Object.keys(this);let s=n.length,r=!1;for(;s--;){const i=n[s];(!e||St(this,this[i],i,e,!0))&&(delete this[i],r=!0)}return r}normalize(e){const n=this,s={};return d.forEach(this,(r,i)=>{const o=d.findKey(s,i);if(o){n[o]=et(r),delete n[i];return}const a=e?mr(i):String(i).trim();a!==i&&delete n[i],n[a]=et(r),s[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return d.forEach(this,(s,r)=>{s!=null&&s!==!1&&(n[r]=e&&d.isArray(s)?s.join(", "):s)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(`
|
|
5
|
-
`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const s=new this(e);return n.forEach(r=>s.set(r)),s}static accessor(e){const s=(this[ye]=this[ye]={accessors:{}}).accessors,r=this.prototype;function i(o){const a=W(o);s[a]||(gr(r,o),s[a]=!0)}return d.isArray(e)?e.forEach(i):i(e),this}}ht.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);d.reduceDescriptors(ht.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(s){this[n]=s}}});d.freezeMethods(ht);const R=ht;function Et(t,e){const n=this||zt,s=e||n,r=R.from(s.headers);let i=s.data;return d.forEach(t,function(a){i=a.call(n,i,r.normalize(),e?e.status:void 0)}),r.normalize(),i}function sn(t){return!!(t&&t.__CANCEL__)}function Y(t,e,n){g.call(this,t??"canceled",g.ERR_CANCELED,e,n),this.name="CanceledError"}d.inherits(Y,g,{__CANCEL__:!0});function Sr(t,e,n){const s=n.config.validateStatus;!n.status||!s||s(n.status)?t(n):e(new g("Request failed with status code "+n.status,[g.ERR_BAD_REQUEST,g.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Er=b.isStandardBrowserEnv?function(){return{write:function(n,s,r,i,o,a){const u=[];u.push(n+"="+encodeURIComponent(s)),d.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),d.isString(i)&&u.push("path="+i),d.isString(o)&&u.push("domain="+o),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(n){const s=document.cookie.match(new RegExp("(^|;\\s*)("+n+")=([^;]*)"));return s?decodeURIComponent(s[3]):null},remove:function(n){this.write(n,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}();function wr(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function _r(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}function rn(t,e){return t&&!wr(e)?_r(t,e):e}const Tr=b.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let s;function r(i){let o=i;return e&&(n.setAttribute("href",o),o=n.href),n.setAttribute("href",o),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return s=r(window.location.href),function(o){const a=d.isString(o)?r(o):o;return a.protocol===s.protocol&&a.host===s.host}}():function(){return function(){return!0}}();function vr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function br(t,e){t=t||10;const n=new Array(t),s=new Array(t);let r=0,i=0,o;return e=e!==void 0?e:1e3,function(u){const c=Date.now(),l=s[i];o||(o=c),n[r]=u,s[r]=c;let f=i,p=0;for(;f!==r;)p+=n[f++],f=f%t;if(r=(r+1)%t,r===i&&(i=(i+1)%t),c-o<e)return;const y=l&&c-l;return y?Math.round(p*1e3/y):void 0}}function me(t,e){let n=0;const s=br(50,250);return r=>{const i=r.loaded,o=r.lengthComputable?r.total:void 0,a=i-n,u=s(a),c=i<=o;n=i;const l={loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:u||void 0,estimated:u&&o&&c?(o-i)/u:void 0,event:r};l[e?"download":"upload"]=!0,t(l)}}const Ar=typeof XMLHttpRequest<"u",xr=Ar&&function(t){return new Promise(function(n,s){let r=t.data;const i=R.from(t.headers).normalize(),o=t.responseType;let a;function u(){t.cancelToken&&t.cancelToken.unsubscribe(a),t.signal&&t.signal.removeEventListener("abort",a)}d.isFormData(r)&&(b.isStandardBrowserEnv||b.isStandardBrowserWebWorkerEnv?i.setContentType(!1):i.setContentType("multipart/form-data;",!1));let c=new XMLHttpRequest;if(t.auth){const y=t.auth.username||"",h=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";i.set("Authorization","Basic "+btoa(y+":"+h))}const l=rn(t.baseURL,t.url);c.open(t.method.toUpperCase(),tn(l,t.params,t.paramsSerializer),!0),c.timeout=t.timeout;function f(){if(!c)return;const y=R.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),m={data:!o||o==="text"||o==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:y,config:t,request:c};Sr(function(E){n(E),u()},function(E){s(E),u()},m),c=null}if("onloadend"in c?c.onloadend=f:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(f)},c.onabort=function(){c&&(s(new g("Request aborted",g.ECONNABORTED,t,c)),c=null)},c.onerror=function(){s(new g("Network Error",g.ERR_NETWORK,t,c)),c=null},c.ontimeout=function(){let h=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded";const m=t.transitional||en;t.timeoutErrorMessage&&(h=t.timeoutErrorMessage),s(new g(h,m.clarifyTimeoutError?g.ETIMEDOUT:g.ECONNABORTED,t,c)),c=null},b.isStandardBrowserEnv){const y=(t.withCredentials||Tr(l))&&t.xsrfCookieName&&Er.read(t.xsrfCookieName);y&&i.set(t.xsrfHeaderName,y)}r===void 0&&i.setContentType(null),"setRequestHeader"in c&&d.forEach(i.toJSON(),function(h,m){c.setRequestHeader(m,h)}),d.isUndefined(t.withCredentials)||(c.withCredentials=!!t.withCredentials),o&&o!=="json"&&(c.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&c.addEventListener("progress",me(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&c.upload&&c.upload.addEventListener("progress",me(t.onUploadProgress)),(t.cancelToken||t.signal)&&(a=y=>{c&&(s(!y||y.type?new Y(null,t,c):y),c.abort(),c=null)},t.cancelToken&&t.cancelToken.subscribe(a),t.signal&&(t.signal.aborted?a():t.signal.addEventListener("abort",a)));const p=vr(l);if(p&&b.protocols.indexOf(p)===-1){s(new g("Unsupported protocol "+p+":",g.ERR_BAD_REQUEST,t));return}c.send(r||null)})},nt={http:Zs,xhr:xr};d.forEach(nt,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const on={getAdapter:t=>{t=d.isArray(t)?t:[t];const{length:e}=t;let n,s;for(let r=0;r<e&&(n=t[r],!(s=d.isString(n)?nt[n.toLowerCase()]:n));r++);if(!s)throw s===!1?new g(`Adapter ${n} is not supported by the environment`,"ERR_NOT_SUPPORT"):new Error(d.hasOwnProp(nt,n)?`Adapter '${n}' is not available in the build`:`Unknown adapter '${n}'`);if(!d.isFunction(s))throw new TypeError("adapter is not a function");return s},adapters:nt};function wt(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Y(null,t)}function ge(t){return wt(t),t.headers=R.from(t.headers),t.data=Et.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),on.getAdapter(t.adapter||zt.adapter)(t).then(function(s){return wt(t),s.data=Et.call(t,t.transformResponse,s),s.headers=R.from(s.headers),s},function(s){return sn(s)||(wt(t),s&&s.response&&(s.response.data=Et.call(t,t.transformResponse,s.response),s.response.headers=R.from(s.response.headers))),Promise.reject(s)})}const Se=t=>t instanceof R?t.toJSON():t;function q(t,e){e=e||{};const n={};function s(c,l,f){return d.isPlainObject(c)&&d.isPlainObject(l)?d.merge.call({caseless:f},c,l):d.isPlainObject(l)?d.merge({},l):d.isArray(l)?l.slice():l}function r(c,l,f){if(d.isUndefined(l)){if(!d.isUndefined(c))return s(void 0,c,f)}else return s(c,l,f)}function i(c,l){if(!d.isUndefined(l))return s(void 0,l)}function o(c,l){if(d.isUndefined(l)){if(!d.isUndefined(c))return s(void 0,c)}else return s(void 0,l)}function a(c,l,f){if(f in e)return s(c,l);if(f in t)return s(void 0,c)}const u={url:i,method:i,data:i,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,headers:(c,l)=>r(Se(c),Se(l),!0)};return d.forEach(Object.keys(Object.assign({},t,e)),function(l){const f=u[l]||r,p=f(t[l],e[l],l);d.isUndefined(p)&&f!==a||(n[l]=p)}),n}const an="1.5.0",Jt={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Jt[t]=function(s){return typeof s===t||"a"+(e<1?"n ":" ")+t}});const Ee={};Jt.transitional=function(e,n,s){function r(i,o){return"[Axios v"+an+"] Transitional option '"+i+"'"+o+(s?". "+s:"")}return(i,o,a)=>{if(e===!1)throw new g(r(o," has been removed"+(n?" in "+n:"")),g.ERR_DEPRECATED);return n&&!Ee[o]&&(Ee[o]=!0,console.warn(r(o," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(i,o,a):!0}};function Rr(t,e,n){if(typeof t!="object")throw new g("options must be an object",g.ERR_BAD_OPTION_VALUE);const s=Object.keys(t);let r=s.length;for(;r-- >0;){const i=s[r],o=e[i];if(o){const a=t[i],u=a===void 0||o(a,i,t);if(u!==!0)throw new g("option "+i+" must be "+u,g.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new g("Unknown option "+i,g.ERR_BAD_OPTION)}}const Rt={assertOptions:Rr,validators:Jt},k=Rt.validators;class at{constructor(e){this.defaults=e,this.interceptors={request:new pe,response:new pe}}request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=q(this.defaults,n);const{transitional:s,paramsSerializer:r,headers:i}=n;s!==void 0&&Rt.assertOptions(s,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),r!=null&&(d.isFunction(r)?n.paramsSerializer={serialize:r}:Rt.assertOptions(r,{encode:k.function,serialize:k.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=i&&d.merge(i.common,i[n.method]);i&&d.forEach(["delete","get","head","post","put","patch","common"],h=>{delete i[h]}),n.headers=R.concat(o,i);const a=[];let u=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(u=u&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const c=[];this.interceptors.response.forEach(function(m){c.push(m.fulfilled,m.rejected)});let l,f=0,p;if(!u){const h=[ge.bind(this),void 0];for(h.unshift.apply(h,a),h.push.apply(h,c),p=h.length,l=Promise.resolve(n);f<p;)l=l.then(h[f++],h[f++]);return l}p=a.length;let y=n;for(f=0;f<p;){const h=a[f++],m=a[f++];try{y=h(y)}catch(S){m.call(this,S);break}}try{l=ge.call(this,y)}catch(h){return Promise.reject(h)}for(f=0,p=c.length;f<p;)l=l.then(c[f++],c[f++]);return l}getUri(e){e=q(this.defaults,e);const n=rn(e.baseURL,e.url);return tn(n,e.params,e.paramsSerializer)}}d.forEach(["delete","get","head","options"],function(e){at.prototype[e]=function(n,s){return this.request(q(s||{},{method:e,url:n,data:(s||{}).data}))}});d.forEach(["post","put","patch"],function(e){function n(s){return function(i,o,a){return this.request(q(a||{},{method:e,headers:s?{"Content-Type":"multipart/form-data"}:{},url:i,data:o}))}}at.prototype[e]=n(),at.prototype[e+"Form"]=n(!0)});const st=at;class Wt{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(i){n=i});const s=this;this.promise.then(r=>{if(!s._listeners)return;let i=s._listeners.length;for(;i-- >0;)s._listeners[i](r);s._listeners=null}),this.promise.then=r=>{let i;const o=new Promise(a=>{s.subscribe(a),i=a}).then(r);return o.cancel=function(){s.unsubscribe(i)},o},e(function(i,o,a){s.reason||(s.reason=new Y(i,o,a),n(s.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 n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}static source(){let e;return{token:new Wt(function(r){e=r}),cancel:e}}}const Or=Wt;function kr(t){return function(n){return t.apply(null,n)}}function Ir(t){return d.isObject(t)&&t.isAxiosError===!0}const Ot={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Ot).forEach(([t,e])=>{Ot[e]=t});const Cr=Ot;function cn(t){const e=new st(t),n=He(st.prototype.request,e);return d.extend(n,st.prototype,e,{allOwnKeys:!0}),d.extend(n,e,null,{allOwnKeys:!0}),n.create=function(r){return cn(q(t,r))},n}const w=cn(zt);w.Axios=st;w.CanceledError=Y;w.CancelToken=Or;w.isCancel=sn;w.VERSION=an;w.toFormData=dt;w.AxiosError=g;w.Cancel=w.CanceledError;w.all=function(e){return Promise.all(e)};w.spread=kr;w.isAxiosError=Ir;w.mergeConfig=q;w.AxiosHeaders=R;w.formToJSON=t=>nn(d.isHTMLForm(t)?new FormData(t):t);w.getAdapter=on.getAdapter;w.HttpStatusCode=Cr;w.default=w;const Pr=w;async function we(t,e){const n=await fetch(t,e);return n.status===200?n.json():Promise.resolve({message:n.statusText,success:!1})}const kt=Bt({types:{context:{},events:{},input:{}},actions:{setUserContext:v(({context:t,event:e})=>{if(!e.type.includes("xstate.done.actor"))return t;const n=e;return n.output.type!=="AUTHENTICATE_SUCCESS"?t:{accessToken:n.output.accessToken,ignoreRefreshToken:!1}}),unsetUserContext:v(()=>({user:null,accessToken:"",refreshToken:"",ignoreRefreshToken:!1})),setAccessToken:v(({context:t,event:e})=>{if(!e.type.includes("xstate.done.actor"))return t;const n=e;return n.output.type!=="REFRESH_TOKEN_SUCCESS"?t:{accessToken:n.output.accessToken,ignoreRefreshToken:!1}}),unsetRefreshToken:v(()=>({refreshToken:""})),setIgnoreRefreshToken:v(()=>({ignoreRefreshToken:!0})),addError:v(({context:t,event:e})=>{if(!e.type.includes("xstate.error.actor"))return t;const n=e;return{errors:[...t.errors,String(n.error).replace("Error: ","")]}}),clearErrors:v(()=>({errors:[]}))},actors:{refreshAccessToken:mt(async({input:t})=>{let e;if(console.log("refreshAccessToken typeof window",typeof window),console.log("refreshAccessToken input",t),typeof window>"u"){if(t.context.refreshToken==="")throw new Error("Unauthorized.");try{const n=await Pr.post(t.context.endpoints.ssrRefresh,{grant_type:"refresh_token"},{headers:{Cookie:`refresh_token=${t.context.refreshToken}`,"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"},withCredentials:!0});console.log("refreshAccessToken axios res",n);const{data:s}=n;if(console.log("refreshAccessToken axios res.data",s),typeof s.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:s.accessToken}}catch{throw new Error("Could not complete refresh request (server)")}}else{e=await we(t.context.endpoints.refresh,{method:"POST",mode:"cors",credentials:"include",headers:{"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"},body:JSON.stringify({grant_type:"refresh_token"}).toString()}),console.log("refreshAccessToken fetch response",e);const n=e;if(typeof n.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:n.accessToken}}}),authenticate:mt(async({input:t})=>{var s;const n=await we(t.context.endpoints.login,{method:"POST",mode:"cors",credentials:"include",headers:{"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"},body:JSON.stringify({username:t.username,password:t.password}).toString()});if(!n.success)throw new Error(((s=n.message)==null?void 0:s.toString())??"Sign in failed. Please try again.");return{type:"AUTHENTICATE_SUCCESS",accessToken:n.accessToken}}),unauthenticate:mt(async({input:t})=>(await fetch(t.context.endpoints.logout,{method:"POST",mode:"cors",credentials:"include",headers:{"clicktap-scope":"view","clicktap-scope-id":"default"}}),{type:"UNAUTHENTICATE"}))}}).createMachine({id:"auth",context:({input:t})=>{var e,n;return{user:null,accessToken:"",refreshToken:((e=t==null?void 0:t.initialContext)==null?void 0:e.refreshToken)??"",ignoreRefreshToken:!1,endpoints:((n=t==null?void 0:t.initialContext)==null?void 0:n.endpoints)??{login:"",logout:"",refresh:"",ssrRefresh:""},errors:[]}},initial:"refreshing",states:{authenticating:{invoke:{src:"authenticate",input:({context:t,event:e})=>e.type!=="LOGIN"?{context:t,username:"",password:""}:{context:t,username:e.username,password:e.password},onDone:[{actions:"setUserContext",target:"loggedIn"}],onError:[{actions:"addError",target:"loggedOut"}]}},unauthenticating:{invoke:{src:"unauthenticate",input:({context:t})=>({context:t}),onDone:[{actions:"unsetUserContext",target:"loggedOut"}],onError:[{actions:["unsetUserContext","setIgnoreRefreshToken"],target:"loggedOut"}]}},refreshing:{invoke:{src:"refreshAccessToken",input:({context:t})=>({context:t}),onDone:[{actions:["unsetRefreshToken","setAccessToken"],target:"loggedIn"}],onError:[{actions:"unsetRefreshToken",target:"unauthenticating"}]}},loggedOut:{on:{LOGIN:{target:"authenticating"},CLEAR_ERRORS:{actions:"clearErrors"}}},loggedIn:{after:{84e4:{guard:()=>typeof window<"u",target:"refreshing"}},on:{LOGOUT:{target:"unauthenticating"},CLEAR_ERRORS:{actions:"clearErrors"}}}}}),Kt=M.createContext({}),Dr=()=>{const t=M.useContext(Kt),[e,n]=M.useState(typeof window<"u"&&t.getSnapshot().value==="loggedIn");return M.useEffect(()=>{if(typeof window>"u")return;const s=t.subscribe(r=>{(r.value==="loggedIn"||r.value==="loggedOut")&&n(r.value==="loggedIn")});return()=>{s.unsubscribe()}},[t]),{authActor:t,isLoggedIn:e}},Mr=async(t="",e={inspect:void 0,endpoints:{login:"",logout:"",refresh:"",ssrRefresh:""}})=>typeof window<"u"?(console.warn("App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page."),L(kt,{inspect:e.inspect,input:{initialContext:{endpoints:e.endpoints}}}).start()):L(kt,{input:{initialContext:{endpoints:e.endpoints,refreshToken:t}},inspect:e.inspect}).start();function Ur({actor:t,children:e}){return _e.jsx(Kt.Provider,{value:t,children:e})}let jr=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,n)=>(n&=63,n<36?e+=n.toString(36):n<62?e+=(n-26).toString(36).toUpperCase():n>62?e+="-":e+="_",e),"");const un=Bt({actors:{tick:us(({sendBack:t,input:e})=>{const n=setInterval(()=>{t({type:"TICK"})},e.interval);return()=>{clearInterval(n)}})},types:{context:{},events:{},input:{}}}).createMachine({id:"timer",initial:"running",context:({input:t})=>({elapsed:0,duration:t.initialContext.duration??3e3,interval:100,intervalId:null}),states:{paused:{on:{RESUME_TIMER:{target:"running",guard:({context:t})=>t.elapsed<t.duration}}},running:{invoke:{input:({context:t})=>({interval:t.interval}),src:"tick"},always:[{target:"completed",guard:({context:t})=>t.elapsed>=t.duration}],on:{TICK:{actions:v(({context:t,event:e})=>e.type!=="TICK"?t:{elapsed:t.elapsed+t.interval})},PAUSE_TIMER:{target:"paused"}}},completed:{type:"final"}}}),Nr=Bt({actors:{timer:un},types:{context:{},events:{},input:{}},actions:{addItem:v(({context:t,event:e})=>{if(e.type!=="ADD_ITEM")return t;const n=`notification-${jr()}`,s=e.duration??t.duration,r=M.cloneElement(e.item,{duration:s,id:n,key:e.item.key??n,...e.item.props}),i={duration:s,id:n,element:r},o=t.items;return t.order==="desc"?o.push(i):o.unshift(i),{items:o,activeItem:n}}),removeItem:v(({context:t,event:e})=>{if(e.type!=="REMOVE_ITEM"&&e.type!=="xstate.done.actor.timer")return t;const n=t.items;return t.order==="desc"?(n.pop(),{items:n,activeItem:n.length>0?n[n.length-1].id:null}):(n.shift(),{items:n,activeItem:n.length>0?n[0].id:null})})},delays:{ITEM_TIMEOUT:({context:t})=>t.items[t.items.length-1].duration??t.duration},guards:{itemHasTimeout:({context:t})=>t.items[t.items.length-1].duration>0||t.duration>0}}).createMachine({id:"toast",context:{items:[],order:"desc",duration:0,activeItem:null},initial:"idle",states:{idle:{on:{ADD_ITEM:{target:"adding"}}},active:{invoke:{id:"timer",src:"timer",input:({context:t})=>({initialContext:{duration:t.items[t.items.length-1].duration??t.duration}}),onDone:{target:"removing",guard:"itemHasTimeout"}},on:{ADD_ITEM:{target:"adding"},REMOVE_ITEM:{target:"removing"},SET_IDLE:{target:"idle"},RESUME_TIMER:{actions:ce("timer",{type:"RESUME_TIMER"})},PAUSE_TIMER:{actions:ce("timer",{type:"PAUSE_TIMER"})}}},adding:{entry:["addItem"],on:{SET_IDLE:{target:"idle"},SET_ACTIVE:{target:"active"}}},removing:{entry:"removeItem",on:{SET_IDLE:{target:"idle"},SET_ACTIVE:{target:"active"}}}}}),Vt=M.createContext({}),$r=()=>M.useContext(Vt);function Lr({children:t,actor:e}){return _e.jsx(Vt.Provider,{value:e,children:t})}exports.AuthContext=Kt;exports.AuthProvider=Ur;exports.ToastContext=Vt;exports.ToastProvider=Lr;exports.authMachine=kt;exports.getAuth=Mr;exports.timerMachine=un;exports.toastMachine=Nr;exports.useAuth=Dr;exports.useToast=$r;
|
|
5
|
+
`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const s=new this(e);return n.forEach(r=>s.set(r)),s}static accessor(e){const s=(this[ye]=this[ye]={accessors:{}}).accessors,r=this.prototype;function i(o){const a=W(o);s[a]||(gr(r,o),s[a]=!0)}return d.isArray(e)?e.forEach(i):i(e),this}}ht.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);d.reduceDescriptors(ht.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(s){this[n]=s}}});d.freezeMethods(ht);const R=ht;function Et(t,e){const n=this||zt,s=e||n,r=R.from(s.headers);let i=s.data;return d.forEach(t,function(a){i=a.call(n,i,r.normalize(),e?e.status:void 0)}),r.normalize(),i}function sn(t){return!!(t&&t.__CANCEL__)}function Y(t,e,n){g.call(this,t??"canceled",g.ERR_CANCELED,e,n),this.name="CanceledError"}d.inherits(Y,g,{__CANCEL__:!0});function Sr(t,e,n){const s=n.config.validateStatus;!n.status||!s||s(n.status)?t(n):e(new g("Request failed with status code "+n.status,[g.ERR_BAD_REQUEST,g.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Er=b.isStandardBrowserEnv?function(){return{write:function(n,s,r,i,o,a){const u=[];u.push(n+"="+encodeURIComponent(s)),d.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),d.isString(i)&&u.push("path="+i),d.isString(o)&&u.push("domain="+o),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(n){const s=document.cookie.match(new RegExp("(^|;\\s*)("+n+")=([^;]*)"));return s?decodeURIComponent(s[3]):null},remove:function(n){this.write(n,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}();function wr(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function _r(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}function rn(t,e){return t&&!wr(e)?_r(t,e):e}const Tr=b.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let s;function r(i){let o=i;return e&&(n.setAttribute("href",o),o=n.href),n.setAttribute("href",o),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return s=r(window.location.href),function(o){const a=d.isString(o)?r(o):o;return a.protocol===s.protocol&&a.host===s.host}}():function(){return function(){return!0}}();function vr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function br(t,e){t=t||10;const n=new Array(t),s=new Array(t);let r=0,i=0,o;return e=e!==void 0?e:1e3,function(u){const c=Date.now(),l=s[i];o||(o=c),n[r]=u,s[r]=c;let f=i,p=0;for(;f!==r;)p+=n[f++],f=f%t;if(r=(r+1)%t,r===i&&(i=(i+1)%t),c-o<e)return;const y=l&&c-l;return y?Math.round(p*1e3/y):void 0}}function me(t,e){let n=0;const s=br(50,250);return r=>{const i=r.loaded,o=r.lengthComputable?r.total:void 0,a=i-n,u=s(a),c=i<=o;n=i;const l={loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:u||void 0,estimated:u&&o&&c?(o-i)/u:void 0,event:r};l[e?"download":"upload"]=!0,t(l)}}const Ar=typeof XMLHttpRequest<"u",xr=Ar&&function(t){return new Promise(function(n,s){let r=t.data;const i=R.from(t.headers).normalize(),o=t.responseType;let a;function u(){t.cancelToken&&t.cancelToken.unsubscribe(a),t.signal&&t.signal.removeEventListener("abort",a)}d.isFormData(r)&&(b.isStandardBrowserEnv||b.isStandardBrowserWebWorkerEnv?i.setContentType(!1):i.setContentType("multipart/form-data;",!1));let c=new XMLHttpRequest;if(t.auth){const y=t.auth.username||"",h=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";i.set("Authorization","Basic "+btoa(y+":"+h))}const l=rn(t.baseURL,t.url);c.open(t.method.toUpperCase(),tn(l,t.params,t.paramsSerializer),!0),c.timeout=t.timeout;function f(){if(!c)return;const y=R.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),m={data:!o||o==="text"||o==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:y,config:t,request:c};Sr(function(E){n(E),u()},function(E){s(E),u()},m),c=null}if("onloadend"in c?c.onloadend=f:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(f)},c.onabort=function(){c&&(s(new g("Request aborted",g.ECONNABORTED,t,c)),c=null)},c.onerror=function(){s(new g("Network Error",g.ERR_NETWORK,t,c)),c=null},c.ontimeout=function(){let h=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded";const m=t.transitional||en;t.timeoutErrorMessage&&(h=t.timeoutErrorMessage),s(new g(h,m.clarifyTimeoutError?g.ETIMEDOUT:g.ECONNABORTED,t,c)),c=null},b.isStandardBrowserEnv){const y=(t.withCredentials||Tr(l))&&t.xsrfCookieName&&Er.read(t.xsrfCookieName);y&&i.set(t.xsrfHeaderName,y)}r===void 0&&i.setContentType(null),"setRequestHeader"in c&&d.forEach(i.toJSON(),function(h,m){c.setRequestHeader(m,h)}),d.isUndefined(t.withCredentials)||(c.withCredentials=!!t.withCredentials),o&&o!=="json"&&(c.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&c.addEventListener("progress",me(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&c.upload&&c.upload.addEventListener("progress",me(t.onUploadProgress)),(t.cancelToken||t.signal)&&(a=y=>{c&&(s(!y||y.type?new Y(null,t,c):y),c.abort(),c=null)},t.cancelToken&&t.cancelToken.subscribe(a),t.signal&&(t.signal.aborted?a():t.signal.addEventListener("abort",a)));const p=vr(l);if(p&&b.protocols.indexOf(p)===-1){s(new g("Unsupported protocol "+p+":",g.ERR_BAD_REQUEST,t));return}c.send(r||null)})},nt={http:Zs,xhr:xr};d.forEach(nt,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const on={getAdapter:t=>{t=d.isArray(t)?t:[t];const{length:e}=t;let n,s;for(let r=0;r<e&&(n=t[r],!(s=d.isString(n)?nt[n.toLowerCase()]:n));r++);if(!s)throw s===!1?new g(`Adapter ${n} is not supported by the environment`,"ERR_NOT_SUPPORT"):new Error(d.hasOwnProp(nt,n)?`Adapter '${n}' is not available in the build`:`Unknown adapter '${n}'`);if(!d.isFunction(s))throw new TypeError("adapter is not a function");return s},adapters:nt};function wt(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Y(null,t)}function ge(t){return wt(t),t.headers=R.from(t.headers),t.data=Et.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),on.getAdapter(t.adapter||zt.adapter)(t).then(function(s){return wt(t),s.data=Et.call(t,t.transformResponse,s),s.headers=R.from(s.headers),s},function(s){return sn(s)||(wt(t),s&&s.response&&(s.response.data=Et.call(t,t.transformResponse,s.response),s.response.headers=R.from(s.response.headers))),Promise.reject(s)})}const Se=t=>t instanceof R?t.toJSON():t;function q(t,e){e=e||{};const n={};function s(c,l,f){return d.isPlainObject(c)&&d.isPlainObject(l)?d.merge.call({caseless:f},c,l):d.isPlainObject(l)?d.merge({},l):d.isArray(l)?l.slice():l}function r(c,l,f){if(d.isUndefined(l)){if(!d.isUndefined(c))return s(void 0,c,f)}else return s(c,l,f)}function i(c,l){if(!d.isUndefined(l))return s(void 0,l)}function o(c,l){if(d.isUndefined(l)){if(!d.isUndefined(c))return s(void 0,c)}else return s(void 0,l)}function a(c,l,f){if(f in e)return s(c,l);if(f in t)return s(void 0,c)}const u={url:i,method:i,data:i,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,headers:(c,l)=>r(Se(c),Se(l),!0)};return d.forEach(Object.keys(Object.assign({},t,e)),function(l){const f=u[l]||r,p=f(t[l],e[l],l);d.isUndefined(p)&&f!==a||(n[l]=p)}),n}const an="1.5.0",Jt={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Jt[t]=function(s){return typeof s===t||"a"+(e<1?"n ":" ")+t}});const Ee={};Jt.transitional=function(e,n,s){function r(i,o){return"[Axios v"+an+"] Transitional option '"+i+"'"+o+(s?". "+s:"")}return(i,o,a)=>{if(e===!1)throw new g(r(o," has been removed"+(n?" in "+n:"")),g.ERR_DEPRECATED);return n&&!Ee[o]&&(Ee[o]=!0,console.warn(r(o," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(i,o,a):!0}};function Rr(t,e,n){if(typeof t!="object")throw new g("options must be an object",g.ERR_BAD_OPTION_VALUE);const s=Object.keys(t);let r=s.length;for(;r-- >0;){const i=s[r],o=e[i];if(o){const a=t[i],u=a===void 0||o(a,i,t);if(u!==!0)throw new g("option "+i+" must be "+u,g.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new g("Unknown option "+i,g.ERR_BAD_OPTION)}}const Rt={assertOptions:Rr,validators:Jt},k=Rt.validators;class at{constructor(e){this.defaults=e,this.interceptors={request:new pe,response:new pe}}request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=q(this.defaults,n);const{transitional:s,paramsSerializer:r,headers:i}=n;s!==void 0&&Rt.assertOptions(s,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),r!=null&&(d.isFunction(r)?n.paramsSerializer={serialize:r}:Rt.assertOptions(r,{encode:k.function,serialize:k.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=i&&d.merge(i.common,i[n.method]);i&&d.forEach(["delete","get","head","post","put","patch","common"],h=>{delete i[h]}),n.headers=R.concat(o,i);const a=[];let u=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(u=u&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const c=[];this.interceptors.response.forEach(function(m){c.push(m.fulfilled,m.rejected)});let l,f=0,p;if(!u){const h=[ge.bind(this),void 0];for(h.unshift.apply(h,a),h.push.apply(h,c),p=h.length,l=Promise.resolve(n);f<p;)l=l.then(h[f++],h[f++]);return l}p=a.length;let y=n;for(f=0;f<p;){const h=a[f++],m=a[f++];try{y=h(y)}catch(S){m.call(this,S);break}}try{l=ge.call(this,y)}catch(h){return Promise.reject(h)}for(f=0,p=c.length;f<p;)l=l.then(c[f++],c[f++]);return l}getUri(e){e=q(this.defaults,e);const n=rn(e.baseURL,e.url);return tn(n,e.params,e.paramsSerializer)}}d.forEach(["delete","get","head","options"],function(e){at.prototype[e]=function(n,s){return this.request(q(s||{},{method:e,url:n,data:(s||{}).data}))}});d.forEach(["post","put","patch"],function(e){function n(s){return function(i,o,a){return this.request(q(a||{},{method:e,headers:s?{"Content-Type":"multipart/form-data"}:{},url:i,data:o}))}}at.prototype[e]=n(),at.prototype[e+"Form"]=n(!0)});const st=at;class Wt{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(i){n=i});const s=this;this.promise.then(r=>{if(!s._listeners)return;let i=s._listeners.length;for(;i-- >0;)s._listeners[i](r);s._listeners=null}),this.promise.then=r=>{let i;const o=new Promise(a=>{s.subscribe(a),i=a}).then(r);return o.cancel=function(){s.unsubscribe(i)},o},e(function(i,o,a){s.reason||(s.reason=new Y(i,o,a),n(s.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 n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}static source(){let e;return{token:new Wt(function(r){e=r}),cancel:e}}}const Or=Wt;function kr(t){return function(n){return t.apply(null,n)}}function Ir(t){return d.isObject(t)&&t.isAxiosError===!0}const Ot={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Ot).forEach(([t,e])=>{Ot[e]=t});const Cr=Ot;function cn(t){const e=new st(t),n=He(st.prototype.request,e);return d.extend(n,st.prototype,e,{allOwnKeys:!0}),d.extend(n,e,null,{allOwnKeys:!0}),n.create=function(r){return cn(q(t,r))},n}const w=cn(zt);w.Axios=st;w.CanceledError=Y;w.CancelToken=Or;w.isCancel=sn;w.VERSION=an;w.toFormData=dt;w.AxiosError=g;w.Cancel=w.CanceledError;w.all=function(e){return Promise.all(e)};w.spread=kr;w.isAxiosError=Ir;w.mergeConfig=q;w.AxiosHeaders=R;w.formToJSON=t=>nn(d.isHTMLForm(t)?new FormData(t):t);w.getAdapter=on.getAdapter;w.HttpStatusCode=Cr;w.default=w;const Pr=w;async function we(t,e){const n=await fetch(t,e);return n.status===200?n.json():Promise.resolve({message:n.statusText,success:!1})}const kt=Bt({types:{context:{},events:{},input:{}},actions:{setUserContext:v(({context:t,event:e})=>{if(!e.type.includes("xstate.done.actor"))return t;const n=e;return n.output.type!=="AUTHENTICATE_SUCCESS"?t:{accessToken:n.output.accessToken,ignoreRefreshToken:!1}}),unsetUserContext:v(()=>({user:null,accessToken:"",refreshToken:"",ignoreRefreshToken:!1})),setAccessToken:v(({context:t,event:e})=>{if(!e.type.includes("xstate.done.actor"))return t;const n=e;return n.output.type!=="REFRESH_TOKEN_SUCCESS"?t:{accessToken:n.output.accessToken,ignoreRefreshToken:!1}}),unsetRefreshToken:v(()=>({refreshToken:""})),setIgnoreRefreshToken:v(()=>({ignoreRefreshToken:!0})),addError:v(({context:t,event:e})=>{if(!e.type.includes("xstate.error.actor"))return t;const n=e;return{errors:[...t.errors,String(n.error).replace("Error: ","")]}}),clearErrors:v(()=>({errors:[]}))},actors:{refreshAccessToken:mt(async({input:t})=>{let e;if(typeof window>"u"){if(t.context.refreshToken==="")throw new Error("Unauthorized.");try{const n=await Pr.post(t.context.endpoints.ssrRefresh,{},{headers:{Cookie:`refresh_token=${t.context.refreshToken}`,"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"},withCredentials:!0});console.log("refreshAccessToken axios res",n);const{data:s}=n;if(console.log("refreshAccessToken axios res.data",s),typeof s.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:s.accessToken}}catch(n){throw console.log(n),new Error("Could not complete refresh request (server)")}}else{e=await we(t.context.endpoints.refresh,{method:"POST",mode:"cors",credentials:"include",headers:{"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"},body:JSON.stringify({grant_type:"refresh_token"}).toString()}),console.log("refreshAccessToken fetch response",e);const n=e;if(typeof n.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:n.accessToken}}}),authenticate:mt(async({input:t})=>{var s;const n=await we(t.context.endpoints.login,{method:"POST",mode:"cors",credentials:"include",headers:{"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"},body:JSON.stringify({username:t.username,password:t.password}).toString()});if(!n.success)throw new Error(((s=n.message)==null?void 0:s.toString())??"Sign in failed. Please try again.");return{type:"AUTHENTICATE_SUCCESS",accessToken:n.accessToken}}),unauthenticate:mt(async({input:t})=>(await fetch(t.context.endpoints.logout,{method:"POST",mode:"cors",credentials:"include",headers:{"clicktap-scope":"view","clicktap-scope-id":"default"}}),{type:"UNAUTHENTICATE"}))}}).createMachine({id:"auth",context:({input:t})=>{var e,n;return{user:null,accessToken:"",refreshToken:((e=t==null?void 0:t.initialContext)==null?void 0:e.refreshToken)??"",ignoreRefreshToken:!1,endpoints:((n=t==null?void 0:t.initialContext)==null?void 0:n.endpoints)??{login:"",logout:"",refresh:"",ssrRefresh:""},errors:[]}},initial:"refreshing",states:{authenticating:{invoke:{src:"authenticate",input:({context:t,event:e})=>e.type!=="LOGIN"?{context:t,username:"",password:""}:{context:t,username:e.username,password:e.password},onDone:[{actions:"setUserContext",target:"loggedIn"}],onError:[{actions:"addError",target:"loggedOut"}]}},unauthenticating:{invoke:{src:"unauthenticate",input:({context:t})=>({context:t}),onDone:[{actions:"unsetUserContext",target:"loggedOut"}],onError:[{actions:["unsetUserContext","setIgnoreRefreshToken"],target:"loggedOut"}]}},refreshing:{invoke:{src:"refreshAccessToken",input:({context:t})=>({context:t}),onDone:[{actions:["unsetRefreshToken","setAccessToken"],target:"loggedIn"}],onError:[{actions:"unsetRefreshToken",target:"unauthenticating"}]}},loggedOut:{on:{LOGIN:{target:"authenticating"},CLEAR_ERRORS:{actions:"clearErrors"}}},loggedIn:{after:{84e4:{guard:()=>typeof window<"u",target:"refreshing"}},on:{LOGOUT:{target:"unauthenticating"},CLEAR_ERRORS:{actions:"clearErrors"}}}}}),Kt=M.createContext({}),Dr=()=>{const t=M.useContext(Kt),[e,n]=M.useState(typeof window<"u"&&t.getSnapshot().value==="loggedIn");return M.useEffect(()=>{if(typeof window>"u")return;const s=t.subscribe(r=>{(r.value==="loggedIn"||r.value==="loggedOut")&&n(r.value==="loggedIn")});return()=>{s.unsubscribe()}},[t]),{authActor:t,isLoggedIn:e}},Mr=async(t="",e={inspect:void 0,endpoints:{login:"",logout:"",refresh:"",ssrRefresh:""}})=>typeof window<"u"?(console.warn("App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page."),L(kt,{inspect:e.inspect,input:{initialContext:{endpoints:e.endpoints}}}).start()):L(kt,{input:{initialContext:{endpoints:e.endpoints,refreshToken:t}},inspect:e.inspect}).start();function Ur({actor:t,children:e}){return _e.jsx(Kt.Provider,{value:t,children:e})}let jr=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,n)=>(n&=63,n<36?e+=n.toString(36):n<62?e+=(n-26).toString(36).toUpperCase():n>62?e+="-":e+="_",e),"");const un=Bt({actors:{tick:us(({sendBack:t,input:e})=>{const n=setInterval(()=>{t({type:"TICK"})},e.interval);return()=>{clearInterval(n)}})},types:{context:{},events:{},input:{}}}).createMachine({id:"timer",initial:"running",context:({input:t})=>({elapsed:0,duration:t.initialContext.duration??3e3,interval:100,intervalId:null}),states:{paused:{on:{RESUME_TIMER:{target:"running",guard:({context:t})=>t.elapsed<t.duration}}},running:{invoke:{input:({context:t})=>({interval:t.interval}),src:"tick"},always:[{target:"completed",guard:({context:t})=>t.elapsed>=t.duration}],on:{TICK:{actions:v(({context:t,event:e})=>e.type!=="TICK"?t:{elapsed:t.elapsed+t.interval})},PAUSE_TIMER:{target:"paused"}}},completed:{type:"final"}}}),Nr=Bt({actors:{timer:un},types:{context:{},events:{},input:{}},actions:{addItem:v(({context:t,event:e})=>{if(e.type!=="ADD_ITEM")return t;const n=`notification-${jr()}`,s=e.duration??t.duration,r=M.cloneElement(e.item,{duration:s,id:n,key:e.item.key??n,...e.item.props}),i={duration:s,id:n,element:r},o=t.items;return t.order==="desc"?o.push(i):o.unshift(i),{items:o,activeItem:n}}),removeItem:v(({context:t,event:e})=>{if(e.type!=="REMOVE_ITEM"&&e.type!=="xstate.done.actor.timer")return t;const n=t.items;return t.order==="desc"?(n.pop(),{items:n,activeItem:n.length>0?n[n.length-1].id:null}):(n.shift(),{items:n,activeItem:n.length>0?n[0].id:null})})},delays:{ITEM_TIMEOUT:({context:t})=>t.items[t.items.length-1].duration??t.duration},guards:{itemHasTimeout:({context:t})=>t.items[t.items.length-1].duration>0||t.duration>0}}).createMachine({id:"toast",context:{items:[],order:"desc",duration:0,activeItem:null},initial:"idle",states:{idle:{on:{ADD_ITEM:{target:"adding"}}},active:{invoke:{id:"timer",src:"timer",input:({context:t})=>({initialContext:{duration:t.items[t.items.length-1].duration??t.duration}}),onDone:{target:"removing",guard:"itemHasTimeout"}},on:{ADD_ITEM:{target:"adding"},REMOVE_ITEM:{target:"removing"},SET_IDLE:{target:"idle"},RESUME_TIMER:{actions:ce("timer",{type:"RESUME_TIMER"})},PAUSE_TIMER:{actions:ce("timer",{type:"PAUSE_TIMER"})}}},adding:{entry:["addItem"],on:{SET_IDLE:{target:"idle"},SET_ACTIVE:{target:"active"}}},removing:{entry:"removeItem",on:{SET_IDLE:{target:"idle"},SET_ACTIVE:{target:"active"}}}}}),Vt=M.createContext({}),$r=()=>M.useContext(Vt);function Lr({children:t,actor:e}){return _e.jsx(Vt.Provider,{value:e,children:t})}exports.AuthContext=Kt;exports.AuthProvider=Ur;exports.ToastContext=Vt;exports.ToastProvider=Lr;exports.authMachine=kt;exports.getAuth=Mr;exports.timerMachine=un;exports.toastMachine=Nr;exports.useAuth=Dr;exports.useToast=$r;
|
package/index.mjs
CHANGED
|
@@ -3685,13 +3685,13 @@ const ge = $t({
|
|
|
3685
3685
|
actors: {
|
|
3686
3686
|
refreshAccessToken: yt(async ({ input: t }) => {
|
|
3687
3687
|
let e;
|
|
3688
|
-
if (
|
|
3688
|
+
if (typeof window > "u") {
|
|
3689
3689
|
if (t.context.refreshToken === "")
|
|
3690
3690
|
throw new Error("Unauthorized.");
|
|
3691
3691
|
try {
|
|
3692
3692
|
const n = await Ur.post(
|
|
3693
3693
|
t.context.endpoints.ssrRefresh,
|
|
3694
|
-
{
|
|
3694
|
+
{},
|
|
3695
3695
|
{
|
|
3696
3696
|
headers: {
|
|
3697
3697
|
Cookie: `refresh_token=${t.context.refreshToken}`,
|
|
@@ -3710,8 +3710,8 @@ const ge = $t({
|
|
|
3710
3710
|
type: "REFRESH_TOKEN_SUCCESS",
|
|
3711
3711
|
accessToken: s.accessToken
|
|
3712
3712
|
};
|
|
3713
|
-
} catch {
|
|
3714
|
-
throw new Error("Could not complete refresh request (server)");
|
|
3713
|
+
} catch (n) {
|
|
3714
|
+
throw console.log(n), new Error("Could not complete refresh request (server)");
|
|
3715
3715
|
}
|
|
3716
3716
|
} else {
|
|
3717
3717
|
e = await me(
|