@doeixd/machine 0.0.17 → 0.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -10
- package/dist/cjs/development/core.js.map +2 -2
- package/dist/cjs/development/index.js +38 -0
- package/dist/cjs/development/index.js.map +2 -2
- package/dist/cjs/production/core.js +1 -1
- package/dist/cjs/production/index.js +5 -5
- package/dist/esm/development/core.js.map +2 -2
- package/dist/esm/development/index.js +38 -0
- package/dist/esm/development/index.js.map +2 -2
- package/dist/esm/production/core.js +1 -1
- package/dist/esm/production/index.js +5 -5
- package/dist/types/extract.d.ts +15 -1
- package/dist/types/extract.d.ts.map +1 -1
- package/dist/types/index.d.ts +14 -1
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/extract.ts +61 -61
- package/src/generators.ts +6 -6
- package/src/index.ts +16 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var N=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var Ue=(e,t)=>{for(var n in t)N(e,n,{get:t[n],enumerable:!0})},qe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Le(t))!Ve.call(e,o)&&o!==n&&N(e,o,{get:()=>t[o],enumerable:!(r=Ie(t,o))||r.enumerable});return e};var Ye=e=>qe(N({},"__esModule",{value:!0}),e);var bt={};Ue(bt,{BoundMachine:()=>k,CANCEL:()=>L,META_KEY:()=>xe,MachineBase:()=>m,MiddlewareBuilder:()=>P,MultiMachineBase:()=>G,action:()=>Ce,bindTransitions:()=>te,branch:()=>yt,call:()=>Be,chain:()=>at,combine:()=>lt,combineFactories:()=>Ge,compose:()=>it,composeTyped:()=>v,createAsyncMachine:()=>oe,createCustomMiddleware:()=>ot,createEnsemble:()=>Ee,createEnsembleFactory:()=>Je,createEvent:()=>Re,createFetchMachine:()=>rt,createFlow:()=>de,createFunctionalMachine:()=>re,createMachine:()=>p,createMachineBuilder:()=>_e,createMachineFactory:()=>Ne,createMiddleware:()=>g,createMiddlewareFactory:()=>Tt,createMiddlewareRegistry:()=>dt,createMultiMachine:()=>Ze,createMutableMachine:()=>et,createParallelMachine:()=>I,createPipeline:()=>ut,createRunner:()=>we,createTransition:()=>Pe,createTransitionExtender:()=>ne,createTransitionFactory:()=>ke,delegateToChild:()=>tt,describe:()=>fe,extendTransitions:()=>K,guard:()=>F,guardAsync:()=>A,guarded:()=>pe,hasState:()=>He,inDevelopment:()=>st,invoke:()=>ge,isConditionalMiddleware:()=>Mt,isMiddlewareContext:()=>ht,isMiddlewareError:()=>ft,isMiddlewareFn:()=>ee,isMiddlewareHooks:()=>pt,isMiddlewareOptions:()=>gt,isMiddlewareResult:()=>xt,isNamedMiddleware:()=>Ct,isPipelineConfig:()=>mt,isState:()=>Se,logState:()=>Oe,matchMachine:()=>We,mergeContext:()=>je,metadata:()=>be,middlewareBuilder:()=>Fe,next:()=>De,overrideTransitions:()=>ze,pipeTransitions:()=>ve,run:()=>z,runAsync:()=>le,runMachine:()=>$e,runSequence:()=>ce,runWithDebug:()=>ue,runWithEnsemble:()=>Xe,runWithRunner:()=>Qe,setContext:()=>E,state:()=>Ke,step:()=>ae,stepAsync:()=>ye,toggle:()=>nt,transitionTo:()=>he,when:()=>B,whenContext:()=>ct,whenGuard:()=>me,whenGuardAsync:()=>Te,withAnalytics:()=>U,withDebugging:()=>Ae,withErrorReporting:()=>J,withHistory:()=>S,withLogging:()=>V,withPerformanceMonitoring:()=>Q,withPermissions:()=>Y,withRetry:()=>X,withSnapshot:()=>R,withTimeTravel:()=>j,withValidation:()=>q,yieldMachine:()=>se});module.exports=Ye(bt);function z(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=n.next(r);if(i)return o;r=o}}function ae(e){return function*(){return yield e}()}function se(e){return e}function ce(e,t){return t.reduce((n,r)=>z(r,n),e)}function de(e){return e}function ue(e,t,n=(r,o)=>{console.log(`Step ${r}:`,o.context)}){let r=e(t),o=t,i=0;for(n(i,o);;){let{value:a,done:s}=r.next(o);if(s)return console.log("Final:",a),a;o=a,i++,n(i,o)}}async function le(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=await n.next(r);if(i)return o;r=o}}async function*ye(e){return yield e}var xe=Symbol("MachineMeta"),Me=Symbol("__machine_runtime_meta__");function b(e,t){let n=e[Me]||{},r={...n,...t};t.guards&&n.guards?r.guards=[...t.guards,...n.guards]:t.guards&&(r.guards=[...t.guards]),t.actions&&n.actions?r.actions=[...t.actions,...n.actions]:t.actions&&(r.actions=[...t.actions]),Object.defineProperty(e,Me,{value:r,enumerable:!1,writable:!1,configurable:!0})}function he(e,t){return b(t,{target:e.name||e.toString()}),t}function fe(e,t){return b(t,{description:e}),t}function pe(e,t){return b(t,{guards:[e]}),t}function ge(e,t){return b(t,{invoke:{src:e.src,onDone:e.onDone.name||e.onDone.toString(),onError:e.onError.name||e.onError.toString(),description:e.description}}),t}function Ce(e,t){return b(t,{actions:[e]}),t}function F(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=function(...u){let c=typeof this=="object"&&"context"in this,d=c?this.context:this;if(e(d,...u)){let M=c?this.context:this;return t.apply(M,u)}else if(r==="throw"){let M=o||"Guard condition failed";throw new Error(M)}else if(r==="ignore"){if(c)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(c)return r.apply(this,u);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),b(s,{description:i||"Synchronous guarded transition",guards:[{name:"runtime_guard",description:i||"Synchronous condition check"}]}),s}function A(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=async function(...u){let c=typeof this=="object"&&"context"in this,d=c?this.context:this;if(await Promise.resolve(e(d,...u))){let M=c?this.context:this;return t.apply(M,u)}else if(r==="throw"){let M=o||"Guard condition failed";throw new Error(M)}else if(r==="ignore"){if(c)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(c)return r.apply(this,u);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),b(s,{description:i||"Runtime guarded transition",guards:[{name:"runtime_guard",description:i||"Runtime condition check"}]}),s}function me(e){return{do(t){let n=F(e,t);return n.else=function(r){return F(e,t,{onFail:r})},n}}}function Te(e){return{do(t){let n=A(e,t);return n.else=function(r){return A(e,t,{onFail:r})},n}}}function be(e,t){return t}function we(e,t){let n=e,r=s=>{n=s,t==null||t(s)},{context:o,...i}=e,a=new Proxy({},{get(s,u){let c=n[u];if(typeof c=="function")return(...d)=>{let y=c.apply(n.context,d),M=Object.assign({context:y.context},i);return r(M),M}}});return{get state(){return n},get context(){return n.context},actions:a,setState:r}}function Ee(e,t,n){let r=()=>{let i=e.getContext(),a=n(i),s=t[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(i)},o=new Proxy({},{get(i,a){let s=r(),u=s[a];if(typeof u!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...c)=>u.apply(s.context,c)}});return{get context(){return e.getContext()},get state(){return r()},actions:o}}function Je(e,t){return function(r){return Ee(e,r,t)}}function Qe(e,t){let n=we(t),r=e(n),o=r.next();for(;!o.done;)o=r.next();return o.value}function Xe(e,t){let n=e(t),r=n.next();for(;!r.done;)r=n.next();return r.value}var G=class{constructor(t){this.store=t}get context(){return this.store.getContext()}setContext(t){this.store.setContext(t)}};function Ze(e,t){let n=new e(t);return new Proxy({},{get(r,o){let i=t.getContext();if(o in i)return i[o];let a=n[o];if(typeof a=="function")return(...s)=>a.apply(n,s)},set(r,o,i){let a=t.getContext();if(o in a){let s={...a,[o]:i};return t.setContext(s),!0}return!1},has(r,o){let i=t.getContext();return o in i||typeof n[o]=="function"},ownKeys(r){let o=t.getContext(),i=Object.keys(o),a=Object.getOwnPropertyNames(Object.getPrototypeOf(n)).filter(s=>s!=="constructor"&&typeof n[s]=="function");return Array.from(new Set([...i,...a]))},getOwnPropertyDescriptor(r,o){let i=t.getContext();if(o in i||typeof n[o]=="function")return{value:void 0,writable:!0,enumerable:!0,configurable:!0}}})}function et(e,t,n){let r=()=>{let o=n(e),i=t[o];if(!i)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(o)}".`);return i(e)};return new Proxy(e,{get(o,i,a){if(i in o)return o[i];let s=r(),u=s[i];if(typeof u=="function")return(...c)=>{let d=u.apply(s.context,c);if(typeof d!="object"||d===null){console.warn(`[MutableMachine] Transition "${String(i)}" did not return a valid context object. State may be inconsistent.`);return}Object.keys(o).forEach(y=>delete o[y]),Object.assign(o,d)}},set(o,i,a,s){return o[i]=a,!0},has(o,i){let a=r();return i in o||typeof a[i]=="function"}})}function tt(e){return function(...t){let n=this.context.child;if(typeof n[e]=="function"){let r=n[e](...t);return E(this,{...this.context,child:r})}return this}}function nt(e){return function(){return typeof this.context[e]!="boolean"&&console.warn(`[toggle primitive] Property '${String(e)}' is not a boolean. Toggling may have unexpected results.`),E(this,{...this.context,[e]:!this.context[e]})}}var _=class extends m{constructor(n){super({status:"idle"});this.config=n;this.fetch=n=>new w(this.config,n!=null?n:this.config.initialParams,1)}},w=class extends m{constructor(n,r,o){super({status:"loading",abortController:new AbortController,attempts:o});this.config=n;this.params=r;this.succeed=n=>{var r,o;return(o=(r=this.config).onSuccess)==null||o.call(r,n),new H(this.config,{status:"success",data:n})};this.fail=n=>{var o,i,a;let r=(o=this.config.maxRetries)!=null?o:3;return this.context.attempts<r?new W(this.config,this.params,n,this.context.attempts):((a=(i=this.config).onError)==null||a.call(i,n),new $(this.config,{status:"error",error:n}))};this.cancel=()=>(this.context.abortController.abort(),new D(this.config));this.execute()}async execute(){}},W=class extends m{constructor(n,r,o,i){super({status:"retrying",error:o,attempts:i});this.config=n;this.params=r;this.retry=n=>new w(this.config,n!=null?n:this.params,this.context.attempts+1)}},H=class extends m{constructor(n,r){super(r);this.config=n;this.refetch=n=>new w(this.config,n!=null?n:this.config.initialParams,1)}},$=class extends m{constructor(n,r){super(r);this.config=n;this.retry=n=>new w(this.config,n!=null?n:this.config.initialParams,1)}},D=class extends m{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new w(this.config,n!=null?n:this.config.initialParams,1)}};function rt(e){return new _(e)}function I(e,t){let n={...e.context,...t.context},r={...e},o={...t};delete r.context,delete o.context;let i={};for(let a in r){let s=r[a];i[a]=(...u)=>{let c=s.apply(e.context,u);return I(c,t)}}for(let a in o){let s=o[a];i[a]=(...u)=>{let c=s.apply(t.context,u);return I(e,c)}}return{context:n,...i}}var L=Symbol("CANCEL");function g(e,t,n={}){let{continueOnError:r=!1,logErrors:o=!0,onError:i}=n,a={...e};for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&s!=="context"&&typeof e[s]!="function"&&(a[s]=e[s]);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let u=e[s];typeof u=="function"&&s!=="context"&&(a[s]=function(...c){let d=s,y=a.context,M=()=>{let l;try{l=u.apply(this,c)}catch(h){if(t.error)try{t.error({transitionName:d,context:y,args:[...c],error:h})}catch(f){if(!r)throw f;o&&console.error(`Middleware error hook error for ${d}:`,f),i==null||i(f,"error",{transitionName:d,context:y,args:c,error:h})}throw h}let x=h=>{if(h&&typeof h=="object"&&h.context){for(let f in a)Object.prototype.hasOwnProperty.call(a,f)&&f!=="context"&&!(f in h)&&(h[f]=a[f]);for(let f in h){if(!Object.prototype.hasOwnProperty.call(h,f))continue;typeof h[f]=="function"&&f!=="context"&&a[f]&&(h[f]=a[f])}}return h};if(l&&typeof l.then=="function")return l.then(f=>{if(x(f),t.after)try{let C=t.after({transitionName:d,prevContext:y,nextContext:f.context,args:[...c]});if(C&&typeof C.then=="function")return C.then(()=>f)}catch(C){if(!r)throw C;o&&console.error(`Middleware after hook error for ${d}:`,C),i==null||i(C,"after",{transitionName:d,prevContext:y,nextContext:f.context,args:c})}return f});if(x(l),t.after)try{let h=t.after({transitionName:d,prevContext:y,nextContext:l.context,args:[...c]});if(h&&typeof h=="object"&&h&&"then"in h)return h.then(()=>l).catch(f=>{if(!r)throw f;return o&&console.error(`Middleware after hook error for ${d}:`,f),i==null||i(f,"after",{transitionName:d,prevContext:y,nextContext:l.context,args:c}),l})}catch(h){if(!r)throw h;o&&console.error(`Middleware after hook error for ${d}:`,h),i==null||i(h,"after",{transitionName:d,prevContext:y,nextContext:l.context,args:c})}return l};if(t.before)try{let l=t.before({transitionName:d,context:y,args:[...c]});if(l&&typeof l=="object"&&l&&"then"in l)return l.then(x=>x===L?a:M()).catch(x=>{if(!r)throw x;return o&&console.error(`Middleware before hook error for ${d}:`,x),i==null||i(x,"before",{transitionName:d,context:y,args:c}),M()});if(l===L)return a}catch(l){if(!r)throw l;o&&console.error(`Middleware before hook error for ${d}:`,l),i==null||i(l,"before",{transitionName:d,context:y,args:c})}return M()})}return a}function V(e,t={}){let{logger:n=console.log,includeArgs:r=!1,includeContext:o=!0}=t;return g(e,{before:({transitionName:i,args:a})=>{let s=r?`→ ${i} [${a.join(", ")}]`:`→ ${i}`;n(s)},after:({transitionName:i,nextContext:a})=>{let s=o?` ${JSON.stringify(a)}`:"";n(`✓ ${i}${s}`)},error:({transitionName:i,error:a})=>{console.error(`[Machine] ${i} failed:`,a)}})}function U(e,t,n={}){let{eventPrefix:r="state_transition",includePrevContext:o=!1,includeArgs:i=!1}=n;return g(e,{after:({transitionName:a,prevContext:s,nextContext:u,args:c})=>{let d=`${r}.${a}`,y={transition:a};o&&(y.from=s),y.to=u,i&&(y.args=c),t(d,y)}})}function q(e,t){return g(e,{before:n=>{if(t(n)===!1)throw new Error(`Validation failed for transition: ${n.transitionName}`)}})}function Y(e,t){return g(e,{before:n=>{if(!t(n))throw new Error(`Unauthorized transition: ${n.transitionName}`)}})}function J(e,t,n={}){let{includeArgs:r=!1}=n;return g(e,{error:o=>{let i={transition:o.transitionName,context:o.context,...r&&{args:o.args}};t(o.error,i)}})}function Q(e,t){let n=new Map;return g(e,{before:r=>{n.set(r.transitionName,Date.now())},after:r=>{let o=n.get(r.transitionName);if(o){let i=Date.now()-o;n.delete(r.transitionName);let a={transitionName:r.transitionName,duration:i,context:r.nextContext||r.prevContext};t(a)}}})}function X(e,t={}){var u,c;let{maxAttempts:n=(u=t.maxRetries)!=null?u:3,shouldRetry:r=()=>!0,backoffMs:o=(c=t.delay)!=null?c:100,backoffMultiplier:i=2,onRetry:a}=t,s={...e};for(let d in e){if(!Object.prototype.hasOwnProperty.call(e,d))continue;let y=e[d];typeof y=="function"&&d!=="context"&&(s[d]=async function(...M){let l,x=0;for(;x<n;)try{return await y.apply(this,M)}catch(h){if(l=h,x++,x<n&&r(l,x)){a==null||a(l,x);let C=(typeof o=="function"?o(x):o)*Math.pow(i,x-1);await new Promise(T=>setTimeout(T,C))}else throw l}throw l})}return s}function ot(e,t){return n=>g(n,e,t)}function S(e,t={}){let{maxSize:n,serializer:r,onEntry:o}=t,i=[],a=0,s=g(e,{before:({transitionName:u,args:c})=>{let d={id:`entry-${a++}`,transitionName:u,args:[...c],timestamp:Date.now()};if(r)try{d.serializedArgs=r.serialize(c)}catch(y){console.error("Failed to serialize history args:",y)}i.push(d),n&&i.length>n&&i.shift(),o==null||o(d)}});return Object.assign(s,{history:i,clearHistory:()=>{i.length=0,a=0}})}function R(e,t={}){let{maxSize:n,serializer:r,captureSnapshot:o,onlyOnChange:i=!1}=t,a=[],s=0,u=g(e,{after:({transitionName:d,prevContext:y,nextContext:M})=>{if(i&&JSON.stringify(y)===JSON.stringify(M))return;let l={id:`snapshot-${s++}`,transitionName:d,before:{...y},after:{...M},timestamp:Date.now()};if(r)try{l.serializedBefore=r.serialize(y),l.serializedAfter=r.serialize(M)}catch(x){console.error("Failed to serialize snapshot:",x)}if(o)try{l.diff=o(y,M)}catch(x){console.error("Failed to capture snapshot:",x)}a.push(l),n&&a.length>n&&a.shift()}});return Object.assign(u,{snapshots:a,clearSnapshots:()=>{a.length=0,s=0},restoreSnapshot:d=>{let y=Object.fromEntries(Object.entries(e).filter(([M])=>M!=="context"&&M!=="snapshots"&&M!=="clearSnapshots"&&M!=="restoreSnapshot"&&typeof e[M]=="function"));return Object.assign({context:d},y)}})}function j(e,t={}){let{maxSize:n,serializer:r,onRecord:o}=t,i=[],a=[],s=0,u=0,c=g(e,{before:({transitionName:M,args:l})=>{let x={id:`entry-${s++}`,transitionName:M,args:[...l],timestamp:Date.now()};if(r)try{x.serializedArgs=r.serialize(l)}catch(h){console.error("Failed to serialize history args:",h)}i.push(x),n&&i.length>n&&i.shift(),o==null||o("history",x)},after:({transitionName:M,prevContext:l,nextContext:x})=>{let h={id:`snapshot-${u++}`,transitionName:M,before:{...l},after:{...x},timestamp:Date.now()};if(r)try{h.serializedBefore=r.serialize(l),h.serializedAfter=r.serialize(x)}catch(f){console.error("Failed to serialize snapshot:",f)}a.push(h),n&&a.length>n&&a.shift(),o==null||o("snapshot",h)}});return Object.assign(c,{history:i,snapshots:a,clearHistory:()=>{i.length=0,s=0},clearSnapshots:()=>{a.length=0,u=0},clearTimeTravel:()=>{i.length=0,a.length=0,s=0,u=0},restoreSnapshot:M=>{let l=Object.fromEntries(Object.entries(e).filter(([x])=>x!=="context"&&x!=="history"&&x!=="snapshots"&&x!=="clearHistory"&&x!=="clearSnapshots"&&x!=="restoreSnapshot"&&x!=="clearTimeTravel"&&x!=="replayFrom"&&typeof e[x]=="function"));return Object.assign({context:M},l)},replayFrom:M=>{var C;if(M<0||M>=i.length)throw new Error(`Invalid replay start index: ${M}`);let l=(C=a[M])==null?void 0:C.before;if(!l)throw new Error(`No snapshot available for index ${M}`);let x=i.slice(M),f=Object.assign({context:l},Object.fromEntries(Object.entries(e).filter(([T])=>T!=="context"&&typeof e[T]=="function")));for(let T of x){let ie=f[T.transitionName];ie&&(f=ie.apply(f.context,T.args))}return f}})}function it(e,...t){return t.reduce((n,r)=>r(n),e)}function v(e,...t){return t.reduce((n,r)=>r(n),e)}var Z=class e{constructor(t){this.machine=t}with(t){let n=t(this.machine);return new e(n)}build(){return this.machine}};function at(e){return new Z(e)}function B(e,t){let n=function(r){return t(r)?e(r):r};return n.middleware=e,n.when=t,n}function st(e){return B(e,()=>typeof process!="undefined"?!1:typeof window!="undefined"?!window.location.hostname.includes("production"):!1)}function ct(e,t,n){return B(n,r=>r.context[e]===t)}function dt(){let e=new Map;return{register(t,n,r,o){if(e.has(t))throw new Error(`Middleware '${t}' is already registered`);return e.set(t,{name:t,middleware:n,description:r,priority:o}),this},unregister(t){return e.delete(t)},has(t){return e.has(t)},get(t){return e.get(t)},list(){return Array.from(e.values()).sort((t,n)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=n.priority)!=null?o:0)})},apply(t,n){let r=n.map(o=>{let i=e.get(o);if(!i)throw new Error(`Middleware '${o}' is not registered`);return i}).sort((o,i)=>{var a,s;return((a=o.priority)!=null?a:0)-((s=i.priority)!=null?s:0)});return v(t,...r.map(o=>o.middleware))},applyAll(t){let n=this.list();return v(t,...n.map(r=>r.middleware))}}}function ut(e={}){let{continueOnError:t=!1,logErrors:n=!0,onError:r}=e;return(o,...i)=>{let a=o,s=[],u=!0;for(let c=0;c<i.length;c++){let d=i[c];try{if("middleware"in d&&"when"in d){if(!d.when(a))continue;a=d.middleware(a)}else a=d(a)}catch(y){if(u=!1,!t)throw y;s.push({error:y,middlewareIndex:c,middlewareName:d.name}),n&&console.error(`Pipeline middleware error at index ${c}:`,y),r==null||r(y,c,d.name)}}return{machine:a,errors:s,success:u}}}function lt(...e){return t=>v(t,...e)}function yt(e,t){return n=>{for(let[r,o]of e)if(r(n))return o(n);return t?t(n):n}}function ee(e){return typeof e=="function"&&e.length===1}function Mt(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"middleware"in e&&"when"in e&&ee(e.middleware)&&typeof e.when=="function"}function xt(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"prevContext"in e&&"nextContext"in e&&"args"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&(!t||O(e.prevContext,t)&&O(e.nextContext,t))}function ht(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"context"in e&&"args"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&(!t||O(e.context,t))}function ft(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"context"in e&&"args"in e&&"error"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&e.error instanceof Error&&(!t||O(e.context,t))}function pt(e,t){if(e===null||typeof e!="object")return!1;let n=e;return!("before"in n&&n.before!==void 0&&typeof n.before!="function"||"after"in n&&n.after!==void 0&&typeof n.after!="function"||"error"in n&&n.error!==void 0&&typeof n.error!="function")}function gt(e){return e===void 0||e!==null&&typeof e=="object"&&("continueOnError"in e?typeof e.continueOnError=="boolean":!0)&&("logErrors"in e?typeof e.logErrors=="boolean":!0)&&("onError"in e?typeof e.onError=="function"||e.onError===void 0:!0)}function O(e,t){return e!==null&&typeof e=="object"}function Ct(e){return e!==null&&typeof e=="object"&&"name"in e&&"middleware"in e&&typeof e.name=="string"&&ee(e.middleware)&&("description"in e?typeof e.description=="string"||e.description===void 0:!0)&&("priority"in e?typeof e.priority=="number"||e.priority===void 0:!0)}function mt(e){return e===void 0||e!==null&&typeof e=="object"&&("continueOnError"in e?typeof e.continueOnError=="boolean":!0)&&("logErrors"in e?typeof e.logErrors=="boolean":!0)&&("onError"in e?typeof e.onError=="function"||e.onError===void 0:!0)}var P=class{constructor(t){this.machine=t;this.middlewares=[]}withLogging(t){return this.middlewares.push(n=>V(n,t)),this}withAnalytics(t,n){return this.middlewares.push(r=>U(r,t,n)),this}withValidation(t,n){return this.middlewares.push(r=>q(r,t)),this}withPermissions(t){return this.middlewares.push(n=>Y(n,t)),this}withErrorReporting(t,n){return this.middlewares.push(r=>J(r,t,n)),this}withPerformanceMonitoring(t,n){return this.middlewares.push(r=>Q(r,t)),this}withRetry(t){return this.middlewares.push(n=>X(n,t)),this}withHistory(t){return this.middlewares.push(n=>S(n,t)),this}withSnapshot(t){return this.middlewares.push(n=>R(n,t)),this}withTimeTravel(t){return this.middlewares.push(n=>j(n,t)),this}withDebugging(){return this.middlewares.push(t=>Ae(t)),this}withCustom(t){return this.middlewares.push(t),this}withConditional(t,n){return this.middlewares.push(B(t,n)),this}build(){let t=this.machine;for(let n of this.middlewares)t=n(t);return t}getChain(){return[...this.middlewares]}clear(){return this.middlewares=[],this}};function Fe(e){return new P(e)}function Tt(e={}){return{create:t=>{let n=Fe(t);return e.logging&&n.withLogging(e.logging),e.analytics&&n.withAnalytics(e.analytics.track,e.analytics.options),e.history&&n.withHistory(e.history),e.snapshot&&n.withSnapshot(e.snapshot),e.timeTravel&&n.withTimeTravel(e.timeTravel),e.retry&&n.withRetry(e.retry),n}}}function Ae(e){return j(R(S(e)))}function Se(e,t){return e instanceof t}function Re(e,...t){return{type:e,args:t}}function je(e,t){return E(e,n=>({...n,...t}))}async function ve(e,...t){let n=e;for(let r of t)n=await r(n);return n}function Oe(e,t){return t?console.log(t,e.context):console.log(e.context),e}function Pe(e,t){return function(...n){let r=t(this.context,...n);return p(r,e())}}function Be(e,t,...n){return e.apply(t,n)}function te(e){return new Proxy(e,{get(t,n){let r=t[n];return typeof r=="function"?function(...o){let i=r.apply(t.context,o);return i&&typeof i=="object"&&"context"in i?te(i):i}:r}})}var k=class e{constructor(t){return this.wrappedMachine=t,new Proxy(this,{get:(n,r)=>{if(r==="wrappedMachine")return Reflect.get(n,r);if(r==="context")return this.wrappedMachine.context;let o=this.wrappedMachine[r];return typeof o=="function"?(...i)=>{let a=o.apply(this.wrappedMachine.context,i);return a&&typeof a=="object"&&"context"in a?new e(a):a}:o}})}};function ke(){return function(t){return function(...n){let r=t(this.context,...n);return p(r,this)}}}function ne(e){return{machine:e,addTransition:function(t,n){let r=function(...i){let a=n(this.context,...i);return p(a,this)},o=K(e,{[t]:r});return ne(o)}}}function re(e){return function(n){let r={},o=Object.fromEntries(Object.entries(n).map(([i,a])=>[i,function(...s){let u=a(this.context,...s);return p(u,r)}]));return Object.assign(r,o),p(e,r)}}function Ke(e,t){return t!==void 0?p(e,t):re(e)}function p(e,t){if(typeof t=="function"){let o;o=t(s=>{let u=p(s,o),c=Object.fromEntries(Object.entries(o).map(([d,y])=>[d,y.bind(s)]));return Object.assign(u,c)});let a=Object.fromEntries(Object.entries(o).map(([s,u])=>[s,u.bind(e)]));return Object.assign({context:e},a)}let n="context"in t?Object.fromEntries(Object.entries(t).filter(([o])=>o!=="context")):t;return Object.assign({context:e},n)}function oe(e,t){if(typeof t=="function"){let o;o=t(s=>{let u=oe(s,o),c=Object.fromEntries(Object.entries(o).map(([d,y])=>[d,y.bind(s)]));return Object.assign(u,c)});let a=Object.fromEntries(Object.entries(o).map(([s,u])=>[s,u.bind(e)]));return Object.assign({context:e},a)}let n="context"in t?Object.fromEntries(Object.entries(t).filter(([o])=>o!=="context")):t;return Object.assign({context:e},n)}function Ne(){return e=>{let t=Object.fromEntries(Object.entries(e).map(([n,r])=>[n,function(...o){let i=r(this.context,...o);return p(i,t)}]));return n=>p(n,t)}}function E(e,t){let{context:n,...r}=e,o=typeof t=="function"?t(n):t;return p(o,r)}function ze(e,t){let{context:n,...r}=e,o={...r,...t};return p(n,o)}function K(e,t){let{context:n,...r}=e,o={...r,...t};return p(n,o)}function Ge(e,t){return(...n)=>{let r=e(...n),o=t(),i={...r.context,...o.context},{context:a,...s}=r,{context:u,...c}=o,d={...s,...c};return p(i,d)}}function _e(e){let{context:t,...n}=e;return r=>p(r,n)}function We(e,t,n){let r=e.context[t],o=n[r];if(!o)throw new Error(`No handler found for state: ${String(r)}`);return o(e.context)}function He(e,t,n){return e.context[t]===n}function $e(e,t){let n=e,r=null;async function o(i){r&&(r.abort(),r=null);let a=n[i.type];if(typeof a!="function")throw new Error(`[Machine] Unknown event type '${String(i.type)}' on current state.`);let s=new AbortController;r=s;try{let c=await a.apply(n.context,[...i.args,{signal:s.signal}]);return s.signal.aborted||(n=c,t==null||t(n)),n}finally{r===s&&(r=null)}}return{get state(){return n.context},dispatch:o,stop:()=>{r&&(r.abort(),r=null)}}}var m=class{constructor(t){this.context=t}};function De(e,t){let{context:n,...r}=e;return p(t(n),r)}
|
|
1
|
+
"use strict";var N=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var Ue=(e,t)=>{for(var n in t)N(e,n,{get:t[n],enumerable:!0})},qe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Le(t))!Ve.call(e,o)&&o!==n&&N(e,o,{get:()=>t[o],enumerable:!(r=Ie(t,o))||r.enumerable});return e};var Ye=e=>qe(N({},"__esModule",{value:!0}),e);var bt={};Ue(bt,{BoundMachine:()=>k,CANCEL:()=>L,META_KEY:()=>xe,MachineBase:()=>m,MiddlewareBuilder:()=>P,MultiMachineBase:()=>G,action:()=>Ce,bindTransitions:()=>te,branch:()=>lt,call:()=>Be,chain:()=>at,combine:()=>yt,combineFactories:()=>Ge,compose:()=>it,composeTyped:()=>v,createAsyncMachine:()=>oe,createCustomMiddleware:()=>ot,createEnsemble:()=>Ee,createEnsembleFactory:()=>Je,createEvent:()=>Re,createFetchMachine:()=>rt,createFlow:()=>de,createFunctionalMachine:()=>re,createMachine:()=>p,createMachineBuilder:()=>_e,createMachineFactory:()=>Ne,createMiddleware:()=>g,createMiddlewareFactory:()=>Tt,createMiddlewareRegistry:()=>dt,createMultiMachine:()=>Ze,createMutableMachine:()=>et,createParallelMachine:()=>I,createPipeline:()=>ut,createRunner:()=>we,createTransition:()=>Pe,createTransitionExtender:()=>ne,createTransitionFactory:()=>ke,delegateToChild:()=>tt,describe:()=>fe,extendTransitions:()=>K,guard:()=>F,guardAsync:()=>A,guarded:()=>pe,hasState:()=>He,inDevelopment:()=>st,invoke:()=>ge,isConditionalMiddleware:()=>Mt,isMiddlewareContext:()=>ht,isMiddlewareError:()=>ft,isMiddlewareFn:()=>ee,isMiddlewareHooks:()=>pt,isMiddlewareOptions:()=>gt,isMiddlewareResult:()=>xt,isNamedMiddleware:()=>Ct,isPipelineConfig:()=>mt,isState:()=>Se,logState:()=>Oe,matchMachine:()=>We,mergeContext:()=>je,metadata:()=>be,middlewareBuilder:()=>Fe,next:()=>De,overrideTransitions:()=>ze,pipeTransitions:()=>ve,run:()=>z,runAsync:()=>ye,runMachine:()=>$e,runSequence:()=>ce,runWithDebug:()=>ue,runWithEnsemble:()=>Xe,runWithRunner:()=>Qe,setContext:()=>E,state:()=>Ke,step:()=>ae,stepAsync:()=>le,toggle:()=>nt,transitionTo:()=>he,when:()=>B,whenContext:()=>ct,whenGuard:()=>me,whenGuardAsync:()=>Te,withAnalytics:()=>U,withDebugging:()=>Ae,withErrorReporting:()=>J,withHistory:()=>S,withLogging:()=>V,withPerformanceMonitoring:()=>Q,withPermissions:()=>Y,withRetry:()=>X,withSnapshot:()=>R,withTimeTravel:()=>j,withValidation:()=>q,yieldMachine:()=>se});module.exports=Ye(bt);function z(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=n.next(r);if(i)return o;r=o}}function ae(e){return function*(){return yield e}()}function se(e){return e}function ce(e,t){return t.reduce((n,r)=>z(r,n),e)}function de(e){return e}function ue(e,t,n=(r,o)=>{console.log(`Step ${r}:`,o.context)}){let r=e(t),o=t,i=0;for(n(i,o);;){let{value:a,done:s}=r.next(o);if(s)return console.log("Final:",a),a;o=a,i++,n(i,o)}}async function ye(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=await n.next(r);if(i)return o;r=o}}async function*le(e){return yield e}var xe=Symbol("MachineMeta"),Me=Symbol("__machine_runtime_meta__");function b(e,t){let n=e[Me]||{},r={...n,...t};t.guards&&n.guards?r.guards=[...t.guards,...n.guards]:t.guards&&(r.guards=[...t.guards]),t.actions&&n.actions?r.actions=[...t.actions,...n.actions]:t.actions&&(r.actions=[...t.actions]),Object.defineProperty(e,Me,{value:r,enumerable:!1,writable:!1,configurable:!0})}function he(e,t){return b(t,{target:e.name||e.toString()}),t}function fe(e,t){return b(t,{description:e}),t}function pe(e,t){return b(t,{guards:[e]}),t}function ge(e,t){return b(t,{invoke:{src:e.src,onDone:e.onDone.name||e.onDone.toString(),onError:e.onError.name||e.onError.toString(),description:e.description}}),t}function Ce(e,t){return b(t,{actions:[e]}),t}function F(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=function(...u){let c=typeof this=="object"&&"context"in this,d=c?this.context:this;if(e(d,...u)){let M=c?this.context:this;return t.apply(M,u)}else if(r==="throw"){let M=o||"Guard condition failed";throw new Error(M)}else if(r==="ignore"){if(c)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(c)return r.apply(this,u);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),b(s,{description:i||"Synchronous guarded transition",guards:[{name:"runtime_guard",description:i||"Synchronous condition check"}]}),s}function A(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=async function(...u){let c=typeof this=="object"&&"context"in this,d=c?this.context:this;if(await Promise.resolve(e(d,...u))){let M=c?this.context:this;return t.apply(M,u)}else if(r==="throw"){let M=o||"Guard condition failed";throw new Error(M)}else if(r==="ignore"){if(c)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(c)return r.apply(this,u);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),b(s,{description:i||"Runtime guarded transition",guards:[{name:"runtime_guard",description:i||"Runtime condition check"}]}),s}function me(e){return{do(t){let n=F(e,t);return n.else=function(r){return F(e,t,{onFail:r})},n}}}function Te(e){return{do(t){let n=A(e,t);return n.else=function(r){return A(e,t,{onFail:r})},n}}}function be(e,t){return t}function we(e,t){let n=e,r=s=>{n=s,t==null||t(s)},{context:o,...i}=e,a=new Proxy({},{get(s,u){let c=n[u];if(typeof c=="function")return(...d)=>{let l=c.apply(n.context,d),M=Object.assign({context:l.context},i);return r(M),M}}});return{get state(){return n},get context(){return n.context},actions:a,setState:r}}function Ee(e,t,n){let r=()=>{let i=e.getContext(),a=n(i),s=t[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(i)},o=new Proxy({},{get(i,a){let s=r(),u=s[a];if(typeof u!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...c)=>u.apply(s.context,c)}});return{get context(){return e.getContext()},get state(){return r()},actions:o}}function Je(e,t){return function(r){return Ee(e,r,t)}}function Qe(e,t){let n=we(t),r=e(n),o=r.next();for(;!o.done;)o=r.next();return o.value}function Xe(e,t){let n=e(t),r=n.next();for(;!r.done;)r=n.next();return r.value}var G=class{constructor(t){this.store=t}get context(){return this.store.getContext()}setContext(t){this.store.setContext(t)}};function Ze(e,t){let n=new e(t);return new Proxy({},{get(r,o){let i=t.getContext();if(o in i)return i[o];let a=n[o];if(typeof a=="function")return(...s)=>a.apply(n,s)},set(r,o,i){let a=t.getContext();if(o in a){let s={...a,[o]:i};return t.setContext(s),!0}return!1},has(r,o){let i=t.getContext();return o in i||typeof n[o]=="function"},ownKeys(r){let o=t.getContext(),i=Object.keys(o),a=Object.getOwnPropertyNames(Object.getPrototypeOf(n)).filter(s=>s!=="constructor"&&typeof n[s]=="function");return Array.from(new Set([...i,...a]))},getOwnPropertyDescriptor(r,o){let i=t.getContext();if(o in i||typeof n[o]=="function")return{value:void 0,writable:!0,enumerable:!0,configurable:!0}}})}function et(e,t,n){let r=()=>{let o=n(e),i=t[o];if(!i)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(o)}".`);return i(e)};return new Proxy(e,{get(o,i,a){if(i in o)return o[i];let s=r(),u=s[i];if(typeof u=="function")return(...c)=>{let d=u.apply(s.context,c);if(typeof d!="object"||d===null){console.warn(`[MutableMachine] Transition "${String(i)}" did not return a valid context object. State may be inconsistent.`);return}Object.keys(o).forEach(l=>delete o[l]),Object.assign(o,d)}},set(o,i,a,s){return o[i]=a,!0},has(o,i){let a=r();return i in o||typeof a[i]=="function"}})}function tt(e){return function(...t){let n=this.context.child;if(typeof n[e]=="function"){let r=n[e](...t);return E(this,{...this.context,child:r})}return this}}function nt(e){return function(){return typeof this.context[e]!="boolean"&&console.warn(`[toggle primitive] Property '${String(e)}' is not a boolean. Toggling may have unexpected results.`),E(this,{...this.context,[e]:!this.context[e]})}}var _=class extends m{constructor(n){super({status:"idle"});this.config=n;this.fetch=n=>new w(this.config,n!=null?n:this.config.initialParams,1)}},w=class extends m{constructor(n,r,o){super({status:"loading",abortController:new AbortController,attempts:o});this.config=n;this.params=r;this.succeed=n=>{var r,o;return(o=(r=this.config).onSuccess)==null||o.call(r,n),new H(this.config,{status:"success",data:n})};this.fail=n=>{var o,i,a;let r=(o=this.config.maxRetries)!=null?o:3;return this.context.attempts<r?new W(this.config,this.params,n,this.context.attempts):((a=(i=this.config).onError)==null||a.call(i,n),new $(this.config,{status:"error",error:n}))};this.cancel=()=>(this.context.abortController.abort(),new D(this.config));this.execute()}async execute(){}},W=class extends m{constructor(n,r,o,i){super({status:"retrying",error:o,attempts:i});this.config=n;this.params=r;this.retry=n=>new w(this.config,n!=null?n:this.params,this.context.attempts+1)}},H=class extends m{constructor(n,r){super(r);this.config=n;this.refetch=n=>new w(this.config,n!=null?n:this.config.initialParams,1)}},$=class extends m{constructor(n,r){super(r);this.config=n;this.retry=n=>new w(this.config,n!=null?n:this.config.initialParams,1)}},D=class extends m{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new w(this.config,n!=null?n:this.config.initialParams,1)}};function rt(e){return new _(e)}function I(e,t){let n={...e.context,...t.context},r={...e},o={...t};delete r.context,delete o.context;let i={};for(let a in r){let s=r[a];i[a]=(...u)=>{let c=s.apply(e.context,u);return I(c,t)}}for(let a in o){let s=o[a];i[a]=(...u)=>{let c=s.apply(t.context,u);return I(e,c)}}return{context:n,...i}}var L=Symbol("CANCEL");function g(e,t,n={}){let{continueOnError:r=!1,logErrors:o=!0,onError:i}=n,a={...e};for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&s!=="context"&&typeof e[s]!="function"&&(a[s]=e[s]);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let u=e[s];typeof u=="function"&&s!=="context"&&(a[s]=function(...c){let d=s,l=a.context,M=()=>{let y;try{y=u.apply(this,c)}catch(h){if(t.error)try{t.error({transitionName:d,context:l,args:[...c],error:h})}catch(f){if(!r)throw f;o&&console.error(`Middleware error hook error for ${d}:`,f),i==null||i(f,"error",{transitionName:d,context:l,args:c,error:h})}throw h}let x=h=>{if(h&&typeof h=="object"&&h.context){for(let f in a)Object.prototype.hasOwnProperty.call(a,f)&&f!=="context"&&!(f in h)&&(h[f]=a[f]);for(let f in h){if(!Object.prototype.hasOwnProperty.call(h,f))continue;typeof h[f]=="function"&&f!=="context"&&a[f]&&(h[f]=a[f])}}return h};if(y&&typeof y.then=="function")return y.then(f=>{if(x(f),t.after)try{let C=t.after({transitionName:d,prevContext:l,nextContext:f.context,args:[...c]});if(C&&typeof C.then=="function")return C.then(()=>f)}catch(C){if(!r)throw C;o&&console.error(`Middleware after hook error for ${d}:`,C),i==null||i(C,"after",{transitionName:d,prevContext:l,nextContext:f.context,args:c})}return f});if(x(y),t.after)try{let h=t.after({transitionName:d,prevContext:l,nextContext:y.context,args:[...c]});if(h&&typeof h=="object"&&h&&"then"in h)return h.then(()=>y).catch(f=>{if(!r)throw f;return o&&console.error(`Middleware after hook error for ${d}:`,f),i==null||i(f,"after",{transitionName:d,prevContext:l,nextContext:y.context,args:c}),y})}catch(h){if(!r)throw h;o&&console.error(`Middleware after hook error for ${d}:`,h),i==null||i(h,"after",{transitionName:d,prevContext:l,nextContext:y.context,args:c})}return y};if(t.before)try{let y=t.before({transitionName:d,context:l,args:[...c]});if(y&&typeof y=="object"&&y&&"then"in y)return y.then(x=>x===L?a:M()).catch(x=>{if(!r)throw x;return o&&console.error(`Middleware before hook error for ${d}:`,x),i==null||i(x,"before",{transitionName:d,context:l,args:c}),M()});if(y===L)return a}catch(y){if(!r)throw y;o&&console.error(`Middleware before hook error for ${d}:`,y),i==null||i(y,"before",{transitionName:d,context:l,args:c})}return M()})}return a}function V(e,t={}){let{logger:n=console.log,includeArgs:r=!1,includeContext:o=!0}=t;return g(e,{before:({transitionName:i,args:a})=>{let s=r?`→ ${i} [${a.join(", ")}]`:`→ ${i}`;n(s)},after:({transitionName:i,nextContext:a})=>{let s=o?` ${JSON.stringify(a)}`:"";n(`✓ ${i}${s}`)},error:({transitionName:i,error:a})=>{console.error(`[Machine] ${i} failed:`,a)}})}function U(e,t,n={}){let{eventPrefix:r="state_transition",includePrevContext:o=!1,includeArgs:i=!1}=n;return g(e,{after:({transitionName:a,prevContext:s,nextContext:u,args:c})=>{let d=`${r}.${a}`,l={transition:a};o&&(l.from=s),l.to=u,i&&(l.args=c),t(d,l)}})}function q(e,t){return g(e,{before:n=>{if(t(n)===!1)throw new Error(`Validation failed for transition: ${n.transitionName}`)}})}function Y(e,t){return g(e,{before:n=>{if(!t(n))throw new Error(`Unauthorized transition: ${n.transitionName}`)}})}function J(e,t,n={}){let{includeArgs:r=!1}=n;return g(e,{error:o=>{let i={transition:o.transitionName,context:o.context,...r&&{args:o.args}};t(o.error,i)}})}function Q(e,t){let n=new Map;return g(e,{before:r=>{n.set(r.transitionName,Date.now())},after:r=>{let o=n.get(r.transitionName);if(o){let i=Date.now()-o;n.delete(r.transitionName);let a={transitionName:r.transitionName,duration:i,context:r.nextContext||r.prevContext};t(a)}}})}function X(e,t={}){var u,c;let{maxAttempts:n=(u=t.maxRetries)!=null?u:3,shouldRetry:r=()=>!0,backoffMs:o=(c=t.delay)!=null?c:100,backoffMultiplier:i=2,onRetry:a}=t,s={...e};for(let d in e){if(!Object.prototype.hasOwnProperty.call(e,d))continue;let l=e[d];typeof l=="function"&&d!=="context"&&(s[d]=async function(...M){let y,x=0;for(;x<n;)try{return await l.apply(this,M)}catch(h){if(y=h,x++,x<n&&r(y,x)){a==null||a(y,x);let C=(typeof o=="function"?o(x):o)*Math.pow(i,x-1);await new Promise(T=>setTimeout(T,C))}else throw y}throw y})}return s}function ot(e,t){return n=>g(n,e,t)}function S(e,t={}){let{maxSize:n,serializer:r,onEntry:o}=t,i=[],a=0,s=g(e,{before:({transitionName:u,args:c})=>{let d={id:`entry-${a++}`,transitionName:u,args:[...c],timestamp:Date.now()};if(r)try{d.serializedArgs=r.serialize(c)}catch(l){console.error("Failed to serialize history args:",l)}i.push(d),n&&i.length>n&&i.shift(),o==null||o(d)}});return Object.assign(s,{history:i,clearHistory:()=>{i.length=0,a=0}})}function R(e,t={}){let{maxSize:n,serializer:r,captureSnapshot:o,onlyOnChange:i=!1}=t,a=[],s=0,u=g(e,{after:({transitionName:d,prevContext:l,nextContext:M})=>{if(i&&JSON.stringify(l)===JSON.stringify(M))return;let y={id:`snapshot-${s++}`,transitionName:d,before:{...l},after:{...M},timestamp:Date.now()};if(r)try{y.serializedBefore=r.serialize(l),y.serializedAfter=r.serialize(M)}catch(x){console.error("Failed to serialize snapshot:",x)}if(o)try{y.diff=o(l,M)}catch(x){console.error("Failed to capture snapshot:",x)}a.push(y),n&&a.length>n&&a.shift()}});return Object.assign(u,{snapshots:a,clearSnapshots:()=>{a.length=0,s=0},restoreSnapshot:d=>{let l=Object.fromEntries(Object.entries(e).filter(([M])=>M!=="context"&&M!=="snapshots"&&M!=="clearSnapshots"&&M!=="restoreSnapshot"&&typeof e[M]=="function"));return Object.assign({context:d},l)}})}function j(e,t={}){let{maxSize:n,serializer:r,onRecord:o}=t,i=[],a=[],s=0,u=0,c=g(e,{before:({transitionName:M,args:y})=>{let x={id:`entry-${s++}`,transitionName:M,args:[...y],timestamp:Date.now()};if(r)try{x.serializedArgs=r.serialize(y)}catch(h){console.error("Failed to serialize history args:",h)}i.push(x),n&&i.length>n&&i.shift(),o==null||o("history",x)},after:({transitionName:M,prevContext:y,nextContext:x})=>{let h={id:`snapshot-${u++}`,transitionName:M,before:{...y},after:{...x},timestamp:Date.now()};if(r)try{h.serializedBefore=r.serialize(y),h.serializedAfter=r.serialize(x)}catch(f){console.error("Failed to serialize snapshot:",f)}a.push(h),n&&a.length>n&&a.shift(),o==null||o("snapshot",h)}});return Object.assign(c,{history:i,snapshots:a,clearHistory:()=>{i.length=0,s=0},clearSnapshots:()=>{a.length=0,u=0},clearTimeTravel:()=>{i.length=0,a.length=0,s=0,u=0},restoreSnapshot:M=>{let y=Object.fromEntries(Object.entries(e).filter(([x])=>x!=="context"&&x!=="history"&&x!=="snapshots"&&x!=="clearHistory"&&x!=="clearSnapshots"&&x!=="restoreSnapshot"&&x!=="clearTimeTravel"&&x!=="replayFrom"&&typeof e[x]=="function"));return Object.assign({context:M},y)},replayFrom:M=>{var C;if(M<0||M>=i.length)throw new Error(`Invalid replay start index: ${M}`);let y=(C=a[M])==null?void 0:C.before;if(!y)throw new Error(`No snapshot available for index ${M}`);let x=i.slice(M),f=Object.assign({context:y},Object.fromEntries(Object.entries(e).filter(([T])=>T!=="context"&&typeof e[T]=="function")));for(let T of x){let ie=f[T.transitionName];ie&&(f=ie.apply(f.context,T.args))}return f}})}function it(e,...t){return t.reduce((n,r)=>r(n),e)}function v(e,...t){return t.reduce((n,r)=>r(n),e)}var Z=class e{constructor(t){this.machine=t}with(t){let n=t(this.machine);return new e(n)}build(){return this.machine}};function at(e){return new Z(e)}function B(e,t){let n=function(r){return t(r)?e(r):r};return n.middleware=e,n.when=t,n}function st(e){return B(e,()=>typeof process!="undefined"?!1:typeof window!="undefined"?!window.location.hostname.includes("production"):!1)}function ct(e,t,n){return B(n,r=>r.context[e]===t)}function dt(){let e=new Map;return{register(t,n,r,o){if(e.has(t))throw new Error(`Middleware '${t}' is already registered`);return e.set(t,{name:t,middleware:n,description:r,priority:o}),this},unregister(t){return e.delete(t)},has(t){return e.has(t)},get(t){return e.get(t)},list(){return Array.from(e.values()).sort((t,n)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=n.priority)!=null?o:0)})},apply(t,n){let r=n.map(o=>{let i=e.get(o);if(!i)throw new Error(`Middleware '${o}' is not registered`);return i}).sort((o,i)=>{var a,s;return((a=o.priority)!=null?a:0)-((s=i.priority)!=null?s:0)});return v(t,...r.map(o=>o.middleware))},applyAll(t){let n=this.list();return v(t,...n.map(r=>r.middleware))}}}function ut(e={}){let{continueOnError:t=!1,logErrors:n=!0,onError:r}=e;return(o,...i)=>{let a=o,s=[],u=!0;for(let c=0;c<i.length;c++){let d=i[c];try{if("middleware"in d&&"when"in d){if(!d.when(a))continue;a=d.middleware(a)}else a=d(a)}catch(l){if(u=!1,!t)throw l;s.push({error:l,middlewareIndex:c,middlewareName:d.name}),n&&console.error(`Pipeline middleware error at index ${c}:`,l),r==null||r(l,c,d.name)}}return{machine:a,errors:s,success:u}}}function yt(...e){return t=>v(t,...e)}function lt(e,t){return n=>{for(let[r,o]of e)if(r(n))return o(n);return t?t(n):n}}function ee(e){return typeof e=="function"&&e.length===1}function Mt(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"middleware"in e&&"when"in e&&ee(e.middleware)&&typeof e.when=="function"}function xt(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"prevContext"in e&&"nextContext"in e&&"args"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&(!t||O(e.prevContext,t)&&O(e.nextContext,t))}function ht(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"context"in e&&"args"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&(!t||O(e.context,t))}function ft(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"context"in e&&"args"in e&&"error"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&e.error instanceof Error&&(!t||O(e.context,t))}function pt(e,t){if(e===null||typeof e!="object")return!1;let n=e;return!("before"in n&&n.before!==void 0&&typeof n.before!="function"||"after"in n&&n.after!==void 0&&typeof n.after!="function"||"error"in n&&n.error!==void 0&&typeof n.error!="function")}function gt(e){return e===void 0||e!==null&&typeof e=="object"&&("continueOnError"in e?typeof e.continueOnError=="boolean":!0)&&("logErrors"in e?typeof e.logErrors=="boolean":!0)&&("onError"in e?typeof e.onError=="function"||e.onError===void 0:!0)}function O(e,t){return e!==null&&typeof e=="object"}function Ct(e){return e!==null&&typeof e=="object"&&"name"in e&&"middleware"in e&&typeof e.name=="string"&&ee(e.middleware)&&("description"in e?typeof e.description=="string"||e.description===void 0:!0)&&("priority"in e?typeof e.priority=="number"||e.priority===void 0:!0)}function mt(e){return e===void 0||e!==null&&typeof e=="object"&&("continueOnError"in e?typeof e.continueOnError=="boolean":!0)&&("logErrors"in e?typeof e.logErrors=="boolean":!0)&&("onError"in e?typeof e.onError=="function"||e.onError===void 0:!0)}var P=class{constructor(t){this.machine=t;this.middlewares=[]}withLogging(t){return this.middlewares.push(n=>V(n,t)),this}withAnalytics(t,n){return this.middlewares.push(r=>U(r,t,n)),this}withValidation(t,n){return this.middlewares.push(r=>q(r,t)),this}withPermissions(t){return this.middlewares.push(n=>Y(n,t)),this}withErrorReporting(t,n){return this.middlewares.push(r=>J(r,t,n)),this}withPerformanceMonitoring(t,n){return this.middlewares.push(r=>Q(r,t)),this}withRetry(t){return this.middlewares.push(n=>X(n,t)),this}withHistory(t){return this.middlewares.push(n=>S(n,t)),this}withSnapshot(t){return this.middlewares.push(n=>R(n,t)),this}withTimeTravel(t){return this.middlewares.push(n=>j(n,t)),this}withDebugging(){return this.middlewares.push(t=>Ae(t)),this}withCustom(t){return this.middlewares.push(t),this}withConditional(t,n){return this.middlewares.push(B(t,n)),this}build(){let t=this.machine;for(let n of this.middlewares)t=n(t);return t}getChain(){return[...this.middlewares]}clear(){return this.middlewares=[],this}};function Fe(e){return new P(e)}function Tt(e={}){return{create:t=>{let n=Fe(t);return e.logging&&n.withLogging(e.logging),e.analytics&&n.withAnalytics(e.analytics.track,e.analytics.options),e.history&&n.withHistory(e.history),e.snapshot&&n.withSnapshot(e.snapshot),e.timeTravel&&n.withTimeTravel(e.timeTravel),e.retry&&n.withRetry(e.retry),n}}}function Ae(e){return j(R(S(e)))}function Se(e,t){return e instanceof t}function Re(e,...t){return{type:e,args:t}}function je(e,t){return E(e,n=>({...n,...t}))}async function ve(e,...t){let n=e;for(let r of t)n=await r(n);return n}function Oe(e,t){return t?console.log(t,e.context):console.log(e.context),e}function Pe(e,t){return function(...n){let r=t(this.context,...n);return p(r,e())}}function Be(e,t,...n){return e.apply(t,n)}function te(e){return new Proxy(e,{get(t,n){let r=t[n];return typeof r=="function"?function(...o){let i=r.apply(t.context,o);return i&&typeof i=="object"&&"context"in i?te(i):i}:r}})}var k=class e{constructor(t){return this.wrappedMachine=t,new Proxy(this,{get:(n,r)=>{if(r==="wrappedMachine")return Reflect.get(n,r);if(r==="context")return this.wrappedMachine.context;let o=this.wrappedMachine[r];return typeof o=="function"?(...i)=>{let a=o.apply(this.wrappedMachine.context,i);return a&&typeof a=="object"&&"context"in a?new e(a):a}:o}})}};function ke(){return function(t){return function(...n){let r=t(this.context,...n);return p(r,this)}}}function ne(e){return{machine:e,addTransition:function(t,n){let r=function(...i){let a=n(this.context,...i);return p(a,this)},o=K(e,{[t]:r});return ne(o)}}}function re(e){return function(n){let r={},o=Object.fromEntries(Object.entries(n).map(([i,a])=>[i,function(...s){let u=a(this.context,...s);return p(u,r)}]));return Object.assign(r,o),p(e,r)}}function Ke(e,t){return t!==void 0?p(e,t):re(e)}function p(e,t){if(typeof t=="function"){let o;o=t(s=>{let u=p(s,o),c=Object.fromEntries(Object.entries(o).map(([d,l])=>[d,l.bind(s)]));return Object.assign(u,c)});let a=Object.fromEntries(Object.entries(o).map(([s,u])=>[s,u.bind(e)]));return Object.assign({context:e},a)}let n="context"in t?Object.fromEntries(Object.entries(t).filter(([o])=>o!=="context")):t;return Object.assign({context:e},n)}function oe(e,t){if(typeof t=="function"){let o;o=t(s=>{let u=oe(s,o),c=Object.fromEntries(Object.entries(o).map(([d,l])=>[d,l.bind(s)]));return Object.assign(u,c)});let a=Object.fromEntries(Object.entries(o).map(([s,u])=>[s,u.bind(e)]));return Object.assign({context:e},a)}let n="context"in t?Object.fromEntries(Object.entries(t).filter(([o])=>o!=="context")):t;return Object.assign({context:e},n)}function Ne(){return e=>{let t=Object.fromEntries(Object.entries(e).map(([n,r])=>[n,function(...o){let i=r(this.context,...o);return p(i,t)}]));return n=>p(n,t)}}function E(e,t){let{context:n,...r}=e,o=typeof t=="function"?t(n):t;return p(o,r)}function ze(e,t){let{context:n,...r}=e,o={...r,...t};return p(n,o)}function K(e,t){let{context:n,...r}=e,o={...r,...t};return p(n,o)}function Ge(e,t){return(...n)=>{let r=e(...n),o=t(),i={...r.context,...o.context},{context:a,...s}=r,{context:u,...c}=o,d={...s,...c};return p(i,d)}}function _e(e){let{context:t,...n}=e;return r=>p(r,n)}function We(e,t,n){let r=e.context[t],o=n[r];if(!o)throw new Error(`No handler found for state: ${String(r)}`);return o(e.context)}function He(e,t,n){return e.context[t]===n}function $e(e,t){let n=e,r=null;async function o(i){r&&(r.abort(),r=null);let a=n[i.type];if(typeof a!="function")throw new Error(`[Machine] Unknown event type '${String(i.type)}' on current state.`);let s=new AbortController;r=s;try{let c=await a.apply(n.context,[...i.args,{signal:s.signal}]);return s.signal.aborted||(n=c,t==null||t(n)),n}finally{r===s&&(r=null)}}return{get state(){return n.context},dispatch:o,stop:()=>{r&&(r.abort(),r=null)}}}var m=class{constructor(t){this.context=t}};function De(e,t){let{context:n,...r}=e;return p(t(n),r)}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var $=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ie=Object.prototype.hasOwnProperty;var Ve=(e,t)=>{for(var n in t)$(e,n,{get:t[n],enumerable:!0})},Ue=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of He(t))!Ie.call(e,i)&&i!==n&&$(e,i,{get:()=>t[i],enumerable:!(r=Ge(t,i))||r.enumerable});return e};var qe=e=>Ue($({},"__esModule",{value:!0}),e);var Nt={};Ve(Nt,{ADVANCED_CONFIG_EXAMPLES:()=>st,BoundMachine:()=>z,CANCEL:()=>J,META_KEY:()=>ge,MachineBase:()=>T,MiddlewareBuilder:()=>B,MultiMachineBase:()=>_,action:()=>we,bindTransitions:()=>oe,branch:()=>ht,call:()=>De,chain:()=>dt,combine:()=>ft,combineFactories:()=>jt,compose:()=>lt,composeTyped:()=>v,createAsyncMachine:()=>Le,createCustomMiddleware:()=>ct,createEnsemble:()=>je,createEnsembleFactory:()=>Je,createEvent:()=>Ne,createFetchMachine:()=>nt,createFlow:()=>Me,createFunctionalMachine:()=>se,createMachine:()=>g,createMachineBuilder:()=>Rt,createMachineFactory:()=>At,createMiddleware:()=>C,createMiddlewareFactory:()=>St,createMiddlewareRegistry:()=>Mt,createMultiMachine:()=>Qe,createMutableMachine:()=>Ze,createParallelMachine:()=>V,createPipeline:()=>xt,createRunner:()=>Fe,createTransition:()=>$e,createTransitionExtender:()=>ae,createTransitionFactory:()=>_e,delegateToChild:()=>et,describe:()=>me,extendTransitions:()=>ce,extractMachine:()=>q,extractMachines:()=>at,generateChart:()=>Oe,guard:()=>j,guardAsync:()=>R,guarded:()=>Te,hasState:()=>Pt,inDevelopment:()=>ut,invoke:()=>be,isConditionalMiddleware:()=>pt,isMiddlewareContext:()=>Ct,isMiddlewareError:()=>mt,isMiddlewareFn:()=>ie,isMiddlewareHooks:()=>Tt,isMiddlewareOptions:()=>bt,isMiddlewareResult:()=>gt,isNamedMiddleware:()=>wt,isPipelineConfig:()=>Et,isState:()=>ve,logState:()=>ze,matchMachine:()=>Ot,mergeContext:()=>Be,metadata:()=>Ae,middlewareBuilder:()=>Pe,next:()=>vt,overrideTransitions:()=>Ft,pipeTransitions:()=>Ke,run:()=>D,runAsync:()=>fe,runMachine:()=>kt,runSequence:()=>ye,runWithDebug:()=>xe,runWithEnsemble:()=>Xe,runWithRunner:()=>Ye,setContext:()=>S,state:()=>We,step:()=>de,stepAsync:()=>he,toggle:()=>tt,transitionTo:()=>Ce,when:()=>K,whenContext:()=>yt,whenGuard:()=>Ee,whenGuardAsync:()=>Se,withAnalytics:()=>X,withDebugging:()=>ke,withErrorReporting:()=>ee,withHistory:()=>O,withLogging:()=>Y,withPerformanceMonitoring:()=>te,withPermissions:()=>Z,withRetry:()=>ne,withSnapshot:()=>P,withTimeTravel:()=>k,withValidation:()=>Q,yieldMachine:()=>ue});module.exports=qe(Nt);function D(e,t){let n=e(t),r=t;for(;;){let{value:i,done:o}=n.next(r);if(o)return i;r=i}}function de(e){return function*(){return yield e}()}function ue(e){return e}function ye(e,t){return t.reduce((n,r)=>D(r,n),e)}function Me(e){return e}function xe(e,t,n=(r,i)=>{console.log(`Step ${r}:`,i.context)}){let r=e(t),i=t,o=0;for(n(o,i);;){let{value:a,done:s}=r.next(i);if(s)return console.log("Final:",a),a;i=a,o++,n(o,i)}}async function fe(e,t){let n=e(t),r=t;for(;;){let{value:i,done:o}=await n.next(r);if(o)return i;r=i}}async function*he(e){return yield e}var ge=Symbol("MachineMeta"),pe=Symbol("__machine_runtime_meta__");function w(e,t){let n=e[pe]||{},r={...n,...t};t.guards&&n.guards?r.guards=[...t.guards,...n.guards]:t.guards&&(r.guards=[...t.guards]),t.actions&&n.actions?r.actions=[...t.actions,...n.actions]:t.actions&&(r.actions=[...t.actions]),Object.defineProperty(e,pe,{value:r,enumerable:!1,writable:!1,configurable:!0})}function Ce(e,t){return w(t,{target:e.name||e.toString()}),t}function me(e,t){return w(t,{description:e}),t}function Te(e,t){return w(t,{guards:[e]}),t}function be(e,t){return w(t,{invoke:{src:e.src,onDone:e.onDone.name||e.onDone.toString(),onError:e.onError.name||e.onError.toString(),description:e.description}}),t}function we(e,t){return w(t,{actions:[e]}),t}function j(e,t,n={}){let{onFail:r="throw",errorMessage:i,description:o}=n,a={...n,onFail:r,errorMessage:i,description:o},s=function(...l){let c=typeof this=="object"&&"context"in this,d=c?this.context:this;if(e(d,...l)){let M=c?this.context:this;return t.apply(M,l)}else if(r==="throw"){let M=i||"Guard condition failed";throw new Error(M)}else if(r==="ignore"){if(c)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(c)return r.apply(this,l);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),w(s,{description:o||"Synchronous guarded transition",guards:[{name:"runtime_guard",description:o||"Synchronous condition check"}]}),s}function R(e,t,n={}){let{onFail:r="throw",errorMessage:i,description:o}=n,a={...n,onFail:r,errorMessage:i,description:o},s=async function(...l){let c=typeof this=="object"&&"context"in this,d=c?this.context:this;if(await Promise.resolve(e(d,...l))){let M=c?this.context:this;return t.apply(M,l)}else if(r==="throw"){let M=i||"Guard condition failed";throw new Error(M)}else if(r==="ignore"){if(c)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(c)return r.apply(this,l);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),w(s,{description:o||"Runtime guarded transition",guards:[{name:"runtime_guard",description:o||"Runtime condition check"}]}),s}function Ee(e){return{do(t){let n=j(e,t);return n.else=function(r){return j(e,t,{onFail:r})},n}}}function Se(e){return{do(t){let n=R(e,t);return n.else=function(r){return R(e,t,{onFail:r})},n}}}function Ae(e,t){return t}function Fe(e,t){let n=e,r=s=>{n=s,t==null||t(s)},{context:i,...o}=e,a=new Proxy({},{get(s,l){let c=n[l];if(typeof c=="function")return(...d)=>{let u=c.apply(n.context,d),M=Object.assign({context:u.context},o);return r(M),M}}});return{get state(){return n},get context(){return n.context},actions:a,setState:r}}function je(e,t,n){let r=()=>{let o=e.getContext(),a=n(o),s=t[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(o)},i=new Proxy({},{get(o,a){let s=r(),l=s[a];if(typeof l!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...c)=>l.apply(s.context,c)}});return{get context(){return e.getContext()},get state(){return r()},actions:i}}function Je(e,t){return function(r){return je(e,r,t)}}function Ye(e,t){let n=Fe(t),r=e(n),i=r.next();for(;!i.done;)i=r.next();return i.value}function Xe(e,t){let n=e(t),r=n.next();for(;!r.done;)r=n.next();return r.value}var _=class{constructor(t){this.store=t}get context(){return this.store.getContext()}setContext(t){this.store.setContext(t)}};function Qe(e,t){let n=new e(t);return new Proxy({},{get(r,i){let o=t.getContext();if(i in o)return o[i];let a=n[i];if(typeof a=="function")return(...s)=>a.apply(n,s)},set(r,i,o){let a=t.getContext();if(i in a){let s={...a,[i]:o};return t.setContext(s),!0}return!1},has(r,i){let o=t.getContext();return i in o||typeof n[i]=="function"},ownKeys(r){let i=t.getContext(),o=Object.keys(i),a=Object.getOwnPropertyNames(Object.getPrototypeOf(n)).filter(s=>s!=="constructor"&&typeof n[s]=="function");return Array.from(new Set([...o,...a]))},getOwnPropertyDescriptor(r,i){let o=t.getContext();if(i in o||typeof n[i]=="function")return{value:void 0,writable:!0,enumerable:!0,configurable:!0}}})}function Ze(e,t,n){let r=()=>{let i=n(e),o=t[i];if(!o)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(i)}".`);return o(e)};return new Proxy(e,{get(i,o,a){if(o in i)return i[o];let s=r(),l=s[o];if(typeof l=="function")return(...c)=>{let d=l.apply(s.context,c);if(typeof d!="object"||d===null){console.warn(`[MutableMachine] Transition "${String(o)}" did not return a valid context object. State may be inconsistent.`);return}Object.keys(i).forEach(u=>delete i[u]),Object.assign(i,d)}},set(i,o,a,s){return i[o]=a,!0},has(i,o){let a=r();return o in i||typeof a[o]=="function"}})}function et(e){return function(...t){let n=this.context.child;if(typeof n[e]=="function"){let r=n[e](...t);return S(this,{...this.context,child:r})}return this}}function tt(e){return function(){return typeof this.context[e]!="boolean"&&console.warn(`[toggle primitive] Property '${String(e)}' is not a boolean. Toggling may have unexpected results.`),S(this,{...this.context,[e]:!this.context[e]})}}var W=class extends T{constructor(n){super({status:"idle"});this.config=n;this.fetch=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}},E=class extends T{constructor(n,r,i){super({status:"loading",abortController:new AbortController,attempts:i});this.config=n;this.params=r;this.succeed=n=>{var r,i;return(i=(r=this.config).onSuccess)==null||i.call(r,n),new G(this.config,{status:"success",data:n})};this.fail=n=>{var i,o,a;let r=(i=this.config.maxRetries)!=null?i:3;return this.context.attempts<r?new L(this.config,this.params,n,this.context.attempts):((a=(o=this.config).onError)==null||a.call(o,n),new H(this.config,{status:"error",error:n}))};this.cancel=()=>(this.context.abortController.abort(),new I(this.config));this.execute()}async execute(){}},L=class extends T{constructor(n,r,i,o){super({status:"retrying",error:i,attempts:o});this.config=n;this.params=r;this.retry=n=>new E(this.config,n!=null?n:this.params,this.context.attempts+1)}},G=class extends T{constructor(n,r){super(r);this.config=n;this.refetch=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}},H=class extends T{constructor(n,r){super(r);this.config=n;this.retry=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}},I=class extends T{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}};function nt(e){return new W(e)}function V(e,t){let n={...e.context,...t.context},r={...e},i={...t};delete r.context,delete i.context;let o={};for(let a in r){let s=r[a];o[a]=(...l)=>{let c=s.apply(e.context,l);return V(c,t)}}for(let a in i){let s=i[a];o[a]=(...l)=>{let c=s.apply(t.context,l);return V(e,c)}}return{context:n,...o}}var p=require("ts-morph");function Re(e){return p.Node.isIdentifier(e)?e.getText():p.Node.isTypeOfExpression(e)?e.getExpression().getText():"unknown"}function F(e){if(!p.Node.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(p.Node.isPropertyAssignment(n)){let r=n.getName(),i=n.getInitializer();i&&(p.Node.isStringLiteral(i)||p.Node.isNumericLiteral(i)?t[r]=i.getLiteralValue():i.getText()==="true"||i.getText()==="false"?t[r]=i.getText()==="true":p.Node.isIdentifier(i)?t[r]=i.getText():p.Node.isObjectLiteralExpression(i)?t[r]=F(i):p.Node.isArrayLiteralExpression(i)&&(t[r]=i.getElements().map(o=>p.Node.isObjectLiteralExpression(o)?F(o):o.getText())))}return t}function rt(e){if(!p.Node.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(p.Node.isPropertyAssignment(n)){let r=n.getName(),i=n.getInitializer();if(!i)continue;r==="onDone"||r==="onError"?t[r]=Re(i):p.Node.isStringLiteral(i)?t[r]=i.getLiteralValue():p.Node.isIdentifier(i)&&(t[r]=i.getText())}return t}function A(e,t=!1){if(!p.Node.isCallExpression(e))return null;let n=e.getExpression(),r=p.Node.isIdentifier(n)?n.getText():null;if(!r)return null;let i={},o=e.getArguments();switch(r){case"transitionTo":o[0]&&(i.target=Re(o[0]));break;case"describe":if(o[0]&&p.Node.isStringLiteral(o[0])&&(i.description=o[0].getLiteralValue()),o[1]&&p.Node.isCallExpression(o[1])){let a=A(o[1],t);a&&Object.assign(i,a)}break;case"guarded":if(o[0]){let a=F(o[0]);Object.keys(a).length>0&&(i.guards=[a])}if(o[1]&&p.Node.isCallExpression(o[1])){let a=A(o[1],t);a&&Object.assign(i,a)}break;case"invoke":if(o[0]){let a=rt(o[0]);Object.keys(a).length>0&&(i.invoke=a)}break;case"action":if(o[0]){let a=F(o[0]);Object.keys(a).length>0&&(i.actions=[a])}if(o[1]&&p.Node.isCallExpression(o[1])){let a=A(o[1],t);a&&Object.assign(i,a)}break;case"guard":if(o[2]){let a=F(o[2]);a.description&&(i.description=a.description)}if(i.guards=[{name:"runtime_guard",description:i.description||"Synchronous condition check"}],o[1]&&p.Node.isCallExpression(o[1])){let a=A(o[1],t);a&&Object.assign(i,a)}break;case"guardAsync":if(o[2]){let a=F(o[2]);a.description&&(i.description=a.description)}if(i.guards=[{name:"runtime_guard_async",description:i.description||"Asynchronous condition check"}],o[1]&&p.Node.isCallExpression(o[1])){let a=A(o[1],t);a&&Object.assign(i,a)}break;default:return null}return Object.keys(i).length>0?i:null}function it(e,t=!1){if(!p.Node.isPropertyDeclaration(e))return t&&console.error(" ⚠️ Not a property declaration"),null;let n=e.getInitializer();if(!n)return t&&console.error(" ⚠️ No initializer"),null;if(!p.Node.isCallExpression(n))return t&&console.error(" ⚠️ Initializer is not a call expression"),null;let r=A(n,t);return r&&t&&console.error(" ✅ Extracted metadata:",JSON.stringify(r,null,2)),r}function U(e,t=!1){let n={on:{}},r=e.getDeclarations()[0];if(!r||!p.Node.isClassDeclaration(r))return t&&console.error(`⚠️ Warning: Could not get class declaration for ${e.getName()}`),n;let i=e.getName();t&&console.error(` Analyzing state: ${i}`);for(let o of r.getInstanceMembers()){let a=o.getName();t&&console.error(` Checking member: ${a}`);let s=it(o,t);if(!s)continue;t&&console.error(` Found transition: ${a}`);let{invoke:l,actions:c,guards:d,...u}=s;if(l&&(n.invoke||(n.invoke=[]),n.invoke.push({src:l.src,onDone:{target:l.onDone},onError:{target:l.onError},description:l.description}),t&&console.error(` → Invoke: ${l.src}`)),u.target){let M={target:u.target};u.description&&(M.description=u.description),d&&(M.cond=d.map(y=>y.name).join(" && "),t&&console.error(` → Guard: ${M.cond}`)),c&&c.length>0&&(M.actions=c.map(y=>y.name),t&&console.error(` → Actions: ${M.actions.join(", ")}`)),n.on[a]=M,t&&console.error(` → Target: ${u.target}`)}}return n}function ot(e,t,n,r,i=!1){let o=U(t,i);if(r){i&&console.error(` 👪 Analyzing children for state: ${e}`),o.initial=r.initialState,o.states={};for(let a of r.classes){let s=n.getClass(a);if(s){let l=s.getSymbolOrThrow();o.states[a]=U(l,i)}else console.warn(`⚠️ Warning: Child class '${a}' not found.`)}}return o}function q(e,t,n=!1){n&&(console.error(`
|
|
2
|
-
🔍 Analyzing machine: ${e.id}`),console.error(` Source: ${e.input}`));let r=t.getSourceFile(e.input);if(!r)throw new Error(`Source file not found: ${e.input}`);if(e.parallel){n&&console.error(" ⏹️ Parallel machine detected. Analyzing regions.");let o={id:e.id,type:"parallel",states:{}};e.description&&(o.description=e.description);for(let a of e.parallel.regions){n&&console.error(` 📍 Analyzing region: ${a.name}`);let s={};for(let
|
|
3
|
-
📊 Starting statechart extraction`),console.error(` Machines to extract: ${e.machines.length}`));let n=new p.Project;n.addSourceFilesAtPaths("src/**/*.ts"),n.addSourceFilesAtPaths("examples/**/*.ts");let r=[];for(let o of e.machines)try{let a=
|
|
4
|
-
✅ Extraction complete: ${r.length}/${e.machines.length} machines extracted`),r}function
|
|
5
|
-
`);let t=new p.Project;t.addSourceFilesAtPaths("src/**/*.ts"),t.addSourceFilesAtPaths("examples/**/*.ts");try{let n=q(e,t,!0);console.log(JSON.stringify(n,null,2))}catch(n){console.error("❌ Error:",n),process.exit(1)}}var st={hierarchical:{input:"examples/dashboardMachine.ts",id:"dashboard",classes:["DashboardMachine","LoggedOutMachine"],initialState:"DashboardMachine",children:{contextProperty:"child",initialState:"ViewingChildMachine",classes:["ViewingChildMachine","EditingChildMachine"]}},parallel:{input:"examples/editorMachine.ts",id:"editor",parallel:{regions:[{name:"fontWeight",initialState:"NormalWeight",classes:["NormalWeight","BoldWeight"]},{name:"textDecoration",initialState:"NoDecoration",classes:["NoDecoration","UnderlineState"]}]}}};require.main===module&&Oe();var J=Symbol("CANCEL");function C(e,t,n={}){let{continueOnError:r=!1,logErrors:i=!0,onError:o}=n,a={...e};for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&s!=="context"&&typeof e[s]!="function"&&(a[s]=e[s]);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let l=e[s];typeof l=="function"&&s!=="context"&&(a[s]=function(...c){let d=s,u=a.context,M=()=>{let y;try{y=l.apply(this,c)}catch(f){if(t.error)try{t.error({transitionName:d,context:u,args:[...c],error:f})}catch(h){if(!r)throw h;i&&console.error(`Middleware error hook error for ${d}:`,h),o==null||o(h,"error",{transitionName:d,context:u,args:c,error:f})}throw f}let x=f=>{if(f&&typeof f=="object"&&f.context){for(let h in a)Object.prototype.hasOwnProperty.call(a,h)&&h!=="context"&&!(h in f)&&(f[h]=a[h]);for(let h in f){if(!Object.prototype.hasOwnProperty.call(f,h))continue;typeof f[h]=="function"&&h!=="context"&&a[h]&&(f[h]=a[h])}}return f};if(y&&typeof y.then=="function")return y.then(h=>{if(x(h),t.after)try{let m=t.after({transitionName:d,prevContext:u,nextContext:h.context,args:[...c]});if(m&&typeof m.then=="function")return m.then(()=>h)}catch(m){if(!r)throw m;i&&console.error(`Middleware after hook error for ${d}:`,m),o==null||o(m,"after",{transitionName:d,prevContext:u,nextContext:h.context,args:c})}return h});if(x(y),t.after)try{let f=t.after({transitionName:d,prevContext:u,nextContext:y.context,args:[...c]});if(f&&typeof f=="object"&&f&&"then"in f)return f.then(()=>y).catch(h=>{if(!r)throw h;return i&&console.error(`Middleware after hook error for ${d}:`,h),o==null||o(h,"after",{transitionName:d,prevContext:u,nextContext:y.context,args:c}),y})}catch(f){if(!r)throw f;i&&console.error(`Middleware after hook error for ${d}:`,f),o==null||o(f,"after",{transitionName:d,prevContext:u,nextContext:y.context,args:c})}return y};if(t.before)try{let y=t.before({transitionName:d,context:u,args:[...c]});if(y&&typeof y=="object"&&y&&"then"in y)return y.then(x=>x===J?a:M()).catch(x=>{if(!r)throw x;return i&&console.error(`Middleware before hook error for ${d}:`,x),o==null||o(x,"before",{transitionName:d,context:u,args:c}),M()});if(y===J)return a}catch(y){if(!r)throw y;i&&console.error(`Middleware before hook error for ${d}:`,y),o==null||o(y,"before",{transitionName:d,context:u,args:c})}return M()})}return a}function Y(e,t={}){let{logger:n=console.log,includeArgs:r=!1,includeContext:i=!0}=t;return C(e,{before:({transitionName:o,args:a})=>{let s=r?`→ ${o} [${a.join(", ")}]`:`→ ${o}`;n(s)},after:({transitionName:o,nextContext:a})=>{let s=i?` ${JSON.stringify(a)}`:"";n(`✓ ${o}${s}`)},error:({transitionName:o,error:a})=>{console.error(`[Machine] ${o} failed:`,a)}})}function X(e,t,n={}){let{eventPrefix:r="state_transition",includePrevContext:i=!1,includeArgs:o=!1}=n;return C(e,{after:({transitionName:a,prevContext:s,nextContext:l,args:c})=>{let d=`${r}.${a}`,u={transition:a};i&&(u.from=s),u.to=l,o&&(u.args=c),t(d,u)}})}function Q(e,t){return C(e,{before:n=>{if(t(n)===!1)throw new Error(`Validation failed for transition: ${n.transitionName}`)}})}function Z(e,t){return C(e,{before:n=>{if(!t(n))throw new Error(`Unauthorized transition: ${n.transitionName}`)}})}function ee(e,t,n={}){let{includeArgs:r=!1}=n;return C(e,{error:i=>{let o={transition:i.transitionName,context:i.context,...r&&{args:i.args}};t(i.error,o)}})}function te(e,t){let n=new Map;return C(e,{before:r=>{n.set(r.transitionName,Date.now())},after:r=>{let i=n.get(r.transitionName);if(i){let o=Date.now()-i;n.delete(r.transitionName);let a={transitionName:r.transitionName,duration:o,context:r.nextContext||r.prevContext};t(a)}}})}function ne(e,t={}){var l,c;let{maxAttempts:n=(l=t.maxRetries)!=null?l:3,shouldRetry:r=()=>!0,backoffMs:i=(c=t.delay)!=null?c:100,backoffMultiplier:o=2,onRetry:a}=t,s={...e};for(let d in e){if(!Object.prototype.hasOwnProperty.call(e,d))continue;let u=e[d];typeof u=="function"&&d!=="context"&&(s[d]=async function(...M){let y,x=0;for(;x<n;)try{return await u.apply(this,M)}catch(f){if(y=f,x++,x<n&&r(y,x)){a==null||a(y,x);let m=(typeof i=="function"?i(x):i)*Math.pow(o,x-1);await new Promise(b=>setTimeout(b,m))}else throw y}throw y})}return s}function ct(e,t){return n=>C(n,e,t)}function O(e,t={}){let{maxSize:n,serializer:r,onEntry:i}=t,o=[],a=0,s=C(e,{before:({transitionName:l,args:c})=>{let d={id:`entry-${a++}`,transitionName:l,args:[...c],timestamp:Date.now()};if(r)try{d.serializedArgs=r.serialize(c)}catch(u){console.error("Failed to serialize history args:",u)}o.push(d),n&&o.length>n&&o.shift(),i==null||i(d)}});return Object.assign(s,{history:o,clearHistory:()=>{o.length=0,a=0}})}function P(e,t={}){let{maxSize:n,serializer:r,captureSnapshot:i,onlyOnChange:o=!1}=t,a=[],s=0,l=C(e,{after:({transitionName:d,prevContext:u,nextContext:M})=>{if(o&&JSON.stringify(u)===JSON.stringify(M))return;let y={id:`snapshot-${s++}`,transitionName:d,before:{...u},after:{...M},timestamp:Date.now()};if(r)try{y.serializedBefore=r.serialize(u),y.serializedAfter=r.serialize(M)}catch(x){console.error("Failed to serialize snapshot:",x)}if(i)try{y.diff=i(u,M)}catch(x){console.error("Failed to capture snapshot:",x)}a.push(y),n&&a.length>n&&a.shift()}});return Object.assign(l,{snapshots:a,clearSnapshots:()=>{a.length=0,s=0},restoreSnapshot:d=>{let u=Object.fromEntries(Object.entries(e).filter(([M])=>M!=="context"&&M!=="snapshots"&&M!=="clearSnapshots"&&M!=="restoreSnapshot"&&typeof e[M]=="function"));return Object.assign({context:d},u)}})}function k(e,t={}){let{maxSize:n,serializer:r,onRecord:i}=t,o=[],a=[],s=0,l=0,c=C(e,{before:({transitionName:M,args:y})=>{let x={id:`entry-${s++}`,transitionName:M,args:[...y],timestamp:Date.now()};if(r)try{x.serializedArgs=r.serialize(y)}catch(f){console.error("Failed to serialize history args:",f)}o.push(x),n&&o.length>n&&o.shift(),i==null||i("history",x)},after:({transitionName:M,prevContext:y,nextContext:x})=>{let f={id:`snapshot-${l++}`,transitionName:M,before:{...y},after:{...x},timestamp:Date.now()};if(r)try{f.serializedBefore=r.serialize(y),f.serializedAfter=r.serialize(x)}catch(h){console.error("Failed to serialize snapshot:",h)}a.push(f),n&&a.length>n&&a.shift(),i==null||i("snapshot",f)}});return Object.assign(c,{history:o,snapshots:a,clearHistory:()=>{o.length=0,s=0},clearSnapshots:()=>{a.length=0,l=0},clearTimeTravel:()=>{o.length=0,a.length=0,s=0,l=0},restoreSnapshot:M=>{let y=Object.fromEntries(Object.entries(e).filter(([x])=>x!=="context"&&x!=="history"&&x!=="snapshots"&&x!=="clearHistory"&&x!=="clearSnapshots"&&x!=="restoreSnapshot"&&x!=="clearTimeTravel"&&x!=="replayFrom"&&typeof e[x]=="function"));return Object.assign({context:M},y)},replayFrom:M=>{var m;if(M<0||M>=o.length)throw new Error(`Invalid replay start index: ${M}`);let y=(m=a[M])==null?void 0:m.before;if(!y)throw new Error(`No snapshot available for index ${M}`);let x=o.slice(M),h=Object.assign({context:y},Object.fromEntries(Object.entries(e).filter(([b])=>b!=="context"&&typeof e[b]=="function")));for(let b of x){let le=h[b.transitionName];le&&(h=le.apply(h.context,b.args))}return h}})}function lt(e,...t){return t.reduce((n,r)=>r(n),e)}function v(e,...t){return t.reduce((n,r)=>r(n),e)}var re=class e{constructor(t){this.machine=t}with(t){let n=t(this.machine);return new e(n)}build(){return this.machine}};function dt(e){return new re(e)}function K(e,t){let n=function(r){return t(r)?e(r):r};return n.middleware=e,n.when=t,n}function ut(e){return K(e,()=>typeof process!="undefined"?!1:typeof window!="undefined"?!window.location.hostname.includes("production"):!1)}function yt(e,t,n){return K(n,r=>r.context[e]===t)}function Mt(){let e=new Map;return{register(t,n,r,i){if(e.has(t))throw new Error(`Middleware '${t}' is already registered`);return e.set(t,{name:t,middleware:n,description:r,priority:i}),this},unregister(t){return e.delete(t)},has(t){return e.has(t)},get(t){return e.get(t)},list(){return Array.from(e.values()).sort((t,n)=>{var r,i;return((r=t.priority)!=null?r:0)-((i=n.priority)!=null?i:0)})},apply(t,n){let r=n.map(i=>{let o=e.get(i);if(!o)throw new Error(`Middleware '${i}' is not registered`);return o}).sort((i,o)=>{var a,s;return((a=i.priority)!=null?a:0)-((s=o.priority)!=null?s:0)});return v(t,...r.map(i=>i.middleware))},applyAll(t){let n=this.list();return v(t,...n.map(r=>r.middleware))}}}function xt(e={}){let{continueOnError:t=!1,logErrors:n=!0,onError:r}=e;return(i,...o)=>{let a=i,s=[],l=!0;for(let c=0;c<o.length;c++){let d=o[c];try{if("middleware"in d&&"when"in d){if(!d.when(a))continue;a=d.middleware(a)}else a=d(a)}catch(u){if(l=!1,!t)throw u;s.push({error:u,middlewareIndex:c,middlewareName:d.name}),n&&console.error(`Pipeline middleware error at index ${c}:`,u),r==null||r(u,c,d.name)}}return{machine:a,errors:s,success:l}}}function ft(...e){return t=>v(t,...e)}function ht(e,t){return n=>{for(let[r,i]of e)if(r(n))return i(n);return t?t(n):n}}function ie(e){return typeof e=="function"&&e.length===1}function pt(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"middleware"in e&&"when"in e&&ie(e.middleware)&&typeof e.when=="function"}function gt(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"prevContext"in e&&"nextContext"in e&&"args"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&(!t||N(e.prevContext,t)&&N(e.nextContext,t))}function Ct(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"context"in e&&"args"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&(!t||N(e.context,t))}function mt(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"context"in e&&"args"in e&&"error"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&e.error instanceof Error&&(!t||N(e.context,t))}function Tt(e,t){if(e===null||typeof e!="object")return!1;let n=e;return!("before"in n&&n.before!==void 0&&typeof n.before!="function"||"after"in n&&n.after!==void 0&&typeof n.after!="function"||"error"in n&&n.error!==void 0&&typeof n.error!="function")}function bt(e){return e===void 0||e!==null&&typeof e=="object"&&("continueOnError"in e?typeof e.continueOnError=="boolean":!0)&&("logErrors"in e?typeof e.logErrors=="boolean":!0)&&("onError"in e?typeof e.onError=="function"||e.onError===void 0:!0)}function N(e,t){return e!==null&&typeof e=="object"}function wt(e){return e!==null&&typeof e=="object"&&"name"in e&&"middleware"in e&&typeof e.name=="string"&&ie(e.middleware)&&("description"in e?typeof e.description=="string"||e.description===void 0:!0)&&("priority"in e?typeof e.priority=="number"||e.priority===void 0:!0)}function Et(e){return e===void 0||e!==null&&typeof e=="object"&&("continueOnError"in e?typeof e.continueOnError=="boolean":!0)&&("logErrors"in e?typeof e.logErrors=="boolean":!0)&&("onError"in e?typeof e.onError=="function"||e.onError===void 0:!0)}var B=class{constructor(t){this.machine=t;this.middlewares=[]}withLogging(t){return this.middlewares.push(n=>Y(n,t)),this}withAnalytics(t,n){return this.middlewares.push(r=>X(r,t,n)),this}withValidation(t,n){return this.middlewares.push(r=>Q(r,t)),this}withPermissions(t){return this.middlewares.push(n=>Z(n,t)),this}withErrorReporting(t,n){return this.middlewares.push(r=>ee(r,t,n)),this}withPerformanceMonitoring(t,n){return this.middlewares.push(r=>te(r,t)),this}withRetry(t){return this.middlewares.push(n=>ne(n,t)),this}withHistory(t){return this.middlewares.push(n=>O(n,t)),this}withSnapshot(t){return this.middlewares.push(n=>P(n,t)),this}withTimeTravel(t){return this.middlewares.push(n=>k(n,t)),this}withDebugging(){return this.middlewares.push(t=>ke(t)),this}withCustom(t){return this.middlewares.push(t),this}withConditional(t,n){return this.middlewares.push(K(t,n)),this}build(){let t=this.machine;for(let n of this.middlewares)t=n(t);return t}getChain(){return[...this.middlewares]}clear(){return this.middlewares=[],this}};function Pe(e){return new B(e)}function St(e={}){return{create:t=>{let n=Pe(t);return e.logging&&n.withLogging(e.logging),e.analytics&&n.withAnalytics(e.analytics.track,e.analytics.options),e.history&&n.withHistory(e.history),e.snapshot&&n.withSnapshot(e.snapshot),e.timeTravel&&n.withTimeTravel(e.timeTravel),e.retry&&n.withRetry(e.retry),n}}}function ke(e){return k(P(O(e)))}function ve(e,t){return e instanceof t}function Ne(e,...t){return{type:e,args:t}}function Be(e,t){return S(e,n=>({...n,...t}))}async function Ke(e,...t){let n=e;for(let r of t)n=await r(n);return n}function ze(e,t){return t?console.log(t,e.context):console.log(e.context),e}function $e(e,t){return function(...n){let r=t(this.context,...n);return g(r,e())}}function De(e,t,...n){return e.apply(t,n)}function oe(e){return new Proxy(e,{get(t,n){let r=t[n];return typeof r=="function"?function(...i){let o=r.apply(t.context,i);return o&&typeof o=="object"&&"context"in o?oe(o):o}:r}})}var z=class e{constructor(t){return this.wrappedMachine=t,new Proxy(this,{get:(n,r)=>{if(r==="wrappedMachine")return Reflect.get(n,r);if(r==="context")return this.wrappedMachine.context;let i=this.wrappedMachine[r];return typeof i=="function"?(...o)=>{let a=i.apply(this.wrappedMachine.context,o);return a&&typeof a=="object"&&"context"in a?new e(a):a}:i}})}};function _e(){return function(t){return function(...n){let r=t(this.context,...n);return g(r,this)}}}function ae(e){return{machine:e,addTransition:function(t,n){let r=function(...o){let a=n(this.context,...o);return g(a,this)},i=ce(e,{[t]:r});return ae(i)}}}function se(e){return function(n){let r={},i=Object.fromEntries(Object.entries(n).map(([o,a])=>[o,function(...s){let l=a(this.context,...s);return g(l,r)}]));return Object.assign(r,i),g(e,r)}}function We(e,t){return t!==void 0?g(e,t):se(e)}function g(e,t){if(typeof t=="function"){let i;i=t(s=>{let l=g(s,i),c=Object.fromEntries(Object.entries(i).map(([d,u])=>[d,u.bind(s)]));return Object.assign(l,c)});let a=Object.fromEntries(Object.entries(i).map(([s,l])=>[s,l.bind(e)]));return Object.assign({context:e},a)}let n="context"in t?Object.fromEntries(Object.entries(t).filter(([i])=>i!=="context")):t;return Object.assign({context:e},n)}function Le(e,t){if(typeof t=="function"){let i;i=t(s=>{let l=Le(s,i),c=Object.fromEntries(Object.entries(i).map(([d,u])=>[d,u.bind(s)]));return Object.assign(l,c)});let a=Object.fromEntries(Object.entries(i).map(([s,l])=>[s,l.bind(e)]));return Object.assign({context:e},a)}let n="context"in t?Object.fromEntries(Object.entries(t).filter(([i])=>i!=="context")):t;return Object.assign({context:e},n)}function At(){return e=>{let t=Object.fromEntries(Object.entries(e).map(([n,r])=>[n,function(...i){let o=r(this.context,...i);return g(o,t)}]));return n=>g(n,t)}}function S(e,t){let{context:n,...r}=e,i=typeof t=="function"?t(n):t;return g(i,r)}function Ft(e,t){let{context:n,...r}=e,i={...r,...t};return g(n,i)}function ce(e,t){let{context:n,...r}=e,i={...r,...t};return g(n,i)}function jt(e,t){return(...n)=>{let r=e(...n),i=t(),o={...r.context,...i.context},{context:a,...s}=r,{context:l,...c}=i,d={...s,...c};return g(o,d)}}function Rt(e){let{context:t,...n}=e;return r=>g(r,n)}function Ot(e,t,n){let r=e.context[t],i=n[r];if(!i)throw new Error(`No handler found for state: ${String(r)}`);return i(e.context)}function Pt(e,t,n){return e.context[t]===n}function kt(e,t){let n=e,r=null;async function i(o){r&&(r.abort(),r=null);let a=n[o.type];if(typeof a!="function")throw new Error(`[Machine] Unknown event type '${String(o.type)}' on current state.`);let s=new AbortController;r=s;try{let c=await a.apply(n.context,[...o.args,{signal:s.signal}]);return s.signal.aborted||(n=c,t==null||t(n)),n}finally{r===s&&(r=null)}}return{get state(){return n.context},dispatch:i,stop:()=>{r&&(r.abort(),r=null)}}}var T=class{constructor(t){this.context=t}};function vt(e,t){let{context:n,...r}=e;return g(t(n),r)}
|
|
1
|
+
"use strict";var $=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var Ue=(e,t)=>{for(var n in t)$(e,n,{get:t[n],enumerable:!0})},qe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ie(t))!Ve.call(e,i)&&i!==n&&$(e,i,{get:()=>t[i],enumerable:!(r=He(t,i))||r.enumerable});return e};var Je=e=>qe($({},"__esModule",{value:!0}),e);var Bt={};Ue(Bt,{ADVANCED_CONFIG_EXAMPLES:()=>ct,BoundMachine:()=>z,CANCEL:()=>Y,META_KEY:()=>Ce,MachineBase:()=>T,MiddlewareBuilder:()=>B,MultiMachineBase:()=>_,_typeToJson:()=>U,action:()=>Ee,bindTransitions:()=>ae,branch:()=>pt,call:()=>_e,chain:()=>ut,combine:()=>ht,combineFactories:()=>Rt,compose:()=>dt,composeTyped:()=>v,createAsyncMachine:()=>Ge,createCustomMiddleware:()=>lt,createEnsemble:()=>Re,createEnsembleFactory:()=>Ye,createEvent:()=>Be,createFetchMachine:()=>rt,createFlow:()=>xe,createFunctionalMachine:()=>ce,createMachine:()=>g,createMachineBuilder:()=>Ot,createMachineFactory:()=>Ft,createMiddleware:()=>C,createMiddlewareFactory:()=>At,createMiddlewareRegistry:()=>xt,createMultiMachine:()=>Ze,createMutableMachine:()=>et,createParallelMachine:()=>V,createPipeline:()=>ft,createRunner:()=>je,createTransition:()=>De,createTransitionExtender:()=>se,createTransitionFactory:()=>We,delegateToChild:()=>tt,describe:()=>Te,extendTransitions:()=>le,extractMachine:()=>J,extractMachines:()=>st,generateChart:()=>Pe,guard:()=>j,guardAsync:()=>R,guarded:()=>be,hasState:()=>kt,inDevelopment:()=>yt,invoke:()=>we,isConditionalMiddleware:()=>gt,isMiddlewareContext:()=>mt,isMiddlewareError:()=>Tt,isMiddlewareFn:()=>oe,isMiddlewareHooks:()=>bt,isMiddlewareOptions:()=>wt,isMiddlewareResult:()=>Ct,isNamedMiddleware:()=>Et,isPipelineConfig:()=>St,isState:()=>Ne,logState:()=>$e,matchMachine:()=>Pt,mergeContext:()=>Ke,metadata:()=>Fe,middlewareBuilder:()=>ke,next:()=>Nt,overrideTransitions:()=>jt,pipeTransitions:()=>ze,run:()=>D,runAsync:()=>he,runMachine:()=>vt,runSequence:()=>Me,runWithDebug:()=>fe,runWithEnsemble:()=>Qe,runWithRunner:()=>Xe,setContext:()=>S,state:()=>Le,step:()=>ue,stepAsync:()=>pe,toggle:()=>nt,transitionTo:()=>me,when:()=>K,whenContext:()=>Mt,whenGuard:()=>Se,whenGuardAsync:()=>Ae,withAnalytics:()=>Q,withDebugging:()=>ve,withErrorReporting:()=>te,withHistory:()=>O,withLogging:()=>X,withPerformanceMonitoring:()=>ne,withPermissions:()=>ee,withRetry:()=>re,withSnapshot:()=>P,withTimeTravel:()=>k,withValidation:()=>Z,yieldMachine:()=>ye});module.exports=Je(Bt);function D(e,t){let n=e(t),r=t;for(;;){let{value:i,done:o}=n.next(r);if(o)return i;r=i}}function ue(e){return function*(){return yield e}()}function ye(e){return e}function Me(e,t){return t.reduce((n,r)=>D(r,n),e)}function xe(e){return e}function fe(e,t,n=(r,i)=>{console.log(`Step ${r}:`,i.context)}){let r=e(t),i=t,o=0;for(n(o,i);;){let{value:a,done:s}=r.next(i);if(s)return console.log("Final:",a),a;i=a,o++,n(o,i)}}async function he(e,t){let n=e(t),r=t;for(;;){let{value:i,done:o}=await n.next(r);if(o)return i;r=i}}async function*pe(e){return yield e}var Ce=Symbol("MachineMeta"),ge=Symbol("__machine_runtime_meta__");function w(e,t){let n=e[ge]||{},r={...n,...t};t.guards&&n.guards?r.guards=[...t.guards,...n.guards]:t.guards&&(r.guards=[...t.guards]),t.actions&&n.actions?r.actions=[...t.actions,...n.actions]:t.actions&&(r.actions=[...t.actions]),Object.defineProperty(e,ge,{value:r,enumerable:!1,writable:!1,configurable:!0})}function me(e,t){return w(t,{target:e.name||e.toString()}),t}function Te(e,t){return w(t,{description:e}),t}function be(e,t){return w(t,{guards:[e]}),t}function we(e,t){return w(t,{invoke:{src:e.src,onDone:e.onDone.name||e.onDone.toString(),onError:e.onError.name||e.onError.toString(),description:e.description}}),t}function Ee(e,t){return w(t,{actions:[e]}),t}function j(e,t,n={}){let{onFail:r="throw",errorMessage:i,description:o}=n,a={...n,onFail:r,errorMessage:i,description:o},s=function(...c){let l=typeof this=="object"&&"context"in this,d=l?this.context:this;if(e(d,...c)){let M=l?this.context:this;return t.apply(M,c)}else if(r==="throw"){let M=i||"Guard condition failed";throw new Error(M)}else if(r==="ignore"){if(l)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(l)return r.apply(this,c);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),w(s,{description:o||"Synchronous guarded transition",guards:[{name:"runtime_guard",description:o||"Synchronous condition check"}]}),s}function R(e,t,n={}){let{onFail:r="throw",errorMessage:i,description:o}=n,a={...n,onFail:r,errorMessage:i,description:o},s=async function(...c){let l=typeof this=="object"&&"context"in this,d=l?this.context:this;if(await Promise.resolve(e(d,...c))){let M=l?this.context:this;return t.apply(M,c)}else if(r==="throw"){let M=i||"Guard condition failed";throw new Error(M)}else if(r==="ignore"){if(l)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(l)return r.apply(this,c);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),w(s,{description:o||"Runtime guarded transition",guards:[{name:"runtime_guard",description:o||"Runtime condition check"}]}),s}function Se(e){return{do(t){let n=j(e,t);return n.else=function(r){return j(e,t,{onFail:r})},n}}}function Ae(e){return{do(t){let n=R(e,t);return n.else=function(r){return R(e,t,{onFail:r})},n}}}function Fe(e,t){return t}function je(e,t){let n=e,r=s=>{n=s,t==null||t(s)},{context:i,...o}=e,a=new Proxy({},{get(s,c){let l=n[c];if(typeof l=="function")return(...d)=>{let u=l.apply(n.context,d),M=Object.assign({context:u.context},o);return r(M),M}}});return{get state(){return n},get context(){return n.context},actions:a,setState:r}}function Re(e,t,n){let r=()=>{let o=e.getContext(),a=n(o),s=t[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(o)},i=new Proxy({},{get(o,a){let s=r(),c=s[a];if(typeof c!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...l)=>c.apply(s.context,l)}});return{get context(){return e.getContext()},get state(){return r()},actions:i}}function Ye(e,t){return function(r){return Re(e,r,t)}}function Xe(e,t){let n=je(t),r=e(n),i=r.next();for(;!i.done;)i=r.next();return i.value}function Qe(e,t){let n=e(t),r=n.next();for(;!r.done;)r=n.next();return r.value}var _=class{constructor(t){this.store=t}get context(){return this.store.getContext()}setContext(t){this.store.setContext(t)}};function Ze(e,t){let n=new e(t);return new Proxy({},{get(r,i){let o=t.getContext();if(i in o)return o[i];let a=n[i];if(typeof a=="function")return(...s)=>a.apply(n,s)},set(r,i,o){let a=t.getContext();if(i in a){let s={...a,[i]:o};return t.setContext(s),!0}return!1},has(r,i){let o=t.getContext();return i in o||typeof n[i]=="function"},ownKeys(r){let i=t.getContext(),o=Object.keys(i),a=Object.getOwnPropertyNames(Object.getPrototypeOf(n)).filter(s=>s!=="constructor"&&typeof n[s]=="function");return Array.from(new Set([...o,...a]))},getOwnPropertyDescriptor(r,i){let o=t.getContext();if(i in o||typeof n[i]=="function")return{value:void 0,writable:!0,enumerable:!0,configurable:!0}}})}function et(e,t,n){let r=()=>{let i=n(e),o=t[i];if(!o)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(i)}".`);return o(e)};return new Proxy(e,{get(i,o,a){if(o in i)return i[o];let s=r(),c=s[o];if(typeof c=="function")return(...l)=>{let d=c.apply(s.context,l);if(typeof d!="object"||d===null){console.warn(`[MutableMachine] Transition "${String(o)}" did not return a valid context object. State may be inconsistent.`);return}Object.keys(i).forEach(u=>delete i[u]),Object.assign(i,d)}},set(i,o,a,s){return i[o]=a,!0},has(i,o){let a=r();return o in i||typeof a[o]=="function"}})}function tt(e){return function(...t){let n=this.context.child;if(typeof n[e]=="function"){let r=n[e](...t);return S(this,{...this.context,child:r})}return this}}function nt(e){return function(){return typeof this.context[e]!="boolean"&&console.warn(`[toggle primitive] Property '${String(e)}' is not a boolean. Toggling may have unexpected results.`),S(this,{...this.context,[e]:!this.context[e]})}}var W=class extends T{constructor(n){super({status:"idle"});this.config=n;this.fetch=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}},E=class extends T{constructor(n,r,i){super({status:"loading",abortController:new AbortController,attempts:i});this.config=n;this.params=r;this.succeed=n=>{var r,i;return(i=(r=this.config).onSuccess)==null||i.call(r,n),new G(this.config,{status:"success",data:n})};this.fail=n=>{var i,o,a;let r=(i=this.config.maxRetries)!=null?i:3;return this.context.attempts<r?new L(this.config,this.params,n,this.context.attempts):((a=(o=this.config).onError)==null||a.call(o,n),new H(this.config,{status:"error",error:n}))};this.cancel=()=>(this.context.abortController.abort(),new I(this.config));this.execute()}async execute(){}},L=class extends T{constructor(n,r,i,o){super({status:"retrying",error:i,attempts:o});this.config=n;this.params=r;this.retry=n=>new E(this.config,n!=null?n:this.params,this.context.attempts+1)}},G=class extends T{constructor(n,r){super(r);this.config=n;this.refetch=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}},H=class extends T{constructor(n,r){super(r);this.config=n;this.retry=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}},I=class extends T{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}};function rt(e){return new W(e)}function V(e,t){let n={...e.context,...t.context},r={...e},i={...t};delete r.context,delete i.context;let o={};for(let a in r){let s=r[a];o[a]=(...c)=>{let l=s.apply(e.context,c);return V(l,t)}}for(let a in i){let s=i[a];o[a]=(...c)=>{let l=s.apply(t.context,c);return V(e,l)}}return{context:n,...o}}var p=require("ts-morph");function U(e,t=!1){let n=e.getSymbol();if(n&&n.getDeclarations().some(p.Node.isClassDeclaration))return n.getName();if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral())return e.getLiteralValue();if(e.isString())return"string";if(e.isNumber())return"number";if(e.isBoolean())return"boolean";if(e.isArray()){let r=e.getArrayElementTypeOrThrow();return[U(r,t)]}if(e.isObject()||e.isIntersection()){let r={},i=e.getProperties();for(let o of i){let a=o.getName();if(a.startsWith("__@"))continue;let s=o.getValueDeclaration();if(s)try{r[a]=U(s.getType(),t)}catch(c){t&&console.error(` Warning: Failed to serialize property ${a}:`,c),r[a]="unknown"}}return Object.keys(r).length>0?r:null}return t&&console.error(` Unhandled type: ${e.getText()}`),"unknown"}function Oe(e){return p.Node.isIdentifier(e)?e.getText():p.Node.isTypeOfExpression(e)?e.getExpression().getText():"unknown"}function F(e){if(!p.Node.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(p.Node.isPropertyAssignment(n)){let r=n.getName(),i=n.getInitializer();i&&(p.Node.isStringLiteral(i)||p.Node.isNumericLiteral(i)?t[r]=i.getLiteralValue():i.getText()==="true"||i.getText()==="false"?t[r]=i.getText()==="true":p.Node.isIdentifier(i)?t[r]=i.getText():p.Node.isObjectLiteralExpression(i)?t[r]=F(i):p.Node.isArrayLiteralExpression(i)&&(t[r]=i.getElements().map(o=>p.Node.isObjectLiteralExpression(o)?F(o):o.getText())))}return t}function it(e){if(!p.Node.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(p.Node.isPropertyAssignment(n)){let r=n.getName(),i=n.getInitializer();if(!i)continue;r==="onDone"||r==="onError"?t[r]=Oe(i):p.Node.isStringLiteral(i)?t[r]=i.getLiteralValue():p.Node.isIdentifier(i)&&(t[r]=i.getText())}return t}function A(e,t=!1){if(!p.Node.isCallExpression(e))return null;let n=e.getExpression(),r=p.Node.isIdentifier(n)?n.getText():null;if(!r)return null;let i={},o=e.getArguments();switch(r){case"transitionTo":o[0]&&(i.target=Oe(o[0]));break;case"describe":if(o[0]&&p.Node.isStringLiteral(o[0])&&(i.description=o[0].getLiteralValue()),o[1]&&p.Node.isCallExpression(o[1])){let a=A(o[1],t);a&&Object.assign(i,a)}break;case"guarded":if(o[0]){let a=F(o[0]);Object.keys(a).length>0&&(i.guards=[a])}if(o[1]&&p.Node.isCallExpression(o[1])){let a=A(o[1],t);a&&Object.assign(i,a)}break;case"invoke":if(o[0]){let a=it(o[0]);Object.keys(a).length>0&&(i.invoke=a)}break;case"action":if(o[0]){let a=F(o[0]);Object.keys(a).length>0&&(i.actions=[a])}if(o[1]&&p.Node.isCallExpression(o[1])){let a=A(o[1],t);a&&Object.assign(i,a)}break;case"guard":if(o[2]){let a=F(o[2]);a.description&&(i.description=a.description)}if(i.guards=[{name:"runtime_guard",description:i.description||"Synchronous condition check"}],o[1]&&p.Node.isCallExpression(o[1])){let a=A(o[1],t);a&&Object.assign(i,a)}break;case"guardAsync":if(o[2]){let a=F(o[2]);a.description&&(i.description=a.description)}if(i.guards=[{name:"runtime_guard_async",description:i.description||"Asynchronous condition check"}],o[1]&&p.Node.isCallExpression(o[1])){let a=A(o[1],t);a&&Object.assign(i,a)}break;default:return null}return Object.keys(i).length>0?i:null}function ot(e,t=!1){if(!p.Node.isPropertyDeclaration(e))return t&&console.error(" ⚠️ Not a property declaration"),null;let n=e.getInitializer();if(!n)return t&&console.error(" ⚠️ No initializer"),null;if(!p.Node.isCallExpression(n))return t&&console.error(" ⚠️ Initializer is not a call expression"),null;let r=A(n,t);return r&&t&&console.error(" ✅ Extracted metadata:",JSON.stringify(r,null,2)),r}function q(e,t=!1){let n={on:{}},r=e.getDeclarations()[0];if(!r||!p.Node.isClassDeclaration(r))return t&&console.error(`⚠️ Warning: Could not get class declaration for ${e.getName()}`),n;let i=e.getName();t&&console.error(` Analyzing state: ${i}`);for(let o of r.getInstanceMembers()){let a=o.getName();t&&console.error(` Checking member: ${a}`);let s=ot(o,t);if(!s)continue;t&&console.error(` Found transition: ${a}`);let{invoke:c,actions:l,guards:d,...u}=s;if(c&&(n.invoke||(n.invoke=[]),n.invoke.push({src:c.src,onDone:{target:c.onDone},onError:{target:c.onError},description:c.description}),t&&console.error(` → Invoke: ${c.src}`)),u.target){let M={target:u.target};u.description&&(M.description=u.description),d&&(M.cond=d.map(y=>y.name).join(" && "),t&&console.error(` → Guard: ${M.cond}`)),l&&l.length>0&&(M.actions=l.map(y=>y.name),t&&console.error(` → Actions: ${M.actions.join(", ")}`)),n.on[a]=M,t&&console.error(` → Target: ${u.target}`)}}return n}function at(e,t,n,r,i=!1){let o=q(t,i);if(r){i&&console.error(` 👪 Analyzing children for state: ${e}`),o.initial=r.initialState,o.states={};for(let a of r.classes){let s=n.getClass(a);if(s){let c=s.getSymbolOrThrow();o.states[a]=q(c,i)}else console.warn(`⚠️ Warning: Child class '${a}' not found.`)}}return o}function J(e,t,n=!1){n&&(console.error(`
|
|
2
|
+
🔍 Analyzing machine: ${e.id}`),console.error(` Source: ${e.input}`));let r=t.getSourceFile(e.input);if(!r)throw new Error(`Source file not found: ${e.input}`);if(e.parallel){n&&console.error(" ⏹️ Parallel machine detected. Analyzing regions.");let o={id:e.id,type:"parallel",states:{}};e.description&&(o.description=e.description);for(let a of e.parallel.regions){n&&console.error(` 📍 Analyzing region: ${a.name}`);let s={};for(let c of a.classes){let l=r.getClass(c);if(l){let d=l.getSymbolOrThrow();s[c]=q(d,n)}else console.warn(`⚠️ Warning: Class '${c}' not found for region '${a.name}'.`)}o.states[a.name]={initial:a.initialState,states:s}}return n&&console.error(` ✅ Extracted ${e.parallel.regions.length} parallel regions`),o}if(!e.initialState||!e.classes)throw new Error(`Machine config for '${e.id}' must have either 'parallel' or 'initialState'/'classes'.`);let i={id:e.id,initial:e.initialState,states:{}};e.description&&(i.description=e.description);for(let o of e.classes){let a=r.getClass(o);if(!a){console.warn(`⚠️ Warning: Class '${o}' not found in '${e.input}'. Skipping.`);continue}let s=a.getSymbolOrThrow(),c=o===e.initialState&&e.children,l=at(o,s,r,c?e.children:void 0,n);i.states[o]=l}return n&&console.error(` ✅ Extracted ${e.classes.length} states`),i}function st(e){var i;let t=(i=e.verbose)!=null?i:!1;t&&(console.error(`
|
|
3
|
+
📊 Starting statechart extraction`),console.error(` Machines to extract: ${e.machines.length}`));let n=new p.Project;n.addSourceFilesAtPaths("src/**/*.ts"),n.addSourceFilesAtPaths("examples/**/*.ts");let r=[];for(let o of e.machines)try{let a=J(o,n,t);r.push(a)}catch(a){console.error(`❌ Error extracting machine '${o.id}':`,a),t||console.error(" Run with --verbose for more details")}return t&&console.error(`
|
|
4
|
+
✅ Extraction complete: ${r.length}/${e.machines.length} machines extracted`),r}function Pe(){let e={input:"examples/authMachine.ts",classes:["LoggedOutMachine","LoggingInMachine","LoggedInMachine","SessionExpiredMachine","ErrorMachine"],id:"auth",initialState:"LoggedOutMachine",description:"Authentication state machine"};console.error("🔍 Using legacy generateChart function"),console.error(`⚠️ Consider using extractMachines() with a config file instead
|
|
5
|
+
`);let t=new p.Project;t.addSourceFilesAtPaths("src/**/*.ts"),t.addSourceFilesAtPaths("examples/**/*.ts");try{let n=J(e,t,!0);console.log(JSON.stringify(n,null,2))}catch(n){console.error("❌ Error:",n),process.exit(1)}}var ct={hierarchical:{input:"examples/dashboardMachine.ts",id:"dashboard",classes:["DashboardMachine","LoggedOutMachine"],initialState:"DashboardMachine",children:{contextProperty:"child",initialState:"ViewingChildMachine",classes:["ViewingChildMachine","EditingChildMachine"]}},parallel:{input:"examples/editorMachine.ts",id:"editor",parallel:{regions:[{name:"fontWeight",initialState:"NormalWeight",classes:["NormalWeight","BoldWeight"]},{name:"textDecoration",initialState:"NoDecoration",classes:["NoDecoration","UnderlineState"]}]}}};require.main===module&&Pe();var Y=Symbol("CANCEL");function C(e,t,n={}){let{continueOnError:r=!1,logErrors:i=!0,onError:o}=n,a={...e};for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&s!=="context"&&typeof e[s]!="function"&&(a[s]=e[s]);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s];typeof c=="function"&&s!=="context"&&(a[s]=function(...l){let d=s,u=a.context,M=()=>{let y;try{y=c.apply(this,l)}catch(f){if(t.error)try{t.error({transitionName:d,context:u,args:[...l],error:f})}catch(h){if(!r)throw h;i&&console.error(`Middleware error hook error for ${d}:`,h),o==null||o(h,"error",{transitionName:d,context:u,args:l,error:f})}throw f}let x=f=>{if(f&&typeof f=="object"&&f.context){for(let h in a)Object.prototype.hasOwnProperty.call(a,h)&&h!=="context"&&!(h in f)&&(f[h]=a[h]);for(let h in f){if(!Object.prototype.hasOwnProperty.call(f,h))continue;typeof f[h]=="function"&&h!=="context"&&a[h]&&(f[h]=a[h])}}return f};if(y&&typeof y.then=="function")return y.then(h=>{if(x(h),t.after)try{let m=t.after({transitionName:d,prevContext:u,nextContext:h.context,args:[...l]});if(m&&typeof m.then=="function")return m.then(()=>h)}catch(m){if(!r)throw m;i&&console.error(`Middleware after hook error for ${d}:`,m),o==null||o(m,"after",{transitionName:d,prevContext:u,nextContext:h.context,args:l})}return h});if(x(y),t.after)try{let f=t.after({transitionName:d,prevContext:u,nextContext:y.context,args:[...l]});if(f&&typeof f=="object"&&f&&"then"in f)return f.then(()=>y).catch(h=>{if(!r)throw h;return i&&console.error(`Middleware after hook error for ${d}:`,h),o==null||o(h,"after",{transitionName:d,prevContext:u,nextContext:y.context,args:l}),y})}catch(f){if(!r)throw f;i&&console.error(`Middleware after hook error for ${d}:`,f),o==null||o(f,"after",{transitionName:d,prevContext:u,nextContext:y.context,args:l})}return y};if(t.before)try{let y=t.before({transitionName:d,context:u,args:[...l]});if(y&&typeof y=="object"&&y&&"then"in y)return y.then(x=>x===Y?a:M()).catch(x=>{if(!r)throw x;return i&&console.error(`Middleware before hook error for ${d}:`,x),o==null||o(x,"before",{transitionName:d,context:u,args:l}),M()});if(y===Y)return a}catch(y){if(!r)throw y;i&&console.error(`Middleware before hook error for ${d}:`,y),o==null||o(y,"before",{transitionName:d,context:u,args:l})}return M()})}return a}function X(e,t={}){let{logger:n=console.log,includeArgs:r=!1,includeContext:i=!0}=t;return C(e,{before:({transitionName:o,args:a})=>{let s=r?`→ ${o} [${a.join(", ")}]`:`→ ${o}`;n(s)},after:({transitionName:o,nextContext:a})=>{let s=i?` ${JSON.stringify(a)}`:"";n(`✓ ${o}${s}`)},error:({transitionName:o,error:a})=>{console.error(`[Machine] ${o} failed:`,a)}})}function Q(e,t,n={}){let{eventPrefix:r="state_transition",includePrevContext:i=!1,includeArgs:o=!1}=n;return C(e,{after:({transitionName:a,prevContext:s,nextContext:c,args:l})=>{let d=`${r}.${a}`,u={transition:a};i&&(u.from=s),u.to=c,o&&(u.args=l),t(d,u)}})}function Z(e,t){return C(e,{before:n=>{if(t(n)===!1)throw new Error(`Validation failed for transition: ${n.transitionName}`)}})}function ee(e,t){return C(e,{before:n=>{if(!t(n))throw new Error(`Unauthorized transition: ${n.transitionName}`)}})}function te(e,t,n={}){let{includeArgs:r=!1}=n;return C(e,{error:i=>{let o={transition:i.transitionName,context:i.context,...r&&{args:i.args}};t(i.error,o)}})}function ne(e,t){let n=new Map;return C(e,{before:r=>{n.set(r.transitionName,Date.now())},after:r=>{let i=n.get(r.transitionName);if(i){let o=Date.now()-i;n.delete(r.transitionName);let a={transitionName:r.transitionName,duration:o,context:r.nextContext||r.prevContext};t(a)}}})}function re(e,t={}){var c,l;let{maxAttempts:n=(c=t.maxRetries)!=null?c:3,shouldRetry:r=()=>!0,backoffMs:i=(l=t.delay)!=null?l:100,backoffMultiplier:o=2,onRetry:a}=t,s={...e};for(let d in e){if(!Object.prototype.hasOwnProperty.call(e,d))continue;let u=e[d];typeof u=="function"&&d!=="context"&&(s[d]=async function(...M){let y,x=0;for(;x<n;)try{return await u.apply(this,M)}catch(f){if(y=f,x++,x<n&&r(y,x)){a==null||a(y,x);let m=(typeof i=="function"?i(x):i)*Math.pow(o,x-1);await new Promise(b=>setTimeout(b,m))}else throw y}throw y})}return s}function lt(e,t){return n=>C(n,e,t)}function O(e,t={}){let{maxSize:n,serializer:r,onEntry:i}=t,o=[],a=0,s=C(e,{before:({transitionName:c,args:l})=>{let d={id:`entry-${a++}`,transitionName:c,args:[...l],timestamp:Date.now()};if(r)try{d.serializedArgs=r.serialize(l)}catch(u){console.error("Failed to serialize history args:",u)}o.push(d),n&&o.length>n&&o.shift(),i==null||i(d)}});return Object.assign(s,{history:o,clearHistory:()=>{o.length=0,a=0}})}function P(e,t={}){let{maxSize:n,serializer:r,captureSnapshot:i,onlyOnChange:o=!1}=t,a=[],s=0,c=C(e,{after:({transitionName:d,prevContext:u,nextContext:M})=>{if(o&&JSON.stringify(u)===JSON.stringify(M))return;let y={id:`snapshot-${s++}`,transitionName:d,before:{...u},after:{...M},timestamp:Date.now()};if(r)try{y.serializedBefore=r.serialize(u),y.serializedAfter=r.serialize(M)}catch(x){console.error("Failed to serialize snapshot:",x)}if(i)try{y.diff=i(u,M)}catch(x){console.error("Failed to capture snapshot:",x)}a.push(y),n&&a.length>n&&a.shift()}});return Object.assign(c,{snapshots:a,clearSnapshots:()=>{a.length=0,s=0},restoreSnapshot:d=>{let u=Object.fromEntries(Object.entries(e).filter(([M])=>M!=="context"&&M!=="snapshots"&&M!=="clearSnapshots"&&M!=="restoreSnapshot"&&typeof e[M]=="function"));return Object.assign({context:d},u)}})}function k(e,t={}){let{maxSize:n,serializer:r,onRecord:i}=t,o=[],a=[],s=0,c=0,l=C(e,{before:({transitionName:M,args:y})=>{let x={id:`entry-${s++}`,transitionName:M,args:[...y],timestamp:Date.now()};if(r)try{x.serializedArgs=r.serialize(y)}catch(f){console.error("Failed to serialize history args:",f)}o.push(x),n&&o.length>n&&o.shift(),i==null||i("history",x)},after:({transitionName:M,prevContext:y,nextContext:x})=>{let f={id:`snapshot-${c++}`,transitionName:M,before:{...y},after:{...x},timestamp:Date.now()};if(r)try{f.serializedBefore=r.serialize(y),f.serializedAfter=r.serialize(x)}catch(h){console.error("Failed to serialize snapshot:",h)}a.push(f),n&&a.length>n&&a.shift(),i==null||i("snapshot",f)}});return Object.assign(l,{history:o,snapshots:a,clearHistory:()=>{o.length=0,s=0},clearSnapshots:()=>{a.length=0,c=0},clearTimeTravel:()=>{o.length=0,a.length=0,s=0,c=0},restoreSnapshot:M=>{let y=Object.fromEntries(Object.entries(e).filter(([x])=>x!=="context"&&x!=="history"&&x!=="snapshots"&&x!=="clearHistory"&&x!=="clearSnapshots"&&x!=="restoreSnapshot"&&x!=="clearTimeTravel"&&x!=="replayFrom"&&typeof e[x]=="function"));return Object.assign({context:M},y)},replayFrom:M=>{var m;if(M<0||M>=o.length)throw new Error(`Invalid replay start index: ${M}`);let y=(m=a[M])==null?void 0:m.before;if(!y)throw new Error(`No snapshot available for index ${M}`);let x=o.slice(M),h=Object.assign({context:y},Object.fromEntries(Object.entries(e).filter(([b])=>b!=="context"&&typeof e[b]=="function")));for(let b of x){let de=h[b.transitionName];de&&(h=de.apply(h.context,b.args))}return h}})}function dt(e,...t){return t.reduce((n,r)=>r(n),e)}function v(e,...t){return t.reduce((n,r)=>r(n),e)}var ie=class e{constructor(t){this.machine=t}with(t){let n=t(this.machine);return new e(n)}build(){return this.machine}};function ut(e){return new ie(e)}function K(e,t){let n=function(r){return t(r)?e(r):r};return n.middleware=e,n.when=t,n}function yt(e){return K(e,()=>typeof process!="undefined"?!1:typeof window!="undefined"?!window.location.hostname.includes("production"):!1)}function Mt(e,t,n){return K(n,r=>r.context[e]===t)}function xt(){let e=new Map;return{register(t,n,r,i){if(e.has(t))throw new Error(`Middleware '${t}' is already registered`);return e.set(t,{name:t,middleware:n,description:r,priority:i}),this},unregister(t){return e.delete(t)},has(t){return e.has(t)},get(t){return e.get(t)},list(){return Array.from(e.values()).sort((t,n)=>{var r,i;return((r=t.priority)!=null?r:0)-((i=n.priority)!=null?i:0)})},apply(t,n){let r=n.map(i=>{let o=e.get(i);if(!o)throw new Error(`Middleware '${i}' is not registered`);return o}).sort((i,o)=>{var a,s;return((a=i.priority)!=null?a:0)-((s=o.priority)!=null?s:0)});return v(t,...r.map(i=>i.middleware))},applyAll(t){let n=this.list();return v(t,...n.map(r=>r.middleware))}}}function ft(e={}){let{continueOnError:t=!1,logErrors:n=!0,onError:r}=e;return(i,...o)=>{let a=i,s=[],c=!0;for(let l=0;l<o.length;l++){let d=o[l];try{if("middleware"in d&&"when"in d){if(!d.when(a))continue;a=d.middleware(a)}else a=d(a)}catch(u){if(c=!1,!t)throw u;s.push({error:u,middlewareIndex:l,middlewareName:d.name}),n&&console.error(`Pipeline middleware error at index ${l}:`,u),r==null||r(u,l,d.name)}}return{machine:a,errors:s,success:c}}}function ht(...e){return t=>v(t,...e)}function pt(e,t){return n=>{for(let[r,i]of e)if(r(n))return i(n);return t?t(n):n}}function oe(e){return typeof e=="function"&&e.length===1}function gt(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"middleware"in e&&"when"in e&&oe(e.middleware)&&typeof e.when=="function"}function Ct(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"prevContext"in e&&"nextContext"in e&&"args"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&(!t||N(e.prevContext,t)&&N(e.nextContext,t))}function mt(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"context"in e&&"args"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&(!t||N(e.context,t))}function Tt(e,t){return e!==null&&typeof e=="object"&&"transitionName"in e&&"context"in e&&"args"in e&&"error"in e&&typeof e.transitionName=="string"&&Array.isArray(e.args)&&e.error instanceof Error&&(!t||N(e.context,t))}function bt(e,t){if(e===null||typeof e!="object")return!1;let n=e;return!("before"in n&&n.before!==void 0&&typeof n.before!="function"||"after"in n&&n.after!==void 0&&typeof n.after!="function"||"error"in n&&n.error!==void 0&&typeof n.error!="function")}function wt(e){return e===void 0||e!==null&&typeof e=="object"&&("continueOnError"in e?typeof e.continueOnError=="boolean":!0)&&("logErrors"in e?typeof e.logErrors=="boolean":!0)&&("onError"in e?typeof e.onError=="function"||e.onError===void 0:!0)}function N(e,t){return e!==null&&typeof e=="object"}function Et(e){return e!==null&&typeof e=="object"&&"name"in e&&"middleware"in e&&typeof e.name=="string"&&oe(e.middleware)&&("description"in e?typeof e.description=="string"||e.description===void 0:!0)&&("priority"in e?typeof e.priority=="number"||e.priority===void 0:!0)}function St(e){return e===void 0||e!==null&&typeof e=="object"&&("continueOnError"in e?typeof e.continueOnError=="boolean":!0)&&("logErrors"in e?typeof e.logErrors=="boolean":!0)&&("onError"in e?typeof e.onError=="function"||e.onError===void 0:!0)}var B=class{constructor(t){this.machine=t;this.middlewares=[]}withLogging(t){return this.middlewares.push(n=>X(n,t)),this}withAnalytics(t,n){return this.middlewares.push(r=>Q(r,t,n)),this}withValidation(t,n){return this.middlewares.push(r=>Z(r,t)),this}withPermissions(t){return this.middlewares.push(n=>ee(n,t)),this}withErrorReporting(t,n){return this.middlewares.push(r=>te(r,t,n)),this}withPerformanceMonitoring(t,n){return this.middlewares.push(r=>ne(r,t)),this}withRetry(t){return this.middlewares.push(n=>re(n,t)),this}withHistory(t){return this.middlewares.push(n=>O(n,t)),this}withSnapshot(t){return this.middlewares.push(n=>P(n,t)),this}withTimeTravel(t){return this.middlewares.push(n=>k(n,t)),this}withDebugging(){return this.middlewares.push(t=>ve(t)),this}withCustom(t){return this.middlewares.push(t),this}withConditional(t,n){return this.middlewares.push(K(t,n)),this}build(){let t=this.machine;for(let n of this.middlewares)t=n(t);return t}getChain(){return[...this.middlewares]}clear(){return this.middlewares=[],this}};function ke(e){return new B(e)}function At(e={}){return{create:t=>{let n=ke(t);return e.logging&&n.withLogging(e.logging),e.analytics&&n.withAnalytics(e.analytics.track,e.analytics.options),e.history&&n.withHistory(e.history),e.snapshot&&n.withSnapshot(e.snapshot),e.timeTravel&&n.withTimeTravel(e.timeTravel),e.retry&&n.withRetry(e.retry),n}}}function ve(e){return k(P(O(e)))}function Ne(e,t){return e instanceof t}function Be(e,...t){return{type:e,args:t}}function Ke(e,t){return S(e,n=>({...n,...t}))}async function ze(e,...t){let n=e;for(let r of t)n=await r(n);return n}function $e(e,t){return t?console.log(t,e.context):console.log(e.context),e}function De(e,t){return function(...n){let r=t(this.context,...n);return g(r,e())}}function _e(e,t,...n){return e.apply(t,n)}function ae(e){return new Proxy(e,{get(t,n){let r=t[n];return typeof r=="function"?function(...i){let o=r.apply(t.context,i);return o&&typeof o=="object"&&"context"in o?ae(o):o}:r}})}var z=class e{constructor(t){return this.wrappedMachine=t,new Proxy(this,{get:(n,r)=>{if(r==="wrappedMachine")return Reflect.get(n,r);if(r==="context")return this.wrappedMachine.context;let i=this.wrappedMachine[r];return typeof i=="function"?(...o)=>{let a=i.apply(this.wrappedMachine.context,o);return a&&typeof a=="object"&&"context"in a?new e(a):a}:i}})}};function We(){return function(t){return function(...n){let r=t(this.context,...n);return g(r,this)}}}function se(e){return{machine:e,addTransition:function(t,n){let r=function(...o){let a=n(this.context,...o);return g(a,this)},i=le(e,{[t]:r});return se(i)}}}function ce(e){return function(n){let r={},i=Object.fromEntries(Object.entries(n).map(([o,a])=>[o,function(...s){let c=a(this.context,...s);return g(c,r)}]));return Object.assign(r,i),g(e,r)}}function Le(e,t){return t!==void 0?g(e,t):ce(e)}function g(e,t){if(typeof t=="function"){let i;i=t(s=>{let c=g(s,i),l=Object.fromEntries(Object.entries(i).map(([d,u])=>[d,u.bind(s)]));return Object.assign(c,l)});let a=Object.fromEntries(Object.entries(i).map(([s,c])=>[s,c.bind(e)]));return Object.assign({context:e},a)}let n="context"in t?Object.fromEntries(Object.entries(t).filter(([i])=>i!=="context")):t;return Object.assign({context:e},n)}function Ge(e,t){if(typeof t=="function"){let i;i=t(s=>{let c=Ge(s,i),l=Object.fromEntries(Object.entries(i).map(([d,u])=>[d,u.bind(s)]));return Object.assign(c,l)});let a=Object.fromEntries(Object.entries(i).map(([s,c])=>[s,c.bind(e)]));return Object.assign({context:e},a)}let n="context"in t?Object.fromEntries(Object.entries(t).filter(([i])=>i!=="context")):t;return Object.assign({context:e},n)}function Ft(){return e=>{let t=Object.fromEntries(Object.entries(e).map(([n,r])=>[n,function(...i){let o=r(this.context,...i);return g(o,t)}]));return n=>g(n,t)}}function S(e,t){let{context:n,...r}=e,i=typeof t=="function"?t(n):t;return g(i,r)}function jt(e,t){let{context:n,...r}=e,i={...r,...t};return g(n,i)}function le(e,t){let{context:n,...r}=e,i={...r,...t};return g(n,i)}function Rt(e,t){return(...n)=>{let r=e(...n),i=t(),o={...r.context,...i.context},{context:a,...s}=r,{context:c,...l}=i,d={...s,...l};return g(o,d)}}function Ot(e){let{context:t,...n}=e;return r=>g(r,n)}function Pt(e,t,n){let r=e.context[t],i=n[r];if(!i)throw new Error(`No handler found for state: ${String(r)}`);return i(e.context)}function kt(e,t,n){return e.context[t]===n}function vt(e,t){let n=e,r=null;async function i(o){r&&(r.abort(),r=null);let a=n[o.type];if(typeof a!="function")throw new Error(`[Machine] Unknown event type '${String(o.type)}' on current state.`);let s=new AbortController;r=s;try{let l=await a.apply(n.context,[...o.args,{signal:s.signal}]);return s.signal.aborted||(n=l,t==null||t(n)),n}finally{r===s&&(r=null)}}return{get state(){return n.context},dispatch:i,stop:()=>{r&&(r.abort(),r=null)}}}var T=class{constructor(t){this.context=t}};function Nt(e,t){let{context:n,...r}=e;return g(t(n),r)}
|