@alwatr/fsm 9.1.1 → 9.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +2 -2
- package/dist/main.js.map +1 -1
- package/package.json +4 -4
package/dist/main.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/* 📦 @alwatr/fsm v9.
|
|
1
|
+
/* 📦 @alwatr/fsm v9.2.1 */
|
|
2
2
|
import{createPersistentStateSignal as D,createStateSignal as V}from"@alwatr/signal";import{createLogger as k}from"@alwatr/logger";import{createEventSignal as P}from"@alwatr/signal";class Z{config_;stateSignal__;logger_;eventSignal;stateSignal;constructor(q,z){this.config_=q;this.stateSignal__=z;this.logger_=k(`fsm:${this.config_.name}`),this.logger_.logMethodArgs?.("constructor",q),this.stateSignal=this.stateSignal__.asReadonly(),this.eventSignal=P({name:`fsm-event-${this.config_.name}`}),this.eventSignal.subscribe(this.processTransition__.bind(this),{receivePrevious:!1})}async processTransition__(q){let z=this.stateSignal__.get();this.logger_.logMethodArgs?.("processTransition__",{state:z.name,event:q});let J=this.findTransition__(q,z.context);if(!J){this.logger_.incident?.("processTransition__","ignored_event","No valid transition found for event",{state:z.name,event:q});return}let W=J.target??z.name;if(W!==z.name)this.executeEffects__(q,z.context,this.config_.states[z.name]?.exit);let K=this.applyAssigners__(q,z.context,J.assigners),Q={name:W,context:K};if(this.stateSignal__.set(Q),Q.name!==z.name)this.executeEffects__(q,Q.context,this.config_.states[Q.name]?.entry)}findTransition__(q,z){this.logger_.logMethod?.("findTransition__");let J=this.stateSignal__.get().name,K=this.config_.states[J]?.on?.[q.type];if(!K)return;return(Array.isArray(K)?K:[K]).find((X,j)=>{if(!X.condition)return!0;try{let Y=X.condition(q,z);return this.logger_.logStep?.("findTransition__","check_condition",{state:J,eventType:q.type,transitionIndex:j,condition:X.condition.name||"anonymous",result:Y}),Y}catch(Y){return this.logger_.error("findTransition__","condition_failed",Y,{state:J,eventType:q.type,transitionIndex:j,condition:X.condition.name||"anonymous"}),!1}})}async executeEffects__(q,z,J){if(!J){this.logger_.logMethodArgs?.("executeEffects__//skipped",{count:0});return}let W=Array.isArray(J)?J:[J];this.logger_.logMethodArgs?.("executeEffects__",{count:W.length});for(let K of W)try{let Q=await K(q,z);if(Q&&"type"in Q)this.logger_.logStep?.("executeEffects__","new_event_from_effect",{effect:K.name||"anonymous",state:this.stateSignal__.get().name,newEvent:Q.type}),this.eventSignal.dispatch(Q)}catch(Q){this.logger_.error("executeEffects__","effect_failed",Q,{effect:K.name||"anonymous",state:this.stateSignal__.get().name,event:q,context:z})}}applyAssigners__(q,z,J){if(!J)return this.logger_.logMethodArgs?.("applyAssigners__//skipped",{count:0}),z;let W=Array.isArray(J)?J:[J];this.logger_.logMethodArgs?.("applyAssigners__",{count:W.length});try{return W.reduce((K,Q)=>{let X=Q(q,K);if(this.logger_.logMethodFull?.(`event.${q.type}.action.${Q.name||"anonymous"}`,{event:q,accContext:K},X),typeof X==="object"&&X!==null)return{...K,...X};return K},z)}catch(K){return this.logger_.error("applyAssigners__","assigner_failed_atomic",K,{event:q,context:z}),z}}destroy(){this.logger_.logMethod?.("destroy"),this.eventSignal.destroy(),this.stateSignal.destroy()}}function F(q){let z={name:q.initial,context:q.context},J=q.persistent?D({name:`fsm-state-${q.name}`,storageKey:q.persistent.storageKey??q.name,initialValue:z,schemaVersion:q.persistent.schemaVersion}):V({name:`fsm-state-${q.name}`,initialValue:z});return new Z(q,J)}export{F as createFsmService,Z as FsmService};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=E5D16A46C1FE275E64756E2164756E21
|
|
5
5
|
//# sourceMappingURL=main.js.map
|
package/dist/main.js.map
CHANGED
|
@@ -6,6 +6,6 @@
|
|
|
6
6
|
"import { createLogger, type AlwatrLogger } from '@alwatr/logger';\nimport { createEventSignal, type StateSignal, type PersistentStateSignal, EventSignal, type IReadonlySignal } from '@alwatr/signal';\n\nimport type { StateMachineConfig, MachineState, MachineEvent, Transition, Effect, Assigner } from './type.js';\n\n/**\n * A generic, encapsulated service that creates, runs, and manages a finite state machine.\n * It handles signal creation, logic connection, and lifecycle management, providing a clean,\n * reactive API for interacting with the FSM.\n *\n * @template TState The union type of all possible state names.\n * @template TEvent The union type of all possible events.\n * @template TContext The type of the machine's context (extended state).\n */\nexport class FsmService<TState extends string, TEvent extends MachineEvent, TContext extends JsonObject> {\n protected readonly logger_: AlwatrLogger;\n\n /** The event signal for sending events to the FSM. */\n public readonly eventSignal: EventSignal<TEvent>;\n\n /** The public, read-only state signal. Subscribe to react to state changes. */\n public readonly stateSignal: IReadonlySignal<MachineState<TState, TContext>>;\n\n constructor(\n protected readonly config_: StateMachineConfig<TState, TEvent, TContext>,\n private readonly stateSignal__: StateSignal<MachineState<TState, TContext>> | PersistentStateSignal<MachineState<TState, TContext>>,\n ) {\n this.logger_ = createLogger(`fsm:${this.config_.name}`);\n this.logger_.logMethodArgs?.('constructor', config_);\n\n this.stateSignal = this.stateSignal__.asReadonly();\n this.eventSignal = createEventSignal<TEvent>({\n name: `fsm-event-${this.config_.name}`,\n });\n this.eventSignal.subscribe(this.processTransition__.bind(this), { receivePrevious: false });\n }\n\n /**\n * The core FSM logic that processes a single event and transitions the machine to a new state.\n * This process is atomic and follows the Run-to-Completion (RTC) model.\n *\n * @param event The event to process.\n */\n private async processTransition__(event: TEvent): Promise<void> {\n const currentState = this.stateSignal__.get();\n this.logger_.logMethodArgs?.('processTransition__', { state: currentState.name, event });\n\n const transition = this.findTransition__(event, currentState.context);\n\n if (!transition) {\n this.logger_.incident?.('processTransition__', 'ignored_event', 'No valid transition found for event', {\n state: currentState.name,\n event,\n });\n return; // Event ignored, no transition occurs.\n }\n\n const targetStateName = transition.target ?? currentState.name;\n\n // 1. Execute exit effects of the current state if transitioning to a new state.\n if (targetStateName !== currentState.name) {\n void this.executeEffects__(event, currentState.context, this.config_.states[currentState.name]?.exit);\n }\n\n // 2. Apply assigners to compute the next context. This is a pure function.\n const nextContext = this.applyAssigners__(event, currentState.context, transition.assigners);\n\n // 3. Create the final next state object.\n const nextState: MachineState<TState, TContext> = {\n name: targetStateName,\n context: nextContext,\n };\n\n // 4. Set the new state, notifying all subscribers.\n this.stateSignal__.set(nextState);\n\n // 5. Execute entry effects of the new state if a transition occurred.\n if (nextState.name !== currentState.name) {\n void this.executeEffects__(event, nextState.context, this.config_.states[nextState.name]?.entry);\n }\n }\n\n /**\n * Finds the first valid transition for the given event and context by evaluating conditions.\n *\n * @param event The triggering event.\n * @param context The current machine context.\n * @returns The first matching transition or `undefined` if none are found.\n */\n private findTransition__(event: TEvent, context: Readonly<TContext>): Transition<TState, TEvent, TContext> | undefined {\n this.logger_.logMethod?.('findTransition__');\n\n const currentStateName = this.stateSignal__.get().name;\n const currentStateConfig = this.config_.states[currentStateName];\n const transitions = currentStateConfig?.on?.[event.type as TEvent['type']] as\n | SingleOrArray<Transition<TState, TEvent, TContext>>\n | undefined;\n\n if (!transitions) return undefined;\n\n // Normalize to an array to handle both single and multiple transitions uniformly.\n const transitionsArray = Array.isArray(transitions) ? transitions : [transitions];\n\n return transitionsArray.find((transition, index) => {\n if (!transition.condition) return true; // A transition without a condition is always valid.\n\n try {\n const conditionMet = transition.condition(event, context);\n this.logger_.logStep?.('findTransition__', 'check_condition', {\n state: currentStateName,\n eventType: event.type,\n transitionIndex: index,\n condition: transition.condition.name || 'anonymous',\n result: conditionMet,\n });\n return conditionMet;\n }\n catch (error) {\n this.logger_.error('findTransition__', 'condition_failed', error, {\n state: currentStateName,\n eventType: event.type,\n transitionIndex: index,\n condition: transition.condition.name || 'anonymous',\n });\n return false; // Treat a failing condition as not met.\n }\n });\n }\n\n /**\n * Sequentially executes a list of effects (side-effects).\n * Errors are caught and logged without stopping the FSM.\n *\n * @param event The event that triggered these effects.\n * @param context The context at the time of execution.\n * @param effects A single effect or an array of effects.\n */\n private async executeEffects__(\n event: TEvent,\n context: Readonly<TContext>,\n effects?: SingleOrArray<Effect<TEvent, TContext>>,\n ): Promise<void> {\n if (!effects) {\n this.logger_.logMethodArgs?.('executeEffects__//skipped', { count: 0 });\n return;\n }\n const effectsArray: Effect<TEvent, TContext>[] = Array.isArray(effects) ? effects : [effects];\n\n this.logger_.logMethodArgs?.('executeEffects__', { count: effectsArray.length });\n\n for (const effect of effectsArray) {\n try {\n const result = await effect(event, context);\n // If an effect returns a new event, dispatch it to be processed next.\n if (result && 'type' in result) {\n this.logger_.logStep?.('executeEffects__', 'new_event_from_effect', {\n effect: effect.name || 'anonymous',\n state: this.stateSignal__.get().name,\n newEvent: result.type,\n });\n this.eventSignal.dispatch(result);\n }\n }\n catch (error) {\n this.logger_.error('executeEffects__', 'effect_failed', error, {\n effect: effect.name || 'anonymous',\n state: this.stateSignal__.get().name,\n event,\n context,\n });\n }\n }\n }\n\n /**\n * Applies all assigner functions to the context to produce a new, updated context.\n * This process is atomic (all-or-nothing). If any assigner fails, the original\n * context is returned, and all updates are discarded.\n *\n * @param event The event that triggered the transition.\n * @param context The current context.\n * @param assigners A single assigner or an array of assigners.\n * @returns The new, updated context, or the original context if any assigner fails.\n */\n private applyAssigners__(event: TEvent, context: Readonly<TContext>, assigners?: SingleOrArray<Assigner<TEvent, TContext>>): TContext {\n if (!assigners) {\n this.logger_.logMethodArgs?.('applyAssigners__//skipped', { count: 0 });\n return context;\n }\n\n const assignersArray: Assigner<TEvent, TContext>[] = Array.isArray(assigners) ? assigners : [assigners];\n\n this.logger_.logMethodArgs?.('applyAssigners__', { count: assignersArray.length });\n\n try {\n // The entire reduce operation is wrapped in a single try/catch block\n // to ensure atomic updates.\n return assignersArray.reduce((accContext, assigner) => {\n const partialUpdate = assigner(event, accContext);\n this.logger_.logMethodFull?.(`event.${event.type}.action.${assigner.name || 'anonymous'}`, { event, accContext }, partialUpdate);\n if (typeof partialUpdate === 'object' && partialUpdate !== null) {\n // The next assigner receives the updated context from the previous one.\n return { ...accContext, ...partialUpdate };\n }\n // If an assigner returns nothing, pass the accumulated context along.\n return accContext;\n }, context);\n }\n catch (error) {\n this.logger_.error('applyAssigners__', 'assigner_failed_atomic', error, {\n event,\n context, // Log the original context for debugging.\n });\n // On ANY failure, discard all changes and return the original context.\n return context;\n }\n }\n\n /**\n * Destroys the service, cleaning up all internal signals and subscriptions\n * to prevent memory leaks.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n this.eventSignal.destroy();\n this.stateSignal.destroy();\n }\n}\n"
|
|
7
7
|
],
|
|
8
8
|
"mappings": ";AAAA,sCAAQ,uBAA6B,uBCArC,uBAAS,uBACT,4BAAS,uBAaF,MAAM,CAA4F,CAUlF,QACF,cAVA,QAGH,YAGA,YAEhB,WAAW,CACU,EACF,EACjB,CAFmB,eACF,qBAEjB,KAAK,QAAU,EAAa,OAAO,KAAK,QAAQ,MAAM,EACtD,KAAK,QAAQ,gBAAgB,cAAe,CAAO,EAEnD,KAAK,YAAc,KAAK,cAAc,WAAW,EACjD,KAAK,YAAc,EAA0B,CAC3C,KAAM,aAAa,KAAK,QAAQ,MAClC,CAAC,EACD,KAAK,YAAY,UAAU,KAAK,oBAAoB,KAAK,IAAI,EAAG,CAAE,gBAAiB,EAAM,CAAC,OAS9E,oBAAmB,CAAC,EAA8B,CAC9D,IAAM,EAAe,KAAK,cAAc,IAAI,EAC5C,KAAK,QAAQ,gBAAgB,sBAAuB,CAAE,MAAO,EAAa,KAAM,OAAM,CAAC,EAEvF,IAAM,EAAa,KAAK,iBAAiB,EAAO,EAAa,OAAO,EAEpE,GAAI,CAAC,EAAY,CACf,KAAK,QAAQ,WAAW,sBAAuB,gBAAiB,sCAAuC,CACrG,MAAO,EAAa,KACpB,OACF,CAAC,EACD,OAGF,IAAM,EAAkB,EAAW,QAAU,EAAa,KAG1D,GAAI,IAAoB,EAAa,KAC9B,KAAK,iBAAiB,EAAO,EAAa,QAAS,KAAK,QAAQ,OAAO,EAAa,OAAO,IAAI,EAItG,IAAM,EAAc,KAAK,iBAAiB,EAAO,EAAa,QAAS,EAA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AO,WAAW,YAAc,EAAO,KACnD,eACA,cAAe,EAAO,WAAW,aACnC,CAAC,EACC,EAAkD,CAClD,KAAM,aAAa,EAAO,OAC1B,aAAc,CAChB,CAAC,EAEH,OAAO,IAAI,EAAW,EAAQ,CAAW",
|
|
9
|
-
"debugId": "
|
|
9
|
+
"debugId": "E5D16A46C1FE275E64756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/fsm",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.2.1",
|
|
4
4
|
"description": "A tiny, type-safe, declarative, and reactive finite state machine (FSM) library for modern TypeScript applications, built on top of Alwatr Signals.",
|
|
5
5
|
"license": "MPL-2.0",
|
|
6
6
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com> (https://ali.mihandoost.com)",
|
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
},
|
|
22
22
|
"sideEffects": false,
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@alwatr/logger": "9.
|
|
25
|
-
"@alwatr/signal": "9.
|
|
24
|
+
"@alwatr/logger": "9.2.1",
|
|
25
|
+
"@alwatr/signal": "9.2.1"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@alwatr/nano-build": "9.1.1",
|
|
@@ -65,5 +65,5 @@
|
|
|
65
65
|
"state",
|
|
66
66
|
"typescript"
|
|
67
67
|
],
|
|
68
|
-
"gitHead": "
|
|
68
|
+
"gitHead": "b9dc0cb8b04b16216d44fbe9a9682f2a57926167"
|
|
69
69
|
}
|