agentgui 1.0.931 → 1.0.932

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.
Files changed (128) hide show
  1. package/AGENTS.md +17 -12
  2. package/database.js +31 -2
  3. package/lib/http-handler.js +11 -25
  4. package/lib/routes-registry.js +4 -48
  5. package/lib/server-startup.js +3 -11
  6. package/lib/ws-setup.js +2 -1
  7. package/package.json +3 -3
  8. package/server.js +7 -1
  9. package/site/app/js/app.js +64 -68
  10. package/site/app/js/backend.js +1 -1
  11. package/static/lib/xstate.umd.min.js +1 -1
  12. package/lib/db-queries-chunks.js +0 -195
  13. package/lib/db-queries-chunks2.js +0 -82
  14. package/lib/db-queries-cleanup.js +0 -74
  15. package/lib/db-queries-del.js +0 -141
  16. package/lib/db-queries-events.js +0 -68
  17. package/lib/db-queries-import.js +0 -133
  18. package/lib/db-queries-messages.js +0 -102
  19. package/lib/db-queries-sessions.js +0 -112
  20. package/lib/db-queries-streams.js +0 -100
  21. package/lib/db-queries.js +0 -89
  22. package/lib/jsonl-parser.js +0 -190
  23. package/lib/jsonl-watcher.js +0 -64
  24. package/lib/routes-agent-actions.js +0 -61
  25. package/lib/routes-auth-config.js +0 -30
  26. package/lib/routes-conversations.js +0 -96
  27. package/lib/routes-debug.js +0 -119
  28. package/lib/routes-messages.js +0 -139
  29. package/lib/routes-runs.js +0 -156
  30. package/lib/routes-scripts.js +0 -135
  31. package/lib/routes-sessions.js +0 -144
  32. package/lib/routes-threads.js +0 -100
  33. package/lib/routes-util.js +0 -110
  34. package/lib/ws-handlers-conv.js +0 -138
  35. package/lib/ws-handlers-conv2.js +0 -169
  36. package/lib/ws-handlers-msg.js +0 -121
  37. package/lib/ws-handlers-queue.js +0 -56
  38. package/lib/ws-handlers-run.js +0 -182
  39. package/lib/ws-handlers-scripts.js +0 -66
  40. package/lib/ws-handlers-session.js +0 -105
  41. package/lib/ws-handlers-session2.js +0 -85
  42. package/lib/ws-legacy-handlers.js +0 -51
  43. package/static/app.js +0 -261
  44. package/static/css/app-shell.css +0 -419
  45. package/static/css/brand-bible.css +0 -591
  46. package/static/css/colors_and_type.css +0 -568
  47. package/static/css/gmail-skin.css +0 -663
  48. package/static/css/main.css +0 -4015
  49. package/static/css/tools-popup.css +0 -472
  50. package/static/index.html +0 -418
  51. package/static/js/agent-auth.js +0 -146
  52. package/static/js/app-shortcuts.js +0 -30
  53. package/static/js/audio-recorder-processor.js +0 -18
  54. package/static/js/client-agents.js +0 -155
  55. package/static/js/client-cache.js +0 -171
  56. package/static/js/client-conv.js +0 -198
  57. package/static/js/client-events.js +0 -164
  58. package/static/js/client-exec.js +0 -160
  59. package/static/js/client-helpers.js +0 -199
  60. package/static/js/client-load.js +0 -175
  61. package/static/js/client-render.js +0 -132
  62. package/static/js/client-scroll.js +0 -178
  63. package/static/js/client-status.js +0 -167
  64. package/static/js/client-streaming.js +0 -117
  65. package/static/js/client-streaming2.js +0 -116
  66. package/static/js/client-streaming3.js +0 -153
  67. package/static/js/client-streaming4.js +0 -194
  68. package/static/js/client-ui-controls.js +0 -170
  69. package/static/js/client-ui.js +0 -128
  70. package/static/js/client-ui2.js +0 -160
  71. package/static/js/client-url.js +0 -93
  72. package/static/js/client-utils.js +0 -174
  73. package/static/js/client-ws-msg.js +0 -88
  74. package/static/js/client-ws.js +0 -161
  75. package/static/js/client.js +0 -145
  76. package/static/js/codec.js +0 -4
  77. package/static/js/conv-list-machine.js +0 -145
  78. package/static/js/conv-list-renderer.js +0 -198
  79. package/static/js/conv-machine.js +0 -110
  80. package/static/js/conv-sidebar-actions.js +0 -188
  81. package/static/js/conv-sidebar-clone.js +0 -91
  82. package/static/js/conversations.js +0 -116
  83. package/static/js/dialogs-types.js +0 -111
  84. package/static/js/dialogs.js +0 -53
  85. package/static/js/event-filter-config.js +0 -36
  86. package/static/js/event-processor.js +0 -181
  87. package/static/js/features.js +0 -187
  88. package/static/js/image-loader-element.js +0 -76
  89. package/static/js/image-loader.js +0 -146
  90. package/static/js/prompt-machine.js +0 -108
  91. package/static/js/recording-machine.js +0 -49
  92. package/static/js/script-runner.js +0 -192
  93. package/static/js/state-barrier.js +0 -105
  94. package/static/js/streaming-renderer-dispatch.js +0 -144
  95. package/static/js/streaming-renderer-events.js +0 -163
  96. package/static/js/streaming-renderer-events2.js +0 -125
  97. package/static/js/streaming-renderer-params.js +0 -38
  98. package/static/js/streaming-renderer-render-misc.js +0 -107
  99. package/static/js/streaming-renderer-render.js +0 -181
  100. package/static/js/streaming-renderer-render2.js +0 -149
  101. package/static/js/streaming-renderer-render3.js +0 -142
  102. package/static/js/streaming-renderer-static.js +0 -181
  103. package/static/js/streaming-renderer-static2.js +0 -140
  104. package/static/js/streaming-renderer-stream.js +0 -170
  105. package/static/js/streaming-renderer-text.js +0 -185
  106. package/static/js/streaming-renderer-tools.js +0 -189
  107. package/static/js/streaming-renderer-tools2.js +0 -92
  108. package/static/js/streaming-renderer.js +0 -200
  109. package/static/js/syntax-highlighter-render.js +0 -72
  110. package/static/js/syntax-highlighter.js +0 -131
  111. package/static/js/terminal-machine.js +0 -51
  112. package/static/js/terminal.js +0 -178
  113. package/static/js/ui-components-rendering.js +0 -62
  114. package/static/js/ui-components.js +0 -88
  115. package/static/js/websocket-manager.js +0 -107
  116. package/static/js/ws-client.js +0 -87
  117. package/static/js/ws-core.js +0 -162
  118. package/static/js/ws-latency.js +0 -88
  119. package/static/js/ws-machine.js +0 -68
  120. package/static/lib/msgpackr.min.js +0 -2
  121. package/static/theme.js +0 -74
  122. package/static/vendor/highlight-js.css +0 -10
  123. package/static/vendor/highlight.min.js +0 -1244
  124. package/static/vendor/prism-dark.css +0 -129
  125. package/static/vendor/rippleui.css +0 -35
  126. package/static/vendor/xterm-addon-fit.min.js +0 -8
  127. package/static/vendor/xterm.css +0 -8
  128. package/static/vendor/xterm.min.js +0 -8
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XState={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="xstate.init",n="xstate.stop";function o(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const i=t=>{const e=o();e&&e.register(t)};function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function a(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function c(t){return{type:s,input:t}}function u(t){setTimeout(()=>{throw t})}const h="function"==typeof Symbol&&Symbol.observable||"@@observable";function f(t,e){const s=p(t),n=p(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&f(s[t],n[t]))}function d(t){if(_(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function p(t){if(Ct(t))return t.value;if("string"!=typeof t)return t;return l(d(t))}function l(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}function y(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}function g(t){return _(t)?t:[t]}function v(t){return void 0===t?[]:g(t)}function m(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function _(t){return Array.isArray(t)}function b(t){return g(t).map(t=>void 0===t||"string"==typeof t?{target:t}:t)}function x(t){if(void 0!==t&&""!==t)return v(t)}function S(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function w(t,e){return`${e}.${t}`}function I(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function E(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function k(t,e){return`${t.sessionId}.${e}`}let $=0;let T=!1;let O=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const j={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class A{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=O.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const n={...j,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:c,systemId:h,inspect:f}=n;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:a,logger:c}=e,u={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},c=k(t,o);h._snapshot._scheduledEvents[c]=i;const u=a.setTimeout(()=>{delete r[c],delete h._snapshot._scheduledEvents[c],h._relay(t,e,s)},n);r[c]=u},cancel:(t,e)=>{const s=k(t,e),n=r[s];delete r[s],delete h._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in h._snapshot._scheduledEvents){const s=h._snapshot._scheduledEvents[e];s.source===t&&u.cancel(t,s.id)}}},h={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+$++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),getAll:()=>Object.fromEntries(n.entries()),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=S(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const t=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];u.schedule(s,n,o,i,r)}},_clock:a,_logger:c};return h}(this,{clock:o,logger:i}),f&&!r&&this.system.inspect(S(f)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(!e&&!s)return;const n=[...e?e.values():[],...s?s.values():[]];for(const e of n)try{e(t)}catch(t){u(t)}},actionExecutor:t=>{const e=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:t.type,params:t.params}}),!t.exec)return;const e=T;try{T=!0,t.exec(t.info,t.params)}finally{T=e}};this._processingStatus===O.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),h&&(this.systemId=h,this.system._set(h,this)),this._initState(s?.snapshot??s?.state),h&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=S(t,e,s);if(this._processingStatus!==O.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){u(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){u(t)}else u(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}select(t,e=Object.is){return{subscribe:s=>{const n=S(s),o=this.getSnapshot();let i=t(o);return this.subscribe(s=>{const o=t(s);e(i,o)||(i=o,n.next?.(o))})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===O.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=O.Running;const t=c(this.options.input);this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===O.Stopped?this:(this.mailbox.clear(),this._processingStatus===O.NotStarted?(this._processingStatus=O.Stopped,this):(this.mailbox.enqueue({type:n}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){u(t)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size)return this._parent||u(t),void this.eventListeners.clear();let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){u(t)}}this.observers.clear(),this.eventListeners.clear(),e&&u(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,a(this.id,t))}_stopProcedure(){return this._processingStatus!==O.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=O.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==O.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:i)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[h](){return this}getSnapshot(){return this._snapshot}}function M(t,...[e]){return new A(t,e)}const N=M;function P(t,e,s,n,{sendId:o}){return[e,{sendId:"function"==typeof o?o(s,n):o},void 0]}function C(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function R(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=P,e.execute=C,e}function V(t,e,s,n,{id:o,systemId:i,src:r,input:a,syncSnapshot:c}){const u="string"==typeof r?I(e.machine,r):r,h="function"==typeof o?o(s):o;let f,d;return u&&(d="function"==typeof a?a({context:e.context,event:s.event,self:t.self}):a,f=M(u,{id:h,src:r,parent:t.self,syncSnapshot:c,systemId:i,input:d})),[qt(e,{children:{...e.children,[h]:f}}),{id:o,systemId:i,actorRef:f,src:r,input:d},void 0]}function D(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==O.Stopped&&e.start()})}function J(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="xstate.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=V,i.execute=D,i}function B(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let a=e.children;return r&&(a={...a},delete a[r.id]),[qt(e,{children:a}),r,void 0]}function L(t,e){const s=e.getSnapshot();if(s&&"children"in s)for(const e of Object.values(s.children))L(t,e);t.system._unregister(e)}function q(t,e){e&&(L(t,e),e._processingStatus===O.Running?t.defer(()=>{t.stopChild(e)}):t.stopChild(e))}function z(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=B,e.execute=q,e}const W=z;function U(t,e,{stateValue:s}){if("string"==typeof s&&ot(s)){const e=t.machine.getStateNodeById(s);return t._nodes.some(t=>t===e)}return t.matches(s)}function Q(t,{context:e,event:s},{guards:n}){return!X(n[0],e,s,t)}function F(t,{context:e,event:s},{guards:n}){return n.every(n=>X(n,e,s,t))}function G(t,{context:e,event:s},{guards:n}){return n.some(n=>X(n,e,s,t))}function X(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return X(r,e,s,n);const a={context:e,event:s},c=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(a,c);return r.check(n,a,r)}function H(t){return"atomic"===t.type||"final"===t.type}function K(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Y(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function Z(t){const e=new Set(t),s=et(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of K(t))if("history"!==s.type&&!e.has(s)){const t=ut(s);for(const s of t)e.add(s)}}else ut(t).forEach(t=>e.add(t));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function tt(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(H(t))return t.key}const n={};for(const t of s)n[t.key]=tt(t,e);return n}function et(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function st(t,e){return tt(t,et(Z(e)))}function nt(t,e){return"compound"===e.type?K(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?K(e).every(e=>nt(t,e)):"final"===e.type}const ot=t=>"#"===t[0];function it(t){const e=t.config.after;if(!e)return[];const s=Object.keys(e).flatMap(s=>{const n=e[s],o="string"==typeof n?{target:n}:n,i=Number.isNaN(+s)?s:+s,r=(e=>{const s=(n=e,o=t.id,{type:`xstate.after.${n}.${o}`});var n,o;const i=s.type;return t.entry.push(Zt(s,{id:i,delay:e})),t.exit.push(R(i)),i})(i);return v(o).map(t=>({...t,event:r,delay:i}))});return s.map(e=>{const{delay:s}=e;return{...rt(t,e.event,e),delay:s}})}function rt(t,e,s){const n=x(s.target),o=s.reenter??!1,i=function(t,e){if(void 0===e)return;return e.map(e=>{if("string"!=typeof e)return e;if(ot(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return dt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`);try{return dt(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}(t,n),r={...s,actions:v(s.actions),guard:s.guard,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function at(t){const e=x(t.config.target);return e?{target:e.map(e=>"string"==typeof e?dt(t.parent,e):e)}:t.parent.initial}function ct(t){return"history"===t.type}function ut(t){const e=ht(t);for(const s of e)for(const n of Y(s,t))e.add(n);return e}function ht(t){const e=new Set;return function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of K(s))t(e)}(t),e}function ft(t,e){if(ot(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 s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function dt(t,e){if("string"==typeof e&&ot(e))try{return t.machine.getStateNodeById(e)}catch{}const s=d(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=ft(n,t)}return n}function pt(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=s.map(e=>ft(t,e)).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce((s,n)=>{const o=ft(t,n);if(!o)return s;const i=pt(o,e[n]);return s.concat(i)},[]))}function lt(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=ft(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=lt(ft(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const a=lt(ft(t,i),r,s,n);a&&o.push(...a)}return o.length?o:t.next(s,n)}(t,e,s,n)}function yt(t){return Object.keys(t.states).map(e=>t.states[e]).filter(t=>"history"===t.type)}function gt(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function vt(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function mt(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(vt(xt([o],e,s),xt([r],e,s))){if(!gt(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function _t(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(ct(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of _t(at(n),e))s.add(t);else s.add(n);return[...s]}function bt(t,e){const s=_t(t,e);if(!s)return;if(!t.reenter&&s.every(e=>e===t.source||gt(e,t.source)))return t.source;const n=function(t){const[e,...s]=t;for(const t of Y(e,void 0))if(s.every(e=>gt(e,t)))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function xt(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=bt(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)gt(s,t)&&n.add(s)}return[...n]}function St(t,e,s,n,o){return wt([{target:[...ht(t)],source:t,reenter:!0,actions:[],eventType:null,toJSON:null}],e,s,n,!0,o)}function wt(t,e,s,n,o,i){const a=[];if(!t.length)return[e,a];const c=s.actionExecutor;s.actionExecutor=t=>{a.push(t),c(t)};try{const c=new Set(e._nodes);let u=e.historyValue;const h=mt(t,c,u);let f=e;o||([f,u]=function(t,e,s,n,o,i,r){let a=t;const c=xt(n,o,i);let u;c.sort((t,e)=>e.order-t.order);for(const t of c)for(const e of yt(t)){let s;s="deep"===e.history?e=>H(e)&&gt(e,t):e=>e.parent===t,u??={...i},u[e.id]=Array.from(o).filter(s)}for(const t of c)a=jt(a,e,s,[...t.exit,...t.invoke.map(t=>z(t.id))],r,void 0),o.delete(t);return[a,u||i]}(f,n,s,h,c,u,i,s.actionExecutor)),f=jt(f,n,s,h.flatMap(t=>t.actions),i,void 0),f=function(t,e,s,n,o,i,a,c){let u=t;const h=new Set,f=new Set;(function(t,e,s,n){for(const o of t){const t=bt(o,e);for(const i of o.target||[])ct(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),Et(i,e,s,n);const i=_t(o,e);for(const r of i){const i=Y(r,t);"parallel"===t?.type&&i.push(t),kt(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,a,f,h),c&&f.add(t.machine.root);const d=new Set;for(const t of[...h].sort((t,e)=>t.order-e.order)){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(J(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(f.has(t)){const e=t.initial.actions;n.push(...e)}if(u=jt(u,e,s,n,i,t.invoke.map(t=>t.id)),"final"===t.type){const n=t.parent;let a="parallel"===n?.type?n:n?.parent,c=a||t;for("compound"===n?.type&&i.push(r(n.id,void 0!==t.output?m(t.output,u.context,e,s.self):void 0));"parallel"===a?.type&&!d.has(a)&&nt(o,a);)d.add(a),i.push(r(a.id)),c=a,a=a.parent;if(a)continue;u=qt(u,{status:"done",output:It(u,e,s,u.machine.root,c)})}}return u}(f,n,s,h,c,i,u,o);const d=[...c];"done"===f.status&&(f=jt(f,n,s,d.sort((t,e)=>e.order-t.order).flatMap(t=>t.exit),i,void 0));try{return u===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,c)?[f,a]:[qt(f,{_nodes:d,historyValue:u}),a]}catch(t){throw t}}finally{s.actionExecutor=c}}function It(t,e,s,n,o){if(void 0===n.output)return;const i=r(o.id,void 0!==o.output&&o.parent?m(o.output,t.context,e,s.self):void 0);return m(n.output,t.context,i,s.self)}function Et(t,e,s,n){if(ct(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),Et(t,e,s,n);for(const i of o)$t(i,t.parent,n,e,s)}else{const o=at(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),Et(i,e,s,n);for(const i of o.target)$t(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;ct(o)||(n.add(o),s.add(o)),Et(o,e,s,n),$t(o,t,n,e,s)}else if("parallel"===t.type)for(const o of K(t).filter(t=>!ct(t)))[...n].some(t=>gt(t,o))||(ct(o)||(n.add(o),s.add(o)),Et(o,e,s,n))}function kt(t,e,s,n,o){for(const i of n)if(o&&!gt(i,o)||t.add(i),"parallel"===i.type)for(const n of K(i).filter(t=>!ct(t)))[...t].some(t=>gt(t,n))||(t.add(n),Et(n,e,s,t))}function $t(t,e,s,n,o){kt(s,n,o,Y(t,e))}function Tt(t,e){return t.implementations.actions[e]}function Ot(t,e,s,n,o,i){const{machine:r}=t;let a=t;for(const t of n){const n="function"==typeof t,c=n?t:Tt(r,"string"==typeof t?t:t.type),u={context:a.context,event:e,self:s.self,system:s.system},h=n||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:a.context,event:e}):t.params:void 0;if(!c||!("resolve"in c)){s.actionExecutor({type:"string"==typeof t?t:"object"==typeof t?t.type:t.name||"(anonymous)",info:u,params:h,exec:c});continue}const f=c,[d,p,l]=f.resolve(s,a,u,h,c,o);a=d,"retryResolve"in f&&i?.push([f,p]),"execute"in f&&s.actionExecutor({type:f.type,info:u,params:p,exec:f.execute.bind(null,s,p)}),l&&(a=Ot(a,e,s,l,o,i))}return a}function jt(t,e,s,n,o,i){const r=i?[]:void 0,a=Ot(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach(([t,e])=>{t.retryResolve(s,a,e)}),a}function At(t,e,o,i){let r=t;const a=[];function c(t,e,s){o.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:o.self,event:e,snapshot:t[0],_transitions:s}),a.push(t)}if(e.type===n)return r=qt(Mt(r,e,o),{status:"stopped"}),c([r,[]],e,[]),{snapshot:r,microsteps:a};let u=e;if(u.type!==s){const e=u,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=Nt(e,r);if(s&&!n.length)return r=qt(t,{status:"error",error:e.error}),c([r,[]],e,[]),{snapshot:r,microsteps:a};const h=wt(n,t,o,u,!1,i);r=h[0],c(h,e,n)}let h=!0;const f=t.machine.options?.maxIterations??1/0;let d=0;for(;"active"===r.status;){if(d++,d>f)throw new Error(`Infinite loop detected: the machine has processed more than ${f} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`);let t=h?Pt(r,u):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;u=i.shift(),t=Nt(u,r)}const s=wt(t,r,o,u,!1,i);r=s[0],h=r!==e,c(s,u,t)}return"active"!==r.status&&Mt(r,u,o),{snapshot:r,microsteps:a}}function Mt(t,e,s){return jt(t,e,s,Object.values(t.children).map(t=>z(t)),[],void 0)}function Nt(t,e){return e.machine.getTransitionData(e,t)}function Pt(t,e){const s=new Set,n=t._nodes.filter(H);for(const o of n)t:for(const n of[o].concat(Y(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||X(o.guard,t.context,e,t)){s.add(o);break t}return mt(Array.from(s),new Set(t._nodes),t.historyValue)}function Ct(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Rt=function(t){return f(t,this.value)},Vt=function(t){return this.tags.has(t)},Dt=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some(t=>void 0!==t.target||t.actions.length)},Jt=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:a,...c}=this;return{...c,tags:Array.from(e)}},Bt=function(){return this._nodes.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{})};function Lt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:st(e.root,t._nodes),tags:new Set(t._nodes.flatMap(t=>t.tags)),children:t.children,historyValue:t.historyValue||{},matches:Rt,hasTag:Vt,can:Dt,getMeta:Bt,toJSON:Jt}}function qt(t,e={}){return Lt({...t,...e},t.machine)}function zt(t){if("object"!=typeof t||null===t)return{};const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function Wt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:1,id:n.id};else{const o=Wt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function Ut(t,{machine:e,context:s},n,o){return(i,r)=>{const a=((i,r)=>{if("string"==typeof i){const a=I(e,i);if(!a)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=M(a,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[c.id]=c,c}return M(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[a.id]=a,t.defer(()=>{a._processingStatus!==O.Stopped&&a.start()}),a}}function Qt(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:Ut(t,e,s.event,i),self:t.self,system:t.system};let a={};if("function"==typeof o)a=o(r,n);else for(const t of Object.keys(o)){const e=o[t];a[t]="function"==typeof e?e(r,n):e}return[qt(e,{context:Object.assign({},e.context,a),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function Ft(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=Qt,e}function Gt(t,e,s,n,{event:o}){return[e,{event:"function"==typeof o?o(s,n):o},void 0]}function Xt(t,{event:e}){t.defer(()=>t.emit(e))}function Ht(t){function e(t,e){}return e.type="xstate.emit",e.event=t,e.resolve=Gt,e.execute=Xt,e}function Kt(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:a}){const c=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const u="function"==typeof o?o(s,n):o;let h;if("string"==typeof r){const t=c&&c[r];h="function"==typeof t?t(s,n):t}else h="function"==typeof r?r(s,n):r;return"number"!=typeof h&&a.push(u),[e,{event:u,id:i,delay:h},void 0]}function Yt(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer(()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)})}function Zt(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=Kt,s.execute=Yt,s}let te=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function ee(t,e,s,n,{to:o,event:i,id:r,delay:a},c){const u=e.machine.implementations.delays;if("string"==typeof i)throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const h="function"==typeof i?i(s,n):i;let f;if("string"==typeof a){const t=u&&u[a];f="function"==typeof t?t(s,n):t}else f="function"==typeof a?a(s,n):a;const d="function"==typeof o?o(s,n):o;let p;if("string"==typeof d){if(p=d===te.Parent?t.self._parent:d===te.Internal?t.self:d.startsWith("#_")?e.children[d.slice(2)]:c.deferredActorIds?.includes(d)?d:e.children[d],!p)throw new Error(`Unable to send event to actor '${d}' from machine '${e.machine.id}'.`)}else p=d||t.self;return[e,{to:p,targetId:"string"==typeof d?d:void 0,event:h,id:r,delay:f},void 0]}function se(t,e,s){"string"==typeof s.to&&(s.to=e.children[s.to])}function ne(t,e){t.defer(()=>{const{to:s,event:n,delay:o,id:i}=e;"number"!=typeof o?t.system._relay(t.self,s,"xstate.error"===n.type?a(t.self.id,n.data):n):t.system.scheduler.schedule(t.self,s,n,o,i)})}function oe(t,e,s){function n(t,e){}return n.type="xstate.sendTo",n.to=t,n.event=e,n.id=s?.id,n.delay=s?.delay,n.resolve=ee,n.retryResolve=se,n.execute=ne,n}function ie(t,e){return oe(te.Parent,t,e)}function re(t,e,s,n,{collect:o}){const i=[],r=function(t){i.push(t)};return r.assign=(...t)=>{i.push(Ft(...t))},r.cancel=(...t)=>{i.push(R(...t))},r.raise=(...t)=>{i.push(Zt(...t))},r.sendTo=(...t)=>{i.push(oe(...t))},r.sendParent=(...t)=>{i.push(ie(...t))},r.spawnChild=(...t)=>{i.push(J(...t))},r.stopChild=(...t)=>{i.push(z(...t))},r.emit=(...t)=>{i.push(Ht(...t))},o({context:s.context,event:s.event,enqueue:r,check:t=>X(t,e.context,s.event,e),self:t.self,system:t.system},n),[e,void 0,i]}function ae(t){function e(t,e){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=re,e}function ce(t,e,s,n,{value:o,label:i}){return[e,{value:"function"==typeof o?o(s,n):o,label:i},void 0]}function ue({logger:t},{value:e,label:s}){s?t(s,e):t(e)}function he(t=({context:t,event:e})=>({context:t,event:e}),e){function s(t,e){}return s.type="xstate.log",s.value=t,s.label=e,s.resolve=ce,s.execute=ue,s}function fe(t,e){return{config:t,transition:(e,s,n)=>({...e,context:t(e.context,s,n)}),getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof e?e({input:s}):e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const de=new WeakMap;const pe="xstate.observable.next",le="xstate.observable.error",ye="xstate.observable.complete";const ge="xstate.promise.resolve",ve="xstate.promise.reject",me=new WeakMap;const _e=fe(t=>{},void 0);const be=new WeakMap;function xe(t,e,s){let n=be.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},be.set(t,n)),n[e]}const Se={},we=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class Ie{constructor(t,e){if(this.config=t,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=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join("."),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?y(this.config.states,(t,e)=>new Ie(t,{_parent:this,_key:e,_machine:this.machine})):Se,"compound"===this.type&&!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=!0===this.config.history?"shallow":this.config.history||!1,this.entry=v(this.config.entry).slice(),this.exit=v(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=v(t.tags).slice()}_initialize(){this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,b(n).map(e=>rt(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,b(t.config.onDone).map(e=>rt(t,s,e)))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,b(s.onDone).map(e=>rt(t,n,e)))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,b(s.onError).map(e=>rt(t,n,e)))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,b(s.onSnapshot).map(e=>rt(t,n,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),this.config.always&&(this.always=b(this.config.always).map(t=>rt(this,"",t))),Object.keys(this.states).forEach(t=>{this.states[t]._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(we),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(we),eventType:null})}:void 0,history:this.history,states:y(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(we)})),entry:this.entry.map(we),exit:this.exit.map(we),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 xe(this,"invoke",()=>v(this.config.invoke).map((t,e)=>{const{src:s,systemId:n}=t,o=t.id??w(this.id,e),i="string"==typeof s?s:`xstate.invoke.${w(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:"xstate.invoke",src:i,id:o}}}}))}get on(){return xe(this,"on",()=>[...this.transitions].flatMap(([t,e])=>e.map(e=>[t,e])).reduce((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t),{}))}get after(){return xe(this,"delayedTransitions",()=>it(this))}get initial(){return xe(this,"initial",()=>function(t,e){const s="string"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const n={source:t,actions:e&&"string"!=typeof e?v(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial))}next(t,e){const s=e.type,n=[];let o;const i=xe(this,`candidates-${s}`,()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter(t=>E(e,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));var t,e});for(const r of i){const{guard:i}=r,a=t.context;let c=!1;try{c=!i||X(i,a,e,t)}catch(t){const e="string"==typeof i?i:"object"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:""}in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(c){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return xe(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)})}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),e=new Set(t.filter(t=>this.transitions.get(t).some(t=>!(!t.target&&!t.actions.length&&!t.reenter))));return Array.from(e)}}class Ee{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=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.id=t.id||"(machine)",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.options={maxIterations:1/0,...this.config.options},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 Ie(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const s=n.config.id,o=n.config.route.guard,i=(t,e)=>t.event.to===`#${s}`&&(!o||"function"!=typeof o||o(t,e)),r={...n.config.route,guard:i,target:`#${s}`};e.push(rt(t,"xstate.route",r))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new Ee(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,st(s,[...Z(pt(s,n))]));var s,n;const o=Z(pt(this.root,e));return Lt({_nodes:[...o],context:t.context||{},children:{},status:nt(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return At(t,e,s,[]).snapshot}microstep(t,e,s){return At(t,e,s,[]).microsteps.map(([t])=>t)}getTransitionData(t,e){return lt(this.root,t.value,t,e)||[]}_getPreInitialState(t,e,s){const{context:n}=this.config,o=Lt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return jt(o,e,t,[Ft(({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s}))],s,void 0)}return o}getInitialSnapshot(t,e){const s=c(e),n=[],o=this._getPreInitialState(t,s,n),[i]=St(this.root,o,t,s,n),{snapshot:r}=At(i,s,t,n);return r}start(t){Object.values(t.children).forEach(t=>{"active"===t.getSnapshot().status&&t.start()})}getStateNodeById(t){const e=d(t),s=e.slice(1),n=ot(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return dt(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:a,hasTag:c,matches:u,getMeta:h,toJSON:f,...d}=t,p={};for(const t in i){const s=i[t];p[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}return{...d,context:Wt(r),children:p,historyValue:zt(d.historyValue)}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;function o(t,e){if(e instanceof Ie)return e;try{return t.machine.getStateNodeById(e.id)}catch{}}Object.keys(n).forEach(t=>{const o=n[t],i=o.snapshot,r=o.src,a="string"==typeof r?I(this,r):r;if(!a)return;const c=M(a,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=c});const i=function(t,e){if(!e||"object"!=typeof e)return{};const s={};for(const n in e){const i=e[n];for(const e of i){const i=o(t,e);i&&(s[n]??=[],s[n].push(i))}}return s}(this.root,t.historyValue),r=Lt({...t,children:s,_nodes:Array.from(Z(pt(this.root,t.value))),historyValue:i},this),a=new Set;return function t(e,s){if(!a.has(e)){a.add(e);for(const n in e){const o=e[n];if(o&&"object"==typeof o){if("xstate$$type"in o&&1===o.xstate$$type){e[n]=s[o.id];continue}t(o,s)}}}}(r.context,s),r}}function ke(t,e){return new Ee(t,e)}function $e(t){const e=M(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}const Te={timeout:1/0};t.Actor=A,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const s=this.getId();return this.timeouts.set(s,{start:this.now(),timeout:e,fn:t}),s}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort(([t,e],[s,n])=>{const o=e.start+e.timeout;return n.start+n.timeout>o?-1:1});for(const[e,s]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-s.start>=s.timeout&&(this.timeouts.delete(e),s.fn.call(null))}this._flushing=!1}increment(t){this._now+=t,this.flushTimeouts()}},t.SpecialTargets=te,t.StateMachine=Ee,t.StateNode=Ie,t.__unsafe_getAllOwnEventDescriptors=function(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]},t.and=function(t){function e(t,e){return!1}return e.check=F,e.guards=t,e},t.assertEvent=function(t,e){const s=v(e);if(!s.some(e=>E(t.type,e))){const e=1===s.length?`type matching "${s[0]}"`:`one of types matching "${s.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}},t.assign=Ft,t.cancel=R,t.createActor=M,t.createEmptyActor=function(){return M(_e)},t.createMachine=ke,t.emit=Ht,t.enqueueActions=ae,t.forwardTo=function(t,e){return oe(t,({event:t})=>t,e)},t.fromCallback=function(t){const e={config:t,start:(e,s)=>{const{self:n,system:o,emit:i}=s,r={receivers:void 0,dispose:void 0};de.set(n,r),r.dispose=t({input:e.input,system:o,self:n,sendBack:t=>{"stopped"!==n.getSnapshot().status&&n._parent&&o._relay(n,n._parent,t)},receive:t=>{r.receivers??=new Set,r.receivers.add(t)},emit:i})},transition:(t,e,s)=>{const o=de.get(s.self);return e.type===n?(t={...t,status:"stopped",error:void 0},de.delete(s.self),o.receivers?.clear(),o.dispose?.(),t):(o.receivers?.forEach(t=>t(e)),t)},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromEventObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case le:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case ye:return{...t,status:"done",input:void 0,_subscription:void 0};case n:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:le,data:t})},complete:()=>{n._relay(s,s,{type:ye})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case pe:return{...t,context:e.data};case le:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case ye:return{...t,status:"done",input:void 0,_subscription:void 0};case n:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{n._relay(s,s,{type:pe,data:t})},error:t=>{n._relay(s,s,{type:le,data:t})},complete:()=>{n._relay(s,s,{type:ye})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromPromise=function(t){const e={config:t,transition:(t,e,s)=>{if("active"!==t.status)return t;switch(e.type){case ge:{const s=e.data;return{...t,status:"done",output:s,input:void 0}}case ve:return{...t,status:"error",error:e.data,input:void 0};case n:return me.get(s.self)?.abort(),me.delete(s.self),{...t,status:"stopped",input:void 0};default:return t}},start:(e,{self:s,system:n,emit:o})=>{if("active"!==e.status)return;const i=new AbortController;me.set(s,i);Promise.resolve(t({input:e.input,system:n,self:s,signal:i.signal,emit:o})).then(t=>{"active"===s.getSnapshot().status&&(me.delete(s),n._relay(s,s,{type:ge,data:t}))},t=>{"active"===s.getSnapshot().status&&(me.delete(s),n._relay(s,s,{type:ve,data:t}))})},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromTransition=fe,t.getInitialMicrosteps=function(t,...[e]){const s=$e(t),n=c(e),o=[],i=t._getPreInitialState(s,n,o),r=St(t.root,i,s,n,o),{microsteps:a}=At(r[0],n,s,o);return[r,...a]},t.getInitialSnapshot=function(t,...[e]){const s=$e(t);return t.getInitialSnapshot(s,e)},t.getMicrosteps=function(t,e,s){const n=$e(t),{microsteps:o}=At(e,s,n,[]);return o},t.getNextSnapshot=function(t,e,s){const n=$e(t);return n.self._snapshot=e,t.transition(e,s,n)},t.getNextTransitions=function(t){const e=[],s=t._nodes.filter(H),n=new Set;for(const t of s)for(const s of[t].concat(Y(t,void 0)))if(!n.has(s.id)){n.add(s.id);for(const[,t]of s.transitions)e.push(...t);s.always&&e.push(...s.always)}return e},t.getStateNodes=pt,t.initialTransition=function(t,...[e]){const s=[],n=$e(t);return n.actionExecutor=t=>{s.push(t)},[t.getInitialSnapshot(n,e),s]},t.interpret=N,t.isMachineSnapshot=Ct,t.log=he,t.mapState=function(t,e){const s=[],n=(t,e)=>{let s=t;for(const t of e){if(!s?.states)return;const e=s.states;if(!(t in e))return;s=e[t]}return s},o=new Set;for(const i of t._nodes.filter(H)){let r=i;for(;r&&!o.has(r);){o.add(r);const i=n(e,r.path);i?.map&&s.push({stateNode:r,result:i.map(t)}),r=r.parent}}return s},t.matchesState=f,t.not=function(t){function e(t,e){return!1}return e.check=Q,e.guards=[t],e},t.or=function(t){function e(t,e){return!1}return e.check=G,e.guards=t,e},t.pathToStateValue=l,t.raise=Zt,t.sendParent=ie,t.sendTo=oe,t.setup=function t({schemas:e,actors:s,actions:n,guards:o,delays:i}){return{assign:Ft,sendTo:oe,raise:Zt,log:he,cancel:R,stopChild:z,enqueueActions:ae,emit:Ht,spawnChild:J,createStateConfig:t=>t,createAction:t=>t,createMachine:t=>ke({...t,schemas:e},{actors:s,actions:n,guards:o,delays:i}),extend:r=>t({schemas:e,actors:s,actions:{...n,...r.actions},guards:{...o,...r.guards},delays:{...i,...r.delays}})}},t.spawnChild=J,t.stateIn=function(t){function e(){return!1}return e.check=U,e.stateValue=t,e},t.stop=W,t.stopChild=z,t.toObserver=S,t.toPromise=function(t){return new Promise((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})})},t.transition=function(t,e,s){const n=[],o=$e(t);return o.actionExecutor=t=>{n.push(t)},[t.transition(e,s,o),n]},t.waitFor=function(t,e,s){const n={...Te,...s};return new Promise((s,o)=>{const{signal:i}=n;if(i?.aborted)return void o(i.reason);let r=!1;const a=n.timeout===1/0?void 0:setTimeout(()=>{c(),o(new Error(`Timeout of ${n.timeout} ms exceeded`))},n.timeout),c=()=>{clearTimeout(a),r=!0,f?.unsubscribe(),h&&i.removeEventListener("abort",h)};function u(t){e(t)&&(c(),s(t))}let h,f;u(t.getSnapshot()),r||(i&&(h=()=>{c(),o(i.reason)},i.addEventListener("abort",h)),f=t.subscribe({next:u,error:t=>{c(),o(t)},complete:()=>{c(),o(new Error("Actor terminated without satisfying predicate"))}}),r&&f.unsubscribe())})},Object.defineProperty(t,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XState={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="xstate.init",n="xstate.stop";function o(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const i=t=>{const e=o();e&&e.register(t)};function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function a(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function c(t){return{type:s,input:t}}function u(t){setTimeout(()=>{throw t})}const h="function"==typeof Symbol&&Symbol.observable||"@@observable";function f(t,e){const s=p(t),n=p(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&f(s[t],n[t]))}function d(t){if(_(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function p(t){if(Rt(t))return t.value;if("string"!=typeof t)return t;return l(d(t))}function l(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}function y(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}function g(t){return _(t)?t:[t]}function v(t){return void 0===t?[]:g(t)}function m(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function _(t){return Array.isArray(t)}function b(t){return g(t).map(t=>void 0===t||"string"==typeof t?{target:t}:t)}function x(t){if(void 0!==t&&""!==t)return v(t)}function S(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function w(t,e){return`${e}.${t}`}function I(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function E(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function k(t,e){return`${t.sessionId}.${e}`}let $=0;let T=!1;let O=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const j={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class A{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=O.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const n={...j,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:c,systemId:h,inspect:f}=n;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:a,logger:c}=e,u={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},c=k(t,o);h._snapshot._scheduledEvents[c]=i;const u=a.setTimeout(()=>{delete r[c],delete h._snapshot._scheduledEvents[c],h._relay(t,e,s)},n);r[c]=u},cancel:(t,e)=>{const s=k(t,e),n=r[s];delete r[s],delete h._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in h._snapshot._scheduledEvents){const s=h._snapshot._scheduledEvents[e];s.source===t&&u.cancel(t,s.id)}}},h={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+$++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),getAll:()=>Object.fromEntries(n.entries()),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=S(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const t=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];u.schedule(s,n,o,i,r)}},_clock:a,_logger:c};return h}(this,{clock:o,logger:i}),f&&!r&&this.system.inspect(S(f)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(!e&&!s)return;const n=[...e?e.values():[],...s?s.values():[]];for(const e of n)try{e(t)}catch(t){u(t)}},actionExecutor:t=>{const e=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:t.type,params:t.params}}),!t.exec)return;const e=T;try{T=!0,t.exec(t.info,t.params)}finally{T=e}};this._processingStatus===O.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),h&&(this.systemId=h,this.system._set(h,this)),this._initState(s?.snapshot??s?.state),h&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=S(t,e,s);if(this._processingStatus!==O.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){u(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){u(t)}else u(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}select(t,e=Object.is){return{subscribe:s=>{const n=S(s),o=this.getSnapshot();let i=t(o);return this.subscribe(s=>{const o=t(s);e(i,o)||(i=o,n.next?.(o))})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===O.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=O.Running;const t=c(this.options.input);this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===O.Stopped?this:(this.mailbox.clear(),this._processingStatus===O.NotStarted?(this._processingStatus=O.Stopped,this):(this.mailbox.enqueue({type:n}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){u(t)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size)return this._parent||u(t),void this.eventListeners.clear();let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){u(t)}}this.observers.clear(),this.eventListeners.clear(),e&&u(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,a(this.id,t))}_stopProcedure(){return this._processingStatus!==O.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=O.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==O.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:i)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[h](){return this}getSnapshot(){return this._snapshot}}function M(t,...[e]){return new A(t,e)}const N=M;function P(t,e,s,n,{sendId:o}){return[e,{sendId:"function"==typeof o?o(s,n):o},void 0]}function C(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function R(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=P,e.execute=C,e}function V(t,e,s,n,{id:o,systemId:i,src:r,input:a,syncSnapshot:c}){const u="string"==typeof r?I(e.machine,r):r,h="function"==typeof o?o(s):o;let f,d;return u&&(d="function"==typeof a?a({context:e.context,event:s.event,self:t.self}):a,f=M(u,{id:h,src:r,parent:t.self,syncSnapshot:c,systemId:i,input:d})),[zt(e,{children:{...e.children,[h]:f}}),{id:o,systemId:i,actorRef:f,src:r,input:d},void 0]}function D(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==O.Stopped&&e.start()})}function J(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="xstate.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=V,i.execute=D,i}function B(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let a=e.children;return r&&(a={...a},delete a[r.id]),[zt(e,{children:a}),r,void 0]}function L(t,e){const s=e.getSnapshot();if(s&&"children"in s)for(const e of Object.values(s.children))L(t,e);t.system._unregister(e)}function q(t,e){e&&(L(t,e),e._processingStatus===O.Running?t.defer(()=>{t.stopChild(e)}):t.stopChild(e))}function z(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=B,e.execute=q,e}const W=z;function U(t,e,{stateValue:s}){if("string"==typeof s&&it(s)){const e=t.machine.getStateNodeById(s);return t._nodes.some(t=>t===e)}return t.matches(s)}function Q(t,{context:e,event:s},{guards:n}){return!H(n[0],e,s,t)}function F(t,{context:e,event:s},{guards:n}){return n.every(n=>H(n,e,s,t))}function G(t){function e(t,e){return!1}return e.check=F,e.guards=t,e}function X(t,{context:e,event:s},{guards:n}){return n.some(n=>H(n,e,s,t))}function H(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return H(r,e,s,n);const a={context:e,event:s},c=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(a,c);return r.check(n,a,r)}function K(t){return"atomic"===t.type||"final"===t.type}function Y(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Z(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function tt(t){const e=new Set(t),s=st(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of Y(t))if("history"!==s.type&&!e.has(s)){const t=ht(s);for(const s of t)e.add(s)}}else ht(t).forEach(t=>e.add(t));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function et(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(K(t))return t.key}const n={};for(const t of s)n[t.key]=et(t,e);return n}function st(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function nt(t,e){return et(t,st(tt(e)))}function ot(t,e){return"compound"===e.type?Y(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?Y(e).every(e=>ot(t,e)):"final"===e.type}const it=t=>"#"===t[0];function rt(t){const e=t.config.after;if(!e)return[];const s=Object.keys(e).flatMap(s=>{const n=e[s],o="string"==typeof n?{target:n}:n,i=Number.isNaN(+s)?s:+s,r=(e=>{const s=(n=e,o=t.id,{type:`xstate.after.${n}.${o}`});var n,o;const i=s.type;return t.entry.push(te(s,{id:i,delay:e})),t.exit.push(R(i)),i})(i);return v(o).map(t=>({...t,event:r,delay:i}))});return s.map(e=>{const{delay:s}=e;return{...at(t,e.event,e),delay:s}})}function at(t,e,s){const n=x(s.target),o=s.reenter??!1,i=function(t,e){if(void 0===e)return;return e.map(e=>{if("string"!=typeof e)return e;if(it(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return pt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`);try{return pt(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}(t,n),r={...s,actions:v(s.actions),guard:s.guard,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function ct(t){const e=x(t.config.target);return e?{target:e.map(e=>"string"==typeof e?pt(t.parent,e):e)}:t.parent.initial}function ut(t){return"history"===t.type}function ht(t){const e=ft(t);for(const s of e)for(const n of Z(s,t))e.add(n);return e}function ft(t){const e=new Set;return function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of Y(s))t(e)}(t),e}function dt(t,e){if(it(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 s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function pt(t,e){if("string"==typeof e&&it(e))try{return t.machine.getStateNodeById(e)}catch{}const s=d(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=dt(n,t)}return n}function lt(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=s.map(e=>dt(t,e)).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce((s,n)=>{const o=dt(t,n);if(!o)return s;const i=lt(o,e[n]);return s.concat(i)},[]))}function yt(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=dt(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=yt(dt(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const a=yt(dt(t,i),r,s,n);a&&o.push(...a)}return o.length?o:t.next(s,n)}(t,e,s,n)}function gt(t){return Object.keys(t.states).map(e=>t.states[e]).filter(t=>"history"===t.type)}function vt(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function mt(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function _t(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(mt(St([o],e,s),St([r],e,s))){if(!vt(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function bt(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(ut(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of bt(ct(n),e))s.add(t);else s.add(n);return[...s]}function xt(t,e){const s=bt(t,e);if(!s)return;if(!t.reenter&&s.every(e=>e===t.source||vt(e,t.source)))return t.source;const n=function(t){const[e,...s]=t;for(const t of Z(e,void 0))if(s.every(e=>vt(e,t)))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function St(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=xt(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)vt(s,t)&&n.add(s)}return[...n]}function wt(t,e,s,n,o){return It([{target:[...ft(t)],source:t,reenter:!0,actions:[],eventType:null,toJSON:null}],e,s,n,!0,o)}function It(t,e,s,n,o,i){const a=[];if(!t.length)return[e,a];const c=s.actionExecutor;s.actionExecutor=t=>{a.push(t),c(t)};try{const c=new Set(e._nodes);let u=e.historyValue;const h=_t(t,c,u);let f=e;o||([f,u]=function(t,e,s,n,o,i,r){let a=t;const c=St(n,o,i);let u;c.sort((t,e)=>e.order-t.order);for(const t of c)for(const e of gt(t)){let s;s="deep"===e.history?e=>K(e)&&vt(e,t):e=>e.parent===t,u??={...i},u[e.id]=Array.from(o).filter(s)}for(const t of c)a=At(a,e,s,[...t.exit,...t.invoke.map(t=>z(t.id))],r,void 0),o.delete(t);return[a,u||i]}(f,n,s,h,c,u,i,s.actionExecutor)),f=At(f,n,s,h.flatMap(t=>t.actions),i,void 0),f=function(t,e,s,n,o,i,a,c){let u=t;const h=new Set,f=new Set;(function(t,e,s,n){for(const o of t){const t=xt(o,e);for(const i of o.target||[])ut(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),kt(i,e,s,n);const i=bt(o,e);for(const r of i){const i=Z(r,t);"parallel"===t?.type&&i.push(t),$t(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,a,f,h),c&&f.add(t.machine.root);const d=new Set;for(const t of[...h].sort((t,e)=>t.order-e.order)){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(J(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(f.has(t)){const e=t.initial.actions;n.push(...e)}if(u=At(u,e,s,n,i,t.invoke.map(t=>t.id)),"final"===t.type){const n=t.parent;let a="parallel"===n?.type?n:n?.parent,c=a||t;for("compound"===n?.type&&i.push(r(n.id,void 0!==t.output?m(t.output,u.context,e,s.self):void 0));"parallel"===a?.type&&!d.has(a)&&ot(o,a);)d.add(a),i.push(r(a.id)),c=a,a=a.parent;if(a)continue;u=zt(u,{status:"done",output:Et(u,e,s,u.machine.root,c)})}}return u}(f,n,s,h,c,i,u,o);const d=[...c];"done"===f.status&&(f=At(f,n,s,d.sort((t,e)=>e.order-t.order).flatMap(t=>t.exit),i,void 0));try{return u===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,c)?[f,a]:[zt(f,{_nodes:d,historyValue:u}),a]}catch(t){throw t}}finally{s.actionExecutor=c}}function Et(t,e,s,n,o){if(void 0===n.output)return;const i=r(o.id,void 0!==o.output&&o.parent?m(o.output,t.context,e,s.self):void 0);return m(n.output,t.context,i,s.self)}function kt(t,e,s,n){if(ut(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),kt(t,e,s,n);for(const i of o)Tt(i,t.parent,n,e,s)}else{const o=ct(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),kt(i,e,s,n);for(const i of o.target)Tt(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;ut(o)||(n.add(o),s.add(o)),kt(o,e,s,n),Tt(o,t,n,e,s)}else if("parallel"===t.type)for(const o of Y(t).filter(t=>!ut(t)))[...n].some(t=>vt(t,o))||(ut(o)||(n.add(o),s.add(o)),kt(o,e,s,n))}function $t(t,e,s,n,o){for(const i of n)if(o&&!vt(i,o)||t.add(i),"parallel"===i.type)for(const n of Y(i).filter(t=>!ut(t)))[...t].some(t=>vt(t,n))||(t.add(n),kt(n,e,s,t))}function Tt(t,e,s,n,o){$t(s,n,o,Z(t,e))}function Ot(t,e){return t.implementations.actions[e]}function jt(t,e,s,n,o,i){const{machine:r}=t;let a=t;for(const t of n){const n="function"==typeof t,c=n?t:Ot(r,"string"==typeof t?t:t.type),u={context:a.context,event:e,self:s.self,system:s.system},h=n||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:a.context,event:e}):t.params:void 0;if(!c||!("resolve"in c)){s.actionExecutor({type:"string"==typeof t?t:"object"==typeof t?t.type:t.name||"(anonymous)",info:u,params:h,exec:c});continue}const f=c,[d,p,l]=f.resolve(s,a,u,h,c,o);a=d,"retryResolve"in f&&i?.push([f,p]),"execute"in f&&s.actionExecutor({type:f.type,info:u,params:p,exec:f.execute.bind(null,s,p)}),l&&(a=jt(a,e,s,l,o,i))}return a}function At(t,e,s,n,o,i){const r=i?[]:void 0,a=jt(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach(([t,e])=>{t.retryResolve(s,a,e)}),a}function Mt(t,e,o,i){let r=t;const a=[];function c(t,e,s){o.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:o.self,event:e,snapshot:t[0],_transitions:s}),a.push(t)}if(e.type===n)return r=zt(Nt(r,e,o),{status:"stopped"}),c([r,[]],e,[]),{snapshot:r,microsteps:a};let u=e;if(u.type!==s){const e=u,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=Pt(e,r);if(s&&!n.length)return r=zt(t,{status:"error",error:e.error}),c([r,[]],e,[]),{snapshot:r,microsteps:a};const h=It(n,t,o,u,!1,i);r=h[0],c(h,e,n)}let h=!0;const f=t.machine.options?.maxIterations??1/0;let d=0;for(;"active"===r.status;){if(d++,d>f)throw new Error(`Infinite loop detected: the machine has processed more than ${f} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`);let t=h?Ct(r,u):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;u=i.shift(),t=Pt(u,r)}const s=It(t,r,o,u,!1,i);r=s[0],h=r!==e,c(s,u,t)}return"active"!==r.status&&Nt(r,u,o),{snapshot:r,microsteps:a}}function Nt(t,e,s){return At(t,e,s,Object.values(t.children).map(t=>z(t)),[],void 0)}function Pt(t,e){return e.machine.getTransitionData(e,t)}function Ct(t,e){const s=new Set,n=t._nodes.filter(K);for(const o of n)t:for(const n of[o].concat(Z(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||H(o.guard,t.context,e,t)){s.add(o);break t}return _t(Array.from(s),new Set(t._nodes),t.historyValue)}function Rt(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Vt=function(t){return f(t,this.value)},Dt=function(t){return this.tags.has(t)},Jt=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some(t=>void 0!==t.target||t.actions.length)},Bt=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:a,...c}=this;return{...c,tags:Array.from(e)}},Lt=function(){return this._nodes.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{})};function qt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:nt(e.root,t._nodes),tags:new Set(t._nodes.flatMap(t=>t.tags)),children:t.children,historyValue:t.historyValue||{},matches:Vt,hasTag:Dt,can:Jt,getMeta:Lt,toJSON:Bt}}function zt(t,e={}){return qt({...t,...e},t.machine)}function Wt(t){if("object"!=typeof t||null===t)return{};const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function Ut(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:1,id:n.id};else{const o=Ut(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function Qt(t,{machine:e,context:s},n,o){return(i,r)=>{const a=((i,r)=>{if("string"==typeof i){const a=I(e,i);if(!a)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=M(a,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[c.id]=c,c}return M(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[a.id]=a,t.defer(()=>{a._processingStatus!==O.Stopped&&a.start()}),a}}function Ft(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:Qt(t,e,s.event,i),self:t.self,system:t.system};let a={};if("function"==typeof o)a=o(r,n);else for(const t of Object.keys(o)){const e=o[t];a[t]="function"==typeof e?e(r,n):e}return[zt(e,{context:Object.assign({},e.context,a),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function Gt(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=Ft,e}function Xt(t,e,s,n,{event:o}){return[e,{event:"function"==typeof o?o(s,n):o},void 0]}function Ht(t,{event:e}){t.defer(()=>t.emit(e))}function Kt(t){function e(t,e){}return e.type="xstate.emit",e.event=t,e.resolve=Xt,e.execute=Ht,e}function Yt(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:a}){const c=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const u="function"==typeof o?o(s,n):o;let h;if("string"==typeof r){const t=c&&c[r];h="function"==typeof t?t(s,n):t}else h="function"==typeof r?r(s,n):r;return"number"!=typeof h&&a.push(u),[e,{event:u,id:i,delay:h},void 0]}function Zt(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer(()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)})}function te(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=Yt,s.execute=Zt,s}let ee=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function se(t,e,s,n,{to:o,event:i,id:r,delay:a},c){const u=e.machine.implementations.delays;if("string"==typeof i)throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const h="function"==typeof i?i(s,n):i;let f;if("string"==typeof a){const t=u&&u[a];f="function"==typeof t?t(s,n):t}else f="function"==typeof a?a(s,n):a;const d="function"==typeof o?o(s,n):o;let p;if("string"==typeof d){if(p=d===ee.Parent?t.self._parent:d===ee.Internal?t.self:d.startsWith("#_")?e.children[d.slice(2)]:c.deferredActorIds?.includes(d)?d:e.children[d],!p)throw new Error(`Unable to send event to actor '${d}' from machine '${e.machine.id}'.`)}else p=d||t.self;return[e,{to:p,targetId:"string"==typeof d?d:void 0,event:h,id:r,delay:f},void 0]}function ne(t,e,s){"string"==typeof s.to&&(s.to=e.children[s.to])}function oe(t,e){t.defer(()=>{const{to:s,event:n,delay:o,id:i}=e;"number"!=typeof o?t.system._relay(t.self,s,"xstate.error"===n.type?a(t.self.id,n.data):n):t.system.scheduler.schedule(t.self,s,n,o,i)})}function ie(t,e,s){function n(t,e){}return n.type="xstate.sendTo",n.to=t,n.event=e,n.id=s?.id,n.delay=s?.delay,n.resolve=se,n.retryResolve=ne,n.execute=oe,n}function re(t,e){return ie(ee.Parent,t,e)}function ae(t,e,s,n,{collect:o}){const i=[],r=function(t){i.push(t)};return r.assign=(...t)=>{i.push(Gt(...t))},r.cancel=(...t)=>{i.push(R(...t))},r.raise=(...t)=>{i.push(te(...t))},r.sendTo=(...t)=>{i.push(ie(...t))},r.sendParent=(...t)=>{i.push(re(...t))},r.spawnChild=(...t)=>{i.push(J(...t))},r.stopChild=(...t)=>{i.push(z(...t))},r.emit=(...t)=>{i.push(Kt(...t))},o({context:s.context,event:s.event,enqueue:r,check:t=>H(t,e.context,s.event,e),self:t.self,system:t.system},n),[e,void 0,i]}function ce(t){function e(t,e){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=ae,e}function ue(t,e,s,n,{value:o,label:i}){return[e,{value:"function"==typeof o?o(s,n):o,label:i},void 0]}function he({logger:t},{value:e,label:s}){s?t(s,e):t(e)}function fe(t=({context:t,event:e})=>({context:t,event:e}),e){function s(t,e){}return s.type="xstate.log",s.value=t,s.label=e,s.resolve=ue,s.execute=he,s}function de(t,e){return{config:t,transition:(e,s,n)=>({...e,context:t(e.context,s,n)}),getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof e?e({input:s}):e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const pe=new WeakMap;const le="xstate.observable.next",ye="xstate.observable.error",ge="xstate.observable.complete";const ve="xstate.promise.resolve",me="xstate.promise.reject",_e=new WeakMap;const be=de(t=>{},void 0);const xe=new WeakMap;function Se(t,e,s){let n=xe.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},xe.set(t,n)),n[e]}const we={},Ie=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class Ee{constructor(t,e){if(this.config=t,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=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join("."),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?y(this.config.states,(t,e)=>new Ee(t,{_parent:this,_key:e,_machine:this.machine})):we,"compound"===this.type&&!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=!0===this.config.history?"shallow":this.config.history||!1,this.entry=v(this.config.entry).slice(),this.exit=v(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=v(t.tags).slice()}_initialize(){this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,b(n).map(e=>at(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,b(t.config.onDone).map(e=>at(t,s,e)))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,b(s.onDone).map(e=>at(t,n,e)))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,b(s.onError).map(e=>at(t,n,e)))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,b(s.onSnapshot).map(e=>at(t,n,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),this.config.always&&(this.always=b(this.config.always).map(t=>at(this,"",t))),Object.keys(this.states).forEach(t=>{this.states[t]._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(Ie),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Ie),eventType:null})}:void 0,history:this.history,states:y(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Ie)})),entry:this.entry.map(Ie),exit:this.exit.map(Ie),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 Se(this,"invoke",()=>v(this.config.invoke).map((t,e)=>{const{src:s,systemId:n}=t,o=t.id??w(this.id,e),i="string"==typeof s?s:`xstate.invoke.${w(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:"xstate.invoke",src:i,id:o}}}}))}get on(){return Se(this,"on",()=>[...this.transitions].flatMap(([t,e])=>e.map(e=>[t,e])).reduce((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t),{}))}get after(){return Se(this,"delayedTransitions",()=>rt(this))}get initial(){return Se(this,"initial",()=>function(t,e){const s="string"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const n={source:t,actions:e&&"string"!=typeof e?v(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial))}next(t,e){const s=e.type,n=[];let o;const i=Se(this,`candidates-${s}`,()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter(t=>E(e,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));var t,e});for(const r of i){const{guard:i}=r,a=t.context;let c=!1;try{c=!i||H(i,a,e,t)}catch(t){const e="string"==typeof i?i:"object"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:""}in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(c){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return Se(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)})}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),e=new Set(t.filter(t=>this.transitions.get(t).some(t=>!(!t.target&&!t.actions.length&&!t.reenter))));return Array.from(e)}}class ke{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=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.id=t.id||"(machine)",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.options={maxIterations:1/0,...this.config.options},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 Ee(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const s=n.config.id,o=n.config.route.guard,i=({event:t})=>t.to===`#${s}`,r={...n.config.route,guard:o?G([i,o]):i,target:`#${s}`};e.push(at(t,"xstate.route",r))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new ke(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,nt(s,[...tt(lt(s,n))]));var s,n;const o=tt(lt(this.root,e));return qt({_nodes:[...o],context:t.context||{},children:{},status:ot(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Mt(t,e,s,[]).snapshot}microstep(t,e,s){return Mt(t,e,s,[]).microsteps.map(([t])=>t)}getTransitionData(t,e){return yt(this.root,t.value,t,e)||[]}_getPreInitialState(t,e,s){const{context:n}=this.config,o=qt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return At(o,e,t,[Gt(({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s}))],s,void 0)}return o}getInitialSnapshot(t,e){const s=c(e),n=[],o=this._getPreInitialState(t,s,n),[i]=wt(this.root,o,t,s,n),{snapshot:r}=Mt(i,s,t,n);return r}start(t){Object.values(t.children).forEach(t=>{"active"===t.getSnapshot().status&&t.start()})}getStateNodeById(t){const e=d(t),s=e.slice(1),n=it(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return pt(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:a,hasTag:c,matches:u,getMeta:h,toJSON:f,...d}=t,p={};for(const t in i){const s=i[t];p[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}return{...d,context:Ut(r),children:p,historyValue:Wt(d.historyValue)}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;function o(t,e){if(e instanceof Ee)return e;try{return t.machine.getStateNodeById(e.id)}catch{}}Object.keys(n).forEach(t=>{const o=n[t],i=o.snapshot,r=o.src,a="string"==typeof r?I(this,r):r;if(!a)return;const c=M(a,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=c});const i=function(t,e){if(!e||"object"!=typeof e)return{};const s={};for(const n in e){const i=e[n];for(const e of i){const i=o(t,e);i&&(s[n]??=[],s[n].push(i))}}return s}(this.root,t.historyValue),r=qt({...t,children:s,_nodes:Array.from(tt(lt(this.root,t.value))),historyValue:i},this),a=new Set;return function t(e,s){if(!a.has(e)){a.add(e);for(const n in e){const o=e[n];if(o&&"object"==typeof o){if("xstate$$type"in o&&1===o.xstate$$type){e[n]=s[o.id];continue}t(o,s)}}}}(r.context,s),r}}function $e(t,e){return new ke(t,e)}function Te(t){const e=M(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}const Oe={timeout:1/0};t.Actor=A,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const s=this.getId();return this.timeouts.set(s,{start:this.now(),timeout:e,fn:t}),s}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort(([t,e],[s,n])=>{const o=e.start+e.timeout;return n.start+n.timeout>o?-1:1});for(const[e,s]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-s.start>=s.timeout&&(this.timeouts.delete(e),s.fn.call(null))}this._flushing=!1}increment(t){this._now+=t,this.flushTimeouts()}},t.SpecialTargets=ee,t.StateMachine=ke,t.StateNode=Ee,t.__unsafe_getAllOwnEventDescriptors=function(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]},t.and=G,t.assertEvent=function(t,e){const s=v(e);if(!s.some(e=>E(t.type,e))){const e=1===s.length?`type matching "${s[0]}"`:`one of types matching "${s.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}},t.assign=Gt,t.cancel=R,t.createActor=M,t.createEmptyActor=function(){return M(be)},t.createMachine=$e,t.emit=Kt,t.enqueueActions=ce,t.forwardTo=function(t,e){return ie(t,({event:t})=>t,e)},t.fromCallback=function(t){const e={config:t,start:(e,s)=>{const{self:n,system:o,emit:i}=s,r={receivers:void 0,dispose:void 0};pe.set(n,r),r.dispose=t({input:e.input,system:o,self:n,sendBack:t=>{"stopped"!==n.getSnapshot().status&&n._parent&&o._relay(n,n._parent,t)},receive:t=>{r.receivers??=new Set,r.receivers.add(t)},emit:i})},transition:(t,e,s)=>{const o=pe.get(s.self);return e.type===n?(t={...t,status:"stopped",error:void 0},pe.delete(s.self),o.receivers?.clear(),o.dispose?.(),t):(o.receivers?.forEach(t=>t(e)),t)},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromEventObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case ye:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case ge:return{...t,status:"done",input:void 0,_subscription:void 0};case n:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:ye,data:t})},complete:()=>{n._relay(s,s,{type:ge})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case le:return{...t,context:e.data};case ye:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case ge:return{...t,status:"done",input:void 0,_subscription:void 0};case n:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{n._relay(s,s,{type:le,data:t})},error:t=>{n._relay(s,s,{type:ye,data:t})},complete:()=>{n._relay(s,s,{type:ge})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromPromise=function(t){const e={config:t,transition:(t,e,s)=>{if("active"!==t.status)return t;switch(e.type){case ve:{const s=e.data;return{...t,status:"done",output:s,input:void 0}}case me:return{...t,status:"error",error:e.data,input:void 0};case n:return _e.get(s.self)?.abort(),_e.delete(s.self),{...t,status:"stopped",input:void 0};default:return t}},start:(e,{self:s,system:n,emit:o})=>{if("active"!==e.status)return;const i=new AbortController;_e.set(s,i);Promise.resolve(t({input:e.input,system:n,self:s,signal:i.signal,emit:o})).then(t=>{"active"===s.getSnapshot().status&&(_e.delete(s),n._relay(s,s,{type:ve,data:t}))},t=>{"active"===s.getSnapshot().status&&(_e.delete(s),n._relay(s,s,{type:me,data:t}))})},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromTransition=de,t.getInitialMicrosteps=function(t,...[e]){const s=Te(t),n=c(e),o=[],i=t._getPreInitialState(s,n,o),r=wt(t.root,i,s,n,o),{microsteps:a}=Mt(r[0],n,s,o);return[r,...a]},t.getInitialSnapshot=function(t,...[e]){const s=Te(t);return t.getInitialSnapshot(s,e)},t.getMicrosteps=function(t,e,s){const n=Te(t),{microsteps:o}=Mt(e,s,n,[]);return o},t.getNextSnapshot=function(t,e,s){const n=Te(t);return n.self._snapshot=e,t.transition(e,s,n)},t.getNextTransitions=function(t){const e=[],s=t._nodes.filter(K),n=new Set;for(const t of s)for(const s of[t].concat(Z(t,void 0)))if(!n.has(s.id)){n.add(s.id);for(const[,t]of s.transitions)e.push(...t);s.always&&e.push(...s.always)}return e},t.getStateNodes=lt,t.initialTransition=function(t,...[e]){const s=[],n=Te(t);return n.actionExecutor=t=>{s.push(t)},[t.getInitialSnapshot(n,e),s]},t.interpret=N,t.isMachineSnapshot=Rt,t.log=fe,t.mapState=function(t,e){const s=[],n=(t,e)=>{let s=t;for(const t of e){if(!s?.states)return;const e=s.states;if(!(t in e))return;s=e[t]}return s},o=new Set;for(const i of t._nodes.filter(K)){let r=i;for(;r&&!o.has(r);){o.add(r);const i=n(e,r.path);i?.map&&s.push({stateNode:r,result:i.map(t)}),r=r.parent}}return s},t.matchesState=f,t.not=function(t){function e(t,e){return!1}return e.check=Q,e.guards=[t],e},t.or=function(t){function e(t,e){return!1}return e.check=X,e.guards=t,e},t.pathToStateValue=l,t.raise=te,t.sendParent=re,t.sendTo=ie,t.setup=function t({schemas:e,actors:s,actions:n,guards:o,delays:i}){return{assign:Gt,sendTo:ie,raise:te,log:fe,cancel:R,stopChild:z,enqueueActions:ce,emit:Kt,spawnChild:J,createStateConfig:t=>t,createAction:t=>t,createMachine:t=>$e({...t,schemas:e},{actors:s,actions:n,guards:o,delays:i}),extend:r=>t({schemas:e,actors:s,actions:{...n,...r.actions},guards:{...o,...r.guards},delays:{...i,...r.delays}})}},t.spawnChild=J,t.stateIn=function(t){function e(){return!1}return e.check=U,e.stateValue=t,e},t.stop=W,t.stopChild=z,t.toObserver=S,t.toPromise=function(t){return new Promise((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})})},t.transition=function(t,e,s){const n=[],o=Te(t);return o.actionExecutor=t=>{n.push(t)},[t.transition(e,s,o),n]},t.waitFor=function(t,e,s){const n={...Oe,...s};return new Promise((s,o)=>{const{signal:i}=n;if(i?.aborted)return void o(i.reason);let r=!1;const a=n.timeout===1/0?void 0:setTimeout(()=>{c(),o(new Error(`Timeout of ${n.timeout} ms exceeded`))},n.timeout),c=()=>{clearTimeout(a),r=!0,f?.unsubscribe(),h&&i.removeEventListener("abort",h)};function u(t){e(t)&&(c(),s(t))}let h,f;u(t.getSnapshot()),r||(i&&(h=()=>{c(),o(i.reason)},i.addEventListener("abort",h)),f=t.subscribe({next:u,error:t=>{c(),o(t)},complete:()=>{c(),o(new Error("Actor terminated without satisfying predicate"))}}),r&&f.unsubscribe())})},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate.umd.min.js.map
@@ -1,195 +0,0 @@
1
- export function addChunkQueries(q, db, prep, generateId) {
2
- q.createChunk = function(sessionId, conversationId, sequence, type, data) {
3
- const id = generateId('chunk');
4
- const now = Date.now();
5
- const dataBlob = typeof data === 'string' ? data : JSON.stringify(data);
6
-
7
- const stmt = prep(
8
- `INSERT INTO chunks (id, sessionId, conversationId, sequence, type, data, created_at)
9
- VALUES (?, ?, ?, ?, ?, ?, ?)`
10
- );
11
- stmt.run(id, sessionId, conversationId, sequence, type, dataBlob, now);
12
-
13
- return {
14
- id,
15
- sessionId,
16
- conversationId,
17
- sequence,
18
- type,
19
- data,
20
- created_at: now
21
- };
22
- };
23
-
24
- q.getChunk = function(id) {
25
- const stmt = prep(
26
- `SELECT id, sessionId, conversationId, sequence, type, data, created_at FROM chunks WHERE id = ?`
27
- );
28
- const row = stmt.get(id);
29
- if (!row) return null;
30
-
31
- try {
32
- return {
33
- ...row,
34
- data: typeof row.data === 'string' ? JSON.parse(row.data) : row.data
35
- };
36
- } catch (e) {
37
- return row;
38
- }
39
- };
40
-
41
- q.getSessionChunks = function(sessionId) {
42
- const stmt = prep(
43
- `SELECT id, sessionId, conversationId, sequence, type, data, created_at
44
- FROM chunks WHERE sessionId = ? ORDER BY sequence ASC`
45
- );
46
- const rows = stmt.all(sessionId);
47
- return rows.map(row => {
48
- try {
49
- return {
50
- ...row,
51
- data: typeof row.data === 'string' ? JSON.parse(row.data) : row.data
52
- };
53
- } catch (e) {
54
- return row;
55
- }
56
- });
57
- };
58
-
59
- q.getConversationChunkCount = function(conversationId) {
60
- const stmt = prep('SELECT COUNT(*) as count FROM chunks WHERE conversationId = ?');
61
- return stmt.get(conversationId).count;
62
- };
63
-
64
- q.getConversationChunks = function(conversationId) {
65
- const stmt = prep(
66
- `SELECT id, sessionId, conversationId, sequence, type, data, created_at
67
- FROM chunks WHERE conversationId = ? ORDER BY created_at ASC`
68
- );
69
- const rows = stmt.all(conversationId);
70
- return rows.map(row => {
71
- try {
72
- return {
73
- ...row,
74
- data: typeof row.data === 'string' ? JSON.parse(row.data) : row.data
75
- };
76
- } catch (e) {
77
- return row;
78
- }
79
- });
80
- };
81
-
82
- q.getConversationChunksSince = function(conversationId, since) {
83
- const stmt = prep(
84
- `SELECT id, sessionId, conversationId, sequence, type, data, created_at
85
- FROM chunks WHERE conversationId = ? AND created_at > ? ORDER BY created_at ASC`
86
- );
87
- const rows = stmt.all(conversationId, since);
88
- return rows.map(row => {
89
- try { return { ...row, data: typeof row.data === 'string' ? JSON.parse(row.data) : row.data }; }
90
- catch (e) { return row; }
91
- });
92
- };
93
-
94
- q.getRecentConversationChunks = function(conversationId, limit = 500) {
95
- const sessions = prep(
96
- `SELECT sessionId, COUNT(*) as n FROM chunks WHERE conversationId = ?
97
- GROUP BY sessionId ORDER BY MAX(created_at) DESC`
98
- ).all(conversationId);
99
- if (!sessions.length) return [];
100
- const included = [];
101
- let total = 0;
102
- for (const s of sessions) {
103
- if (total + s.n > limit && included.length > 0) break;
104
- included.unshift(s.sessionId);
105
- total += s.n;
106
- }
107
- const placeholders = included.map(() => '?').join(',');
108
- const rows = prep(
109
- `SELECT id, sessionId, conversationId, sequence, type, data, created_at
110
- FROM chunks WHERE conversationId = ? AND sessionId IN (${placeholders})
111
- ORDER BY created_at ASC`
112
- ).all(conversationId, ...included);
113
- return rows.map(row => {
114
- try { return { ...row, data: typeof row.data === 'string' ? JSON.parse(row.data) : row.data }; }
115
- catch (e) { return row; }
116
- });
117
- };
118
-
119
- q.getRecentMessages = function(conversationId, limit = 20) {
120
- const countStmt = prep('SELECT COUNT(*) as count FROM messages WHERE conversationId = ?');
121
- const total = countStmt.get(conversationId).count;
122
-
123
- const stmt = prep(
124
- 'SELECT * FROM messages WHERE conversationId = ? ORDER BY created_at DESC LIMIT ? '
125
- );
126
- const messages = stmt.all(conversationId, limit).reverse();
127
-
128
- return {
129
- messages: messages.map(msg => {
130
- if (typeof msg.content === 'string') {
131
- try {
132
- msg.content = JSON.parse(msg.content);
133
- } catch (_) {}
134
- }
135
- return msg;
136
- }),
137
- total,
138
- limit,
139
- offset: Math.max(0, total - limit),
140
- hasMore: total > limit
141
- };
142
- };
143
-
144
- q.getMessagesBefore = function(conversationId, beforeId, limit = 50) {
145
- const countStmt = prep('SELECT COUNT(*) as count FROM messages WHERE conversationId = ?');
146
- const total = countStmt.get(conversationId).count;
147
-
148
- const stmt = prep(`
149
- SELECT * FROM messages
150
- WHERE conversationId = ? AND id < (SELECT id FROM messages WHERE id = ?)
151
- ORDER BY created_at DESC LIMIT ?
152
- `);
153
- const messages = stmt.all(conversationId, beforeId, limit).reverse();
154
-
155
- return {
156
- messages: messages.map(msg => {
157
- if (typeof msg.content === 'string') {
158
- try {
159
- msg.content = JSON.parse(msg.content);
160
- } catch (_) {}
161
- }
162
- return msg;
163
- }),
164
- total,
165
- limit,
166
- hasMore: total > (limit + 1)
167
- };
168
- };
169
-
170
- q.getChunksBefore = function(conversationId, beforeTimestamp, limit = 500) {
171
- const total = prep('SELECT COUNT(*) as count FROM chunks WHERE conversationId = ? AND created_at < ?')
172
- .get(conversationId, beforeTimestamp).count;
173
-
174
- const rows = prep(`
175
- SELECT id, sessionId, conversationId, sequence, type, data, created_at
176
- FROM chunks
177
- WHERE conversationId = ? AND created_at < ?
178
- ORDER BY created_at DESC LIMIT ?
179
- `).all(conversationId, beforeTimestamp, limit);
180
- rows.reverse();
181
-
182
- return {
183
- chunks: rows.map(row => {
184
- try {
185
- return { ...row, data: typeof row.data === 'string' ? JSON.parse(row.data) : row.data };
186
- } catch (e) {
187
- return row;
188
- }
189
- }),
190
- total,
191
- limit,
192
- hasMore: rows.length === limit
193
- };
194
- };
195
- }
@@ -1,82 +0,0 @@
1
- export function addChunkQueries2(q, db, prep, generateId) {
2
- q.getChunksSince = function(sessionId, timestamp) {
3
- const stmt = prep(
4
- `SELECT id, sessionId, conversationId, sequence, type, data, created_at
5
- FROM chunks WHERE sessionId = ? AND created_at > ? ORDER BY sequence ASC`
6
- );
7
- const rows = stmt.all(sessionId, timestamp);
8
- return rows.map(row => {
9
- try {
10
- return {
11
- ...row,
12
- data: typeof row.data === 'string' ? JSON.parse(row.data) : row.data
13
- };
14
- } catch (e) {
15
- return row;
16
- }
17
- });
18
- };
19
-
20
- q.getChunksSinceSeq = function(sessionId, sinceSeq) {
21
- const stmt = prep(
22
- `SELECT id, sessionId, conversationId, sequence, type, data, created_at
23
- FROM chunks WHERE sessionId = ? AND sequence > ? ORDER BY sequence ASC`
24
- );
25
- const rows = stmt.all(sessionId, sinceSeq);
26
- return rows.map(row => {
27
- try {
28
- return {
29
- ...row,
30
- data: typeof row.data === 'string' ? JSON.parse(row.data) : row.data
31
- };
32
- } catch (e) {
33
- return row;
34
- }
35
- });
36
- };
37
-
38
- q.deleteSessionChunks = function(sessionId) {
39
- const stmt = prep('DELETE FROM chunks WHERE sessionId = ?');
40
- const result = stmt.run(sessionId);
41
- return result.changes || 0;
42
- };
43
-
44
- q.getMaxSequence = function(sessionId) {
45
- const stmt = prep('SELECT MAX(sequence) as max FROM chunks WHERE sessionId = ?');
46
- const result = stmt.get(sessionId);
47
- return result?.max ?? -1;
48
- };
49
-
50
- q.getEmptyConversations = function() {
51
- const stmt = prep(`
52
- SELECT c.* FROM conversations c
53
- LEFT JOIN messages m ON c.id = m.conversationId
54
- WHERE c.status != 'deleted'
55
- GROUP BY c.id
56
- HAVING COUNT(m.id) = 0
57
- `);
58
- return stmt.all();
59
- };
60
-
61
- q.permanentlyDeleteConversation = function(id) {
62
- return this.deleteConversation(id);
63
- };
64
-
65
- q.cleanupEmptyConversations = function() {
66
- const emptyConvs = this.getEmptyConversations();
67
- let deletedCount = 0;
68
-
69
- for (const conv of emptyConvs) {
70
- console.log(`[cleanup] Deleting empty conversation: ${conv.id} (${conv.title || 'Untitled'})`);
71
- if (this.permanentlyDeleteConversation(conv.id)) {
72
- deletedCount++;
73
- }
74
- }
75
-
76
- if (deletedCount > 0) {
77
- console.log(`[cleanup] Deleted ${deletedCount} empty conversation(s)`);
78
- }
79
-
80
- return deletedCount;
81
- };
82
- }
@@ -1,74 +0,0 @@
1
- export function addCleanupQueries(q, db, prep, generateId) {
2
- q.cleanup = function() {
3
- const thirtyDaysAgo = Date.now() - (30 * 24 * 60 * 60 * 1000);
4
- const sevenDaysAgo = Date.now() - (7 * 24 * 60 * 60 * 1000);
5
- const now = Date.now();
6
-
7
- const cleanupStmt = db.transaction(() => {
8
- prep('DELETE FROM events WHERE created_at < ?').run(thirtyDaysAgo);
9
- prep('DELETE FROM idempotencyKeys WHERE (created_at + ttl) < ?').run(now);
10
-
11
- prep('DELETE FROM chunks WHERE sessionId IN (SELECT id FROM sessions WHERE completed_at IS NOT NULL AND completed_at < ?)').run(thirtyDaysAgo);
12
- prep('DELETE FROM stream_updates WHERE sessionId IN (SELECT id FROM sessions WHERE completed_at IS NOT NULL AND completed_at < ?)').run(thirtyDaysAgo);
13
-
14
- prep('DELETE FROM chunks WHERE created_at < ? AND sessionId NOT IN (SELECT id FROM sessions WHERE completed_at IS NULL AND started_at >= ?)').run(sevenDaysAgo, sevenDaysAgo);
15
- prep('DELETE FROM stream_updates WHERE created_at < ? AND sessionId NOT IN (SELECT id FROM sessions WHERE completed_at IS NULL AND started_at >= ?)').run(sevenDaysAgo, sevenDaysAgo);
16
-
17
- prep('DELETE FROM sessions WHERE completed_at IS NOT NULL AND completed_at < ?').run(thirtyDaysAgo);
18
-
19
- const deletedConvIds = prep("SELECT id FROM conversations WHERE status = 'deleted' AND updated_at < ?").all(sevenDaysAgo).map(r => r.id);
20
- for (const cid of deletedConvIds) {
21
- prep('DELETE FROM stream_updates WHERE conversationId = ?').run(cid);
22
- prep('DELETE FROM chunks WHERE conversationId = ?').run(cid);
23
- prep('DELETE FROM events WHERE conversationId = ?').run(cid);
24
- prep('DELETE FROM sessions WHERE conversationId = ?').run(cid);
25
- prep('DELETE FROM messages WHERE conversationId = ?').run(cid);
26
- prep('DELETE FROM thread_states WHERE thread_id = ?').run(cid);
27
- prep('DELETE FROM run_metadata WHERE thread_id = ?').run(cid);
28
- prep('DELETE FROM conversations WHERE id = ?').run(cid);
29
- }
30
-
31
- prep('DELETE FROM thread_states WHERE created_at < ?').run(thirtyDaysAgo);
32
- prep('DELETE FROM run_metadata WHERE created_at < ? AND status NOT IN (?, ?)').run(thirtyDaysAgo, 'active', 'pending');
33
-
34
- prep('DELETE FROM workflow_runs WHERE created_at < ?').run(thirtyDaysAgo);
35
- });
36
-
37
- cleanupStmt();
38
-
39
- try {
40
- db.exec('PRAGMA incremental_vacuum(1000)');
41
- } catch (_) {
42
- }
43
- };
44
-
45
- q.setIdempotencyKey = function(key, value) {
46
- const now = Date.now();
47
- const ttl = 24 * 60 * 60 * 1000;
48
-
49
- const stmt = prep(
50
- 'INSERT OR REPLACE INTO idempotencyKeys (key, value, created_at, ttl) VALUES (?, ?, ?, ?)'
51
- );
52
- stmt.run(key, JSON.stringify(value), now, ttl);
53
- };
54
-
55
- q.getIdempotencyKey = function(key) {
56
- const stmt = prep('SELECT * FROM idempotencyKeys WHERE key = ?');
57
- const entry = stmt.get(key);
58
-
59
- if (!entry) return null;
60
-
61
- const isExpired = Date.now() - entry.created_at > entry.ttl;
62
- if (isExpired) {
63
- db.run('DELETE FROM idempotencyKeys WHERE key = ?', [key]);
64
- return null;
65
- }
66
-
67
- return entry.value;
68
- };
69
-
70
- q.clearIdempotencyKey = function(key) {
71
- db.run('DELETE FROM idempotencyKeys WHERE key = ?', [key]);
72
- };
73
-
74
- }