@doeixd/machine 0.0.22 → 0.0.23

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.
@@ -0,0 +1 @@
1
+ function q(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=n.next(r);if(i)return o;r=o}}function le(e){return function*(){return yield e}()}function Me(e){return e}function xe(e,t){return t.reduce((n,r)=>q(r,n),e)}function he(e){return e}function fe(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 pe(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*ge(e){return yield e}var Ce=Symbol("MachineMeta"),Y=Symbol("__machine_runtime_meta__");function w(e,t){let n=e[Y]||{},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,Y,{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 R(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=function(...d){let c=typeof this=="object"&&"context"in this,u=c?this.context:this;if(e(u,...d)){let M=c?this.context:this;return t.apply(M,d)}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,d);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:i||"Synchronous guarded transition",guards:[{name:"runtime_guard",description:i||"Synchronous condition check"}]}),s}function j(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=async function(...d){let c=typeof this=="object"&&"context"in this,u=c?this.context:this;if(await Promise.resolve(e(u,...d))){let M=c?this.context:this;return t.apply(M,d)}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,d);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:i||"Runtime guarded transition",guards:[{name:"runtime_guard",description:i||"Runtime condition check"}]}),s}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){return{do(t){let n=j(e,t);return n.else=function(r){return j(e,t,{onFail:r})},n}}}function Se(e,t){return t}function Re(e,t){let n=e,r=s=>{n=s,t==null||t(s)},{context:o,...i}=e,a=new Proxy({},{get(s,d){let c=n[d];if(typeof c=="function")return(...u)=>{let l=c.apply(n.context,u),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 v(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(),d=s[a];if(typeof d!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...c)=>d.apply(s.context,c)}});return{get context(){return e.getContext()},get state(){return r()},actions:o}}function et(e,t){return function(r){return v(e,r,t)}}function tt(e,t){let n=Re(t),r=e(n),o=r.next();for(;!o.done;)o=r.next();return o.value}function nt(e,t){let n=e(t),r=n.next();for(;!r.done;)r=n.next();return r.value}var J=class{constructor(t){this.store=t}get context(){return this.store.getContext()}setContext(t){this.store.setContext(t)}};function rt(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 ot(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(),d=s[i];if(typeof d=="function")return(...c)=>{let u=d.apply(s.context,c);if(typeof u!="object"||u===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,u)}},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 ut(e){return function(...t){let n=this.context.child;if(typeof n[e]=="function"){let r=n[e](...t);return A(this,{...this.context,child:r})}return this}}function yt(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.`),A(this,{...this.context,[e]:!this.context[e]})}}var O=class extends m{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 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 B(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 P(this.config,this.params,n,this.context.attempts):((a=(i=this.config).onError)==null||a.call(i,n),new k(this.config,{status:"error",error:n}))};this.cancel=()=>(this.context.abortController.abort(),new K(this.config));this.execute()}async execute(){}},P=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 E(this.config,n!=null?n:this.params,this.context.attempts+1)}},B=class extends m{constructor(n,r){super(r);this.config=n;this.refetch=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}},k=class extends m{constructor(n,r){super(r);this.config=n;this.retry=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}},K=class extends m{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new E(this.config,n!=null?n:this.config.initialParams,1)}};function lt(e){return new O(e)}function Q(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]=(...d)=>{let c=s.apply(e.context,d);return Q(c,t)}}for(let a in o){let s=o[a];i[a]=(...d)=>{let c=s.apply(t.context,d);return Q(e,c)}}return{context:n,...i}}var X=Symbol("CANCEL");function C(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 d=e[s];typeof d=="function"&&s!=="context"&&(a[s]=function(...c){let u=s,l=a.context,M=()=>{let y;try{y=d.apply(this,c)}catch(h){if(t.error)try{t.error({transitionName:u,context:l,args:[...c],error:h})}catch(f){if(!r)throw f;o&&console.error(`Middleware error hook error for ${u}:`,f),i==null||i(f,"error",{transitionName:u,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 g=t.after({transitionName:u,prevContext:l,nextContext:f.context,args:[...c]});if(g&&typeof g.then=="function")return g.then(()=>f)}catch(g){if(!r)throw g;o&&console.error(`Middleware after hook error for ${u}:`,g),i==null||i(g,"after",{transitionName:u,prevContext:l,nextContext:f.context,args:c})}return f});if(x(y),t.after)try{let h=t.after({transitionName:u,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 ${u}:`,f),i==null||i(f,"after",{transitionName:u,prevContext:l,nextContext:y.context,args:c}),y})}catch(h){if(!r)throw h;o&&console.error(`Middleware after hook error for ${u}:`,h),i==null||i(h,"after",{transitionName:u,prevContext:l,nextContext:y.context,args:c})}return y};if(t.before)try{let y=t.before({transitionName:u,context:l,args:[...c]});if(y&&typeof y=="object"&&y&&"then"in y)return y.then(x=>x===X?a:M()).catch(x=>{if(!r)throw x;return o&&console.error(`Middleware before hook error for ${u}:`,x),i==null||i(x,"before",{transitionName:u,context:l,args:c}),M()});if(y===X)return a}catch(y){if(!r)throw y;o&&console.error(`Middleware before hook error for ${u}:`,y),i==null||i(y,"before",{transitionName:u,context:l,args:c})}return M()})}return a}function Z(e,t={}){let{logger:n=console.log,includeArgs:r=!1,includeContext:o=!0}=t;return C(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 ee(e,t,n={}){let{eventPrefix:r="state_transition",includePrevContext:o=!1,includeArgs:i=!1}=n;return C(e,{after:({transitionName:a,prevContext:s,nextContext:d,args:c})=>{let u=`${r}.${a}`,l={transition:a};o&&(l.from=s),l.to=d,i&&(l.args=c),t(u,l)}})}function te(e,t){return C(e,{before:n=>{if(t(n)===!1)throw new Error(`Validation failed for transition: ${n.transitionName}`)}})}function ne(e,t){return C(e,{before:n=>{if(!t(n))throw new Error(`Unauthorized transition: ${n.transitionName}`)}})}function re(e,t,n={}){let{includeArgs:r=!1}=n;return C(e,{error:o=>{let i={transition:o.transitionName,context:o.context,...r&&{args:o.args}};t(o.error,i)}})}function oe(e,t){let n=new Map;return C(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 ie(e,t={}){var d,c;let{maxAttempts:n=(d=t.maxRetries)!=null?d:3,shouldRetry:r=()=>!0,backoffMs:o=(c=t.delay)!=null?c:100,backoffMultiplier:i=2,onRetry:a}=t,s={...e};for(let u in e){if(!Object.prototype.hasOwnProperty.call(e,u))continue;let l=e[u];typeof l=="function"&&u!=="context"&&(s[u]=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 g=(typeof o=="function"?o(x):o)*Math.pow(i,x-1);await new Promise(b=>setTimeout(b,g))}else throw y}throw y})}return s}function xt(e,t){return n=>C(n,e,t)}function N(e,t={}){let{maxSize:n,serializer:r,onEntry:o}=t,i=[],a=0,s=C(e,{before:({transitionName:d,args:c})=>{let u={id:`entry-${a++}`,transitionName:d,args:[...c],timestamp:Date.now()};if(r)try{u.serializedArgs=r.serialize(c)}catch(l){console.error("Failed to serialize history args:",l)}i.push(u),n&&i.length>n&&i.shift(),o==null||o(u)}});return Object.assign(s,{history:i,clearHistory:()=>{i.length=0,a=0}})}function z(e,t={}){let{maxSize:n,serializer:r,captureSnapshot:o,onlyOnChange:i=!1}=t,a=[],s=0,d=C(e,{after:({transitionName:u,prevContext:l,nextContext:M})=>{if(i&&JSON.stringify(l)===JSON.stringify(M))return;let y={id:`snapshot-${s++}`,transitionName:u,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(d,{snapshots:a,clearSnapshots:()=>{a.length=0,s=0},restoreSnapshot:u=>{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:u},l)}})}function _(e,t={}){let{maxSize:n,serializer:r,onRecord:o}=t,i=[],a=[],s=0,d=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(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-${d++}`,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,d=0},clearTimeTravel:()=>{i.length=0,a.length=0,s=0,d=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 g;if(M<0||M>=i.length)throw new Error(`Invalid replay start index: ${M}`);let y=(g=a[M])==null?void 0:g.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(([b])=>b!=="context"&&typeof e[b]=="function")));for(let b of x){let U=f[b.transitionName];U&&(f=U.apply(f.context,b.args))}return f}})}function Ft(e,...t){return t.reduce((n,r)=>r(n),e)}function G(e,...t){return t.reduce((n,r)=>r(n),e)}var W=class e{constructor(t){this.machine=t}with(t){let n=t(this.machine);return new e(n)}build(){return this.machine}};function St(e){return new W(e)}function $(e,t){let n=function(r){return t(r)?e(r):r};return n.middleware=e,n.when=t,n}function Rt(e){return $(e,()=>typeof process!="undefined"?!1:typeof window!="undefined"?!window.location.hostname.includes("production"):!1)}function jt(e,t,n){return $(n,r=>r.context[e]===t)}function vt(){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 G(t,...r.map(o=>o.middleware))},applyAll(t){let n=this.list();return G(t,...n.map(r=>r.middleware))}}}function Ot(e={}){let{continueOnError:t=!1,logErrors:n=!0,onError:r}=e;return(o,...i)=>{let a=o,s=[],d=!0;for(let c=0;c<i.length;c++){let u=i[c];try{if("middleware"in u&&"when"in u){if(!u.when(a))continue;a=u.middleware(a)}else a=u(a)}catch(l){if(d=!1,!t)throw l;s.push({error:l,middlewareIndex:c,middlewareName:u.name}),n&&console.error(`Pipeline middleware error at index ${c}:`,l),r==null||r(l,c,u.name)}}return{machine:a,errors:s,success:d}}}function Pt(...e){return t=>G(t,...e)}function Bt(e,t){return n=>{for(let[r,o]of e)if(r(n))return o(n);return t?t(n):n}}function ae(e){return typeof e=="function"&&e.length===1}function kt(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"middleware"in e&&"when"in e&&ae(e.middleware)&&typeof e.when=="function"}function Kt(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||F(e.prevContext,t)&&F(e.nextContext,t))}function Nt(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||F(e.context,t))}function zt(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||F(e.context,t))}function _t(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 F(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"&&ae(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 Ht(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 H=class{constructor(t){this.machine=t;this.middlewares=[]}withLogging(t){return this.middlewares.push(n=>Z(n,t)),this}withAnalytics(t,n){return this.middlewares.push(r=>ee(r,t,n)),this}withValidation(t,n){return this.middlewares.push(r=>te(r,t)),this}withPermissions(t){return this.middlewares.push(n=>ne(n,t)),this}withErrorReporting(t,n){return this.middlewares.push(r=>re(r,t,n)),this}withPerformanceMonitoring(t,n){return this.middlewares.push(r=>oe(r,t)),this}withRetry(t){return this.middlewares.push(n=>ie(n,t)),this}withHistory(t){return this.middlewares.push(n=>N(n,t)),this}withSnapshot(t){return this.middlewares.push(n=>z(n,t)),this}withTimeTravel(t){return this.middlewares.push(n=>_(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($(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 je(e){return new H(e)}function $t(e={}){return{create:t=>{let n=je(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 _(z(N(e)))}function Oe(e,t){return e instanceof t}function Pe(e,...t){return{type:e,args:t}}function Be(e,t){return A(e,n=>({...n,...t}))}async function ke(e,...t){let n=e;for(let r of t)n=await r(n);return n}function Ke(e,t){return t?console.log(t,e.context):console.log(e.context),e}function Ne(e,t){return function(...n){let r=t(this.context,...n);return p(r,e())}}function ze(e,t,...n){return e.apply(t,n)}function se(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?se(i):i}:r}})}var D=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 _e(){return function(t){return function(...n){let r=t(this.context,...n);return p(r,this)}}}function ce(e){return{machine:e,addTransition:function(t,n){let r=function(...i){let a=n(this.context,...i);return p(a,this)},o=V(e,{[t]:r});return ce(o)}}}function de(e){return function(n){let r={},o=Object.fromEntries(Object.entries(n).map(([i,a])=>[i,function(...s){let d=a(this.context,...s);return p(d,r)}]));return Object.assign(r,o),p(e,r)}}function Ge(e,t){return t!==void 0?p(e,t):de(e)}function p(e,t){if(typeof t=="function"){let o;o=t(s=>{let d=p(s,o),c=Object.fromEntries(Object.entries(o).map(([u,l])=>[u,l.bind(s)]));return Object.assign(d,c)});let a=Object.fromEntries(Object.entries(o).map(([s,d])=>[s,d.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 ue(e,t){if(typeof t=="function"){let o;o=t(s=>{let d=ue(s,o),c=Object.fromEntries(Object.entries(o).map(([u,l])=>[u,l.bind(s)]));return Object.assign(d,c)});let a=Object.fromEntries(Object.entries(o).map(([s,d])=>[s,d.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 We(){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 A(e,t){let{context:n,...r}=e,o=typeof t=="function"?t(n):t;return p(o,r)}function He(e,t){let{context:n,...r}=e,o={...r,...t};return p(n,o)}function V(e,t){let{context:n,...r}=e,o={...r,...t};return p(n,o)}function $e(e,t){return(...n)=>{let r=e(...n),o=t(),i={...r.context,...o.context},{context:a,...s}=r,{context:d,...c}=o,u={...s,...c};return p(i,u)}}function De(e){let{context:t,...n}=e;return r=>p(r,n)}function Ve(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 Ie(e,t,n){return e.context[t]===n}function I(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 Le(e,t){let{context:n,...r}=e;return p(t(n),r)}import{useState as S,useRef as L,useEffect as ye,useMemo as T,createContext as Ue,useContext as qe,createElement as Ye,useSyncExternalStore as Je}from"react";function En(e){let[t,n]=S(e),r=T(()=>I(t,i=>{n(i)}),[]),o=T(()=>new Proxy({},{get:(i,a)=>(...s)=>{r.dispatch({type:a,args:s})}}),[r]);return[t,o]}function Qe(e,t,n=Object.is){let[r,o]=S(()=>t(e)),i=L(t),a=L(n);return i.current=t,a.current=n,ye(()=>{let s=i.current(e);a.current(r,s)||o(s)},[e,r]),r}function An(e,t,n){let[r,o]=S(e),i=L(r);i.current=r;let a=T(()=>({getContext:()=>i.current,setContext:d=>{o(d)}}),[]);return T(()=>v(a,t,n),[a,t,n])}function Fn(){let e=Ue(null),t=({machine:a,actions:s,children:d})=>{let c=T(()=>[a,s],[a,s]);return Ye(e.Provider,{value:c},d)},n=()=>{let a=qe(e);if(!a)throw new Error("useMachineContext must be used within a Machine.Provider");return a},r=()=>n()[0];return{Provider:t,useMachineContext:n,useMachineState:r,useMachineActions:()=>n()[1],useSelector:(a,s)=>{let d=r();return Qe(d,a,s)}}}function Sn(e){let t=T(()=>e.subscribe.bind(e),[e]),n=T(()=>e.getSnapshot.bind(e),[e]);return Je(t,n)}function Rn(e,t,n=Object.is){let r=T(()=>e.subscribe.bind(e),[e]),o=T(()=>e.getSnapshot.bind(e),[e]),i=()=>t(o()),[a,s]=S(i);return ye(()=>{let d=()=>{let c=t(e.getSnapshot());s(u=>n(u,c)?u:c)};return d(),e.subscribe(()=>{d()})},[e,t,n]),a}export{D as BoundMachine,X as CANCEL,Ce as META_KEY,m as MachineBase,H as MiddlewareBuilder,J as MultiMachineBase,Ee as action,se as bindTransitions,Bt as branch,ze as call,St as chain,Pt as combine,$e as combineFactories,Ft as compose,G as composeTyped,ue as createAsyncMachine,xt as createCustomMiddleware,v as createEnsemble,et as createEnsembleFactory,Pe as createEvent,lt as createFetchMachine,he as createFlow,de as createFunctionalMachine,p as createMachine,De as createMachineBuilder,Fn as createMachineContext,We as createMachineFactory,C as createMiddleware,$t as createMiddlewareFactory,vt as createMiddlewareRegistry,rt as createMultiMachine,ot as createMutableMachine,Q as createParallelMachine,Ot as createPipeline,Re as createRunner,Ne as createTransition,ce as createTransitionExtender,_e as createTransitionFactory,ut as delegateToChild,Te as describe,V as extendTransitions,R as guard,j as guardAsync,be as guarded,Ie as hasState,Rt as inDevelopment,we as invoke,kt as isConditionalMiddleware,Nt as isMiddlewareContext,zt as isMiddlewareError,ae as isMiddlewareFn,_t as isMiddlewareHooks,Gt as isMiddlewareOptions,Kt as isMiddlewareResult,Wt as isNamedMiddleware,Ht as isPipelineConfig,Oe as isState,Ke as logState,Ve as matchMachine,Be as mergeContext,Se as metadata,je as middlewareBuilder,Le as next,He as overrideTransitions,ke as pipeTransitions,q as run,pe as runAsync,I as runMachine,xe as runSequence,fe as runWithDebug,nt as runWithEnsemble,tt as runWithRunner,A as setContext,Ge as state,le as step,ge as stepAsync,yt as toggle,me as transitionTo,Sn as useActor,Rn as useActorSelector,An as useEnsemble,En as useMachine,Qe as useMachineSelector,$ as when,jt as whenContext,Ae as whenGuard,Fe as whenGuardAsync,ee as withAnalytics,ve as withDebugging,re as withErrorReporting,N as withHistory,Z as withLogging,oe as withPerformanceMonitoring,ne as withPermissions,ie as withRetry,z as withSnapshot,_ as withTimeTravel,te as withValidation,Me as yieldMachine};
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @file React integration entry point
3
+ */
4
+ export * from './core';
5
+ export * from './react';
6
+ //# sourceMappingURL=entry-react.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry-react.d.ts","sourceRoot":"","sources":["../../src/entry-react.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,cAAc,QAAQ,CAAC;AAGvB,cAAc,SAAS,CAAC"}
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @file React integration for @doeixd/machine
3
+ * @description
4
+ * Provides a suite of hooks for integrating state machines with React components,
5
+ * covering simple component state, performance-optimized selections, and advanced
6
+ * framework-agnostic patterns.
7
+ *
8
+ * ---
9
+ *
10
+ * ### Hooks Overview
11
+ *
12
+ * 1. **`useMachine(machineFactory)`**:
13
+ * - **Best for:** Local, self-contained component state.
14
+ * - **Returns:** `[machine, actions]`
15
+ * - The simplest way to get started. It manages an immutable machine instance
16
+ * and provides a stable `actions` object to trigger transitions.
17
+ *
18
+ * 2. **`useMachineSelector(machine, selector, isEqual?)`**:
19
+ * - **Best for:** Performance optimization in child components.
20
+ * - **Returns:** A selected slice of the machine's state: `T`.
21
+ * - Subscribes a component to only a part of the machine's state, preventing
22
+ * unnecessary re-renders when other parts of the context change.
23
+ *
24
+ * 3. **`useEnsemble(initialContext, factories, getDiscriminant)`**:
25
+ * - **Best for:** Complex state, shared state, or integrating with external logic.
26
+ * - **Returns:** A stable `Ensemble` instance.
27
+ * - The most powerful hook. It uses the `Ensemble` pattern to decouple your
28
+ * pure machine logic from React's state management, making your business
29
+ * logic portable and easy to test.
30
+ *
31
+ * 4. **`createMachineContext()`**:
32
+ * - **Best for:** Avoiding prop-drilling.
33
+ * - **Returns:** A `Provider` and consumer hooks (`useContext`, `useSelector`, etc.).
34
+ * - A utility to provide a machine created with `useMachine` or `useEnsemble` to
35
+ * the entire component tree below it.
36
+ *
37
+ * 5. **`useActor(actor)`**:
38
+ * - **Best for:** Using the Actor model.
39
+ * - **Returns:** The current machine snapshot.
40
+ */
41
+ import { type ReactNode } from 'react';
42
+ import { Machine, runMachine, type Ensemble, type Actor, BaseMachine } from './index';
43
+ export type Runner<M extends Machine<any>> = ReturnType<typeof runMachine<M>>;
44
+ /**
45
+ * A React hook for using a self-contained, immutable state machine within a component.
46
+ * It provides a more ergonomic API than a raw dispatcher by returning a stable `actions`
47
+ * object, similar to the `runMachine` primitive.
48
+ *
49
+ * This is the ideal hook for managing component-level state.
50
+ *
51
+ * @template M - The machine type (can be a union of states).
52
+ * @param machineFactory - A function that creates the initial machine instance.
53
+ * This function is called only once on the initial render.
54
+ * @returns A tuple of `[machine, actions]`, where:
55
+ * - `machine`: The current, reactive machine instance. Its identity changes on
56
+ * every transition, triggering re-renders. Use this for reading state and
57
+ * for type-narrowing.
58
+ * - `actions`: A stable object containing all possible transition methods,
59
+ * pre-bound to update the machine's state.
60
+ */
61
+ export declare function useMachine<M extends Machine<any>>(machineFactory: () => M): [M, Record<string, (...args: any[]) => void>];
62
+ /**
63
+ * A hook that subscribes a component to a selected slice of a machine's state.
64
+ *
65
+ * This is a critical performance optimization. It prevents a component from
66
+ * re-rendering if only an irrelevant part of the machine's context has changed.
67
+ * The component will only re-render if the value returned by the `selector` function
68
+ * is different from the previous render.
69
+ *
70
+ * @template M - The machine type.
71
+ * @template T - The type of the selected value.
72
+ * @param machine - The reactive machine instance from `useMachine`.
73
+ * @param selector - A function that takes the current machine state and returns
74
+ * a derived value.
75
+ * @param isEqual - An optional function to compare the previous and next selected
76
+ * values. Defaults to `Object.is` for strict equality checking. Provide your own
77
+ * for deep comparisons of objects or arrays.
78
+ * @returns The selected, memoized value from the machine's state.
79
+ */
80
+ export declare function useMachineSelector<M extends Machine<any>, T>(machine: M, selector: (state: M) => T, isEqual?: (a: T, b: T) => boolean): T;
81
+ /**
82
+ * A hook that creates and manages an `Ensemble` within a React component.
83
+ *
84
+ * This is the most powerful and flexible integration pattern. It decouples your
85
+ * state logic (defined in `factories`) from React's state management. Your machine
86
+ * logic becomes pure, portable, and easily testable outside of React.
87
+ *
88
+ * @template C - The shared context object type.
89
+ * @template F - An object of factory functions that create machine instances.
90
+ * @param initialContext - The initial context object for the machine.
91
+ * @param factories - An object mapping state names to factory functions.
92
+ * @param getDiscriminant - An accessor function that determines the current state
93
+ * from the context.
94
+ * @returns A stable `Ensemble` instance. The component will reactively update
95
+ * when the ensemble's underlying context changes.
96
+ */
97
+ export declare function useEnsemble<C extends object, F extends Record<string, (context: C) => Machine<C>>>(initialContext: C, factories: F, getDiscriminant: (context: C) => keyof F): Ensemble<ReturnType<F[keyof F]>, C>;
98
+ /**
99
+ * Creates a React Context for providing a machine instance down the component tree,
100
+ * avoiding the need to pass it down as props ("prop-drilling").
101
+ *
102
+ * It returns a `Provider` component and a suite of consumer hooks for accessing
103
+ * the state and actions.
104
+ */
105
+ export declare function createMachineContext<M extends Machine<any>>(): {
106
+ Provider: ({ machine, actions, children, }: {
107
+ machine: M;
108
+ actions: Record<string, (...args: any[]) => void>;
109
+ children: ReactNode;
110
+ }) => import("react").FunctionComponentElement<import("react").ProviderProps<[M, Record<string, (...args: any[]) => void>] | null>>;
111
+ useMachineContext: () => [M, Record<string, (...args: any[]) => void>];
112
+ useMachineState: () => M;
113
+ useMachineActions: () => Record<string, (...args: any[]) => void>;
114
+ useSelector: <T>(selector: (state: M) => T, isEqual?: (a: T, b: T) => boolean) => T;
115
+ };
116
+ /**
117
+ * Subscribes to an Actor and returns the current snapshot.
118
+ * Uses `useSyncExternalStore` for concurrent features compatibility.
119
+ *
120
+ * @param actor The actor instance to subscribe to.
121
+ * @returns The current machine snapshot.
122
+ */
123
+ export declare function useActor<M extends BaseMachine<any>>(actor: Actor<M>): M;
124
+ /**
125
+ * Subscribes to an Actor and selects a slice of the state.
126
+ * Only re-renders when the selected slice changes.
127
+ *
128
+ * @param actor The actor instance.
129
+ * @param selector Function to select a part of the state.
130
+ * @param isEqual Optional equality function.
131
+ */
132
+ export declare function useActorSelector<M extends BaseMachine<any>, T>(actor: Actor<M>, selector: (state: M) => T, isEqual?: (a: T, b: T) => boolean): T;
133
+ //# sourceMappingURL=react.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react.d.ts","sourceRoot":"","sources":["../../src/react.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,EASL,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAEf,OAAO,EACL,OAAO,EACP,UAAU,EAEV,KAAK,QAAQ,EAEb,KAAK,KAAK,EACV,WAAW,EACZ,MAAM,SAAS,CAAC;AAEjB,MAAM,MAAM,MAAM,CAAC,CAAC,SAAS,OAAO,CAAC,GAAG,CAAC,IAAI,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;AAM9E;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,OAAO,CAAC,GAAG,CAAC,EAC/C,cAAc,EAAE,MAAM,CAAC,GACtB,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC,CAAC,CAwB/C;AAMD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,EAC1D,OAAO,EAAE,CAAC,EACV,QAAQ,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,EACzB,OAAO,GAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,OAAmB,GAC3C,CAAC,CAmBH;AAMD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CACzB,CAAC,SAAS,MAAM,EAChB,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,EAEpD,cAAc,EAAE,CAAC,EACjB,SAAS,EAAE,CAAC,EACZ,eAAe,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,MAAM,CAAC,GACvC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAyBrC;AAMD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,OAAO,CAAC,GAAG,CAAC;gDAQtD;QACD,OAAO,EAAE,CAAC,CAAC;QACX,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC,CAAC;QAClD,QAAQ,EAAE,SAAS,CAAC;KACrB,yGAXuD,GAAG,EAAE,KAAK,IAAI;0DAAd,GAAG,EAAE,KAAK,IAAI;2BAyB1C,CAAC;6BACC,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;kBAEjD,CAAC,YACV,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,YACf,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,OAAO,KAChC,CAAC;EAYL;AAMD;;;;;;GAMG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,WAAW,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAMvE;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,WAAW,CAAC,GAAG,CAAC,EAAE,CAAC,EAC5D,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,EACf,QAAQ,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,EACzB,OAAO,GAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,OAAmB,GAC3C,CAAC,CAgCH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@doeixd/machine",
3
- "version": "0.0.22",
3
+ "version": "0.0.23",
4
4
  "files": [
5
5
  "dist",
6
6
  "src"
@@ -124,6 +124,15 @@
124
124
  },
125
125
  "require": "./dist/cjs/production/extract.js",
126
126
  "import": "./dist/esm/production/extract.js"
127
+ },
128
+ "./react": {
129
+ "types": "./dist/types/entry-react.d.ts",
130
+ "development": {
131
+ "require": "./dist/cjs/development/react.js",
132
+ "import": "./dist/esm/development/react.js"
133
+ },
134
+ "require": "./dist/cjs/production/react.js",
135
+ "import": "./dist/esm/production/react.js"
127
136
  }
128
137
  },
129
138
  "typesVersions": {
@@ -133,6 +142,9 @@
133
142
  ],
134
143
  "extract": [
135
144
  "./dist/types/extract.d.ts"
145
+ ],
146
+ "react": [
147
+ "./dist/types/entry-react.d.ts"
136
148
  ]
137
149
  }
138
150
  },