@alwatr/fsm 4.1.0 → 6.0.0
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/CHANGELOG.md +115 -0
- package/README.md +274 -63
- package/dist/facade.d.ts +64 -0
- package/dist/facade.d.ts.map +1 -0
- package/dist/fsm-service.d.ts +61 -0
- package/dist/fsm-service.d.ts.map +1 -0
- package/dist/main.cjs +2 -143
- package/dist/main.cjs.map +4 -4
- package/dist/main.d.ts +3 -3
- package/dist/main.d.ts.map +1 -1
- package/dist/main.mjs +2 -116
- package/dist/main.mjs.map +4 -4
- package/dist/type.d.ts +98 -9
- package/dist/type.d.ts.map +1 -1
- package/package.json +10 -10
- package/dist/base.d.ts +0 -47
- package/dist/base.d.ts.map +0 -1
- package/dist/fsm.d.ts +0 -19
- package/dist/fsm.d.ts.map +0 -1
package/dist/main.cjs
CHANGED
|
@@ -1,144 +1,3 @@
|
|
|
1
|
-
/* @alwatr/fsm
|
|
2
|
-
"use strict";
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
-
var __export = (target, all) => {
|
|
8
|
-
for (var name in all)
|
|
9
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
-
};
|
|
11
|
-
var __copyProps = (to, from, except, desc) => {
|
|
12
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
-
for (let key of __getOwnPropNames(from))
|
|
14
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
-
}
|
|
17
|
-
return to;
|
|
18
|
-
};
|
|
19
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
-
|
|
21
|
-
// src/main.ts
|
|
22
|
-
var main_exports = {};
|
|
23
|
-
__export(main_exports, {
|
|
24
|
-
AlwatrFluxStateMachine: () => AlwatrFluxStateMachine,
|
|
25
|
-
AlwatrFluxStateMachineBase: () => AlwatrFluxStateMachineBase
|
|
26
|
-
});
|
|
27
|
-
module.exports = __toCommonJS(main_exports);
|
|
28
|
-
|
|
29
|
-
// src/base.ts
|
|
30
|
-
var import_nanolib = require("@alwatr/nanolib");
|
|
31
|
-
var import_observable = require("@alwatr/observable");
|
|
32
|
-
__dev_mode__: import_nanolib.packageTracer.add("@alwatr/fsm", "4.1.0");
|
|
33
|
-
var AlwatrFluxStateMachineBase = class extends import_observable.AlwatrObservable {
|
|
34
|
-
constructor(config) {
|
|
35
|
-
config.loggerPrefix ??= "flux-state-machine";
|
|
36
|
-
super(config);
|
|
37
|
-
/**
|
|
38
|
-
* States and transitions config.
|
|
39
|
-
*/
|
|
40
|
-
this.stateRecord_ = {};
|
|
41
|
-
/**
|
|
42
|
-
* Bind actions name to class methods
|
|
43
|
-
*/
|
|
44
|
-
this.actionRecord_ = {};
|
|
45
|
-
this.firstResetToInitialState__ = true;
|
|
46
|
-
this.initialState_ = config.initialState;
|
|
47
|
-
this.message_ = { state: this.initialState_ };
|
|
48
|
-
setTimeout(this.resetToInitialState_.bind(this), 0);
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Reset machine to initial state without notify.
|
|
52
|
-
*/
|
|
53
|
-
resetToInitialState_() {
|
|
54
|
-
this.logger_.logMethod?.("resetToInitialState_");
|
|
55
|
-
if (this.firstResetToInitialState__) {
|
|
56
|
-
this.firstResetToInitialState__ = false;
|
|
57
|
-
const eventDetail2 = { from: this.initialState_, event: "reset", to: this.initialState_ };
|
|
58
|
-
this.execAction__(`on_state_${this.initialState_}_enter`, eventDetail2);
|
|
59
|
-
return this.postTransition__(eventDetail2);
|
|
60
|
-
}
|
|
61
|
-
const from = this.message_.state;
|
|
62
|
-
this.message_ = { state: this.initialState_ };
|
|
63
|
-
const eventDetail = { from, event: "reset", to: this.initialState_ };
|
|
64
|
-
return this.postTransition__(eventDetail);
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* Transition condition.
|
|
68
|
-
*/
|
|
69
|
-
shouldTransition_(_eventDetail) {
|
|
70
|
-
this.logger_.logMethodFull?.("shouldTransition_", _eventDetail, true);
|
|
71
|
-
return true;
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* Transition flux state machine instance to new state.
|
|
75
|
-
*/
|
|
76
|
-
async transition_(event) {
|
|
77
|
-
const fromState = this.message_.state;
|
|
78
|
-
const toState = this.stateRecord_[fromState]?.[event];
|
|
79
|
-
this.logger_.logMethodArgs?.("transition_", { fromState, event, toState });
|
|
80
|
-
if (toState == null) {
|
|
81
|
-
this.logger_.incident?.("transition", "invalid_target_state", {
|
|
82
|
-
fromState,
|
|
83
|
-
event
|
|
84
|
-
});
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
const eventDetail = { from: fromState, event, to: toState };
|
|
88
|
-
if (await this.shouldTransition_(eventDetail) !== true) return;
|
|
89
|
-
this.notify_({ state: toState });
|
|
90
|
-
this.postTransition__(eventDetail);
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Execute all actions for current state.
|
|
94
|
-
*/
|
|
95
|
-
async postTransition__(eventDetail) {
|
|
96
|
-
this.logger_.logMethodArgs?.("postTransition__", eventDetail);
|
|
97
|
-
await this.execAction__(`on_event_${eventDetail.event}`, eventDetail);
|
|
98
|
-
if (eventDetail.from !== eventDetail.to) {
|
|
99
|
-
await this.execAction__(`on_any_state_exit`, eventDetail);
|
|
100
|
-
await this.execAction__(`on_state_${eventDetail.from}_exit`, eventDetail);
|
|
101
|
-
await this.execAction__(`on_any_state_enter`, eventDetail);
|
|
102
|
-
await this.execAction__(`on_state_${eventDetail.to}_enter`, eventDetail);
|
|
103
|
-
}
|
|
104
|
-
this.execAction__(`on_state_${eventDetail.from}_event_${eventDetail.event}`, eventDetail);
|
|
105
|
-
}
|
|
106
|
-
/**
|
|
107
|
-
* Execute action name if defined in _actionRecord.
|
|
108
|
-
*/
|
|
109
|
-
execAction__(name, eventDetail) {
|
|
110
|
-
const actionFn = this.actionRecord_[name];
|
|
111
|
-
if (typeof actionFn === "function") {
|
|
112
|
-
this.logger_.logMethodArgs?.("execAction__", name);
|
|
113
|
-
return actionFn.call(this, eventDetail);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
};
|
|
117
|
-
|
|
118
|
-
// src/fsm.ts
|
|
119
|
-
var AlwatrFluxStateMachine = class extends AlwatrFluxStateMachineBase {
|
|
120
|
-
/**
|
|
121
|
-
* Current state.
|
|
122
|
-
*/
|
|
123
|
-
get state() {
|
|
124
|
-
return this.message_.state;
|
|
125
|
-
}
|
|
126
|
-
/**
|
|
127
|
-
* Transition flux state machine instance to new state.
|
|
128
|
-
*/
|
|
129
|
-
transition(event) {
|
|
130
|
-
this.transition_(event);
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* Reset machine to initial state without notify.
|
|
134
|
-
*/
|
|
135
|
-
resetToInitialState() {
|
|
136
|
-
this.resetToInitialState_();
|
|
137
|
-
}
|
|
138
|
-
};
|
|
139
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
140
|
-
0 && (module.exports = {
|
|
141
|
-
AlwatrFluxStateMachine,
|
|
142
|
-
AlwatrFluxStateMachineBase
|
|
143
|
-
});
|
|
1
|
+
/* @alwatr/fsm v6.0.0 */
|
|
2
|
+
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var main_exports={};__export(main_exports,{FsmService:()=>FsmService,createFsmService:()=>createFsmService});module.exports=__toCommonJS(main_exports);var import_logger=require("@alwatr/logger");var import_signal=require("@alwatr/signal");var FsmService=class{constructor(config_){this.config_=config_;this.logger_=(0,import_logger.createLogger)(`fsm:${this.config_.name}`);this.eventSignal=(0,import_signal.createEventSignal)({name:`fsm-event-${this.config_.name}`});this.stateSignal__=(0,import_signal.createStateSignal)({name:`fsm-state-${this.config_.name}`,initialValue:{name:this.config_.initial,context:this.config_.context}});this.stateSignal=this.stateSignal__.asReadonly();this.logger_.logMethodArgs?.("constructor",config_);this.eventSignal.subscribe(this.processTransition__.bind(this),{receivePrevious:false})}async processTransition__(event){const currentState=this.stateSignal__.get();this.logger_.logMethodArgs?.("processTransition__",{state:currentState.name,event});const transition=this.findTransition__(event,currentState.context);if(!transition){this.logger_.incident?.("processTransition__","ignored_event","No valid transition found for event",{state:currentState.name,event});return}const targetStateName=transition.target??currentState.name;if(targetStateName!==currentState.name){void this.executeEffects__(event,currentState.context,this.config_.states[currentState.name]?.exit)}const nextContext=this.applyAssigners__(event,currentState.context,transition.assigners);const nextState={name:targetStateName,context:nextContext};this.stateSignal__.set(nextState);if(nextState.name!==currentState.name){void this.executeEffects__(event,nextState.context,this.config_.states[nextState.name]?.entry)}}findTransition__(event,context){this.logger_.logMethod?.("findTransition__");const currentStateName=this.stateSignal__.get().name;const currentStateConfig=this.config_.states[currentStateName];const transitions=currentStateConfig?.on?.[event.type];if(!transitions)return void 0;const transitionsArray=Array.isArray(transitions)?transitions:[transitions];return transitionsArray.find((transition,index)=>{if(!transition.condition)return true;try{const conditionMet=transition.condition(event,context);this.logger_.logStep?.("findTransition__","check_condition",{state:currentStateName,eventType:event.type,transitionIndex:index,condition:transition.condition.name||"anonymous",result:conditionMet});return conditionMet}catch(error){this.logger_.error("findTransition__","condition_failed",error,{state:currentStateName,eventType:event.type,transitionIndex:index,condition:transition.condition.name||"anonymous"});return false}})}async executeEffects__(event,context,effects){if(!effects){this.logger_.logMethodArgs?.("executeEffects__//skipped",{count:0});return}const effectsArray=Array.isArray(effects)?effects:[effects];this.logger_.logMethodArgs?.("executeEffects__",{count:effectsArray.length});for(const effect of effectsArray){try{const result=await effect(event,context);if(result&&"type"in result){this.logger_.logStep?.("executeEffects__","new_event_from_effect",{effect:effect.name||"anonymous",state:this.stateSignal__.get().name,newEvent:result.type});this.eventSignal.dispatch(result)}}catch(error){this.logger_.error("executeEffects__","effect_failed",error,{effect:effect.name||"anonymous",state:this.stateSignal__.get().name,event,context})}}}applyAssigners__(event,context,assigners){if(!assigners){this.logger_.logMethodArgs?.("applyAssigners__//skipped",{count:0});return context}const assignersArray=Array.isArray(assigners)?assigners:[assigners];this.logger_.logMethodArgs?.("applyAssigners__",{count:assignersArray.length});try{return assignersArray.reduce((accContext,assigner)=>{const partialUpdate=assigner(event,accContext);this.logger_.logMethodFull?.(`event.${event.type}.action.${assigner.name||"anonymous"}`,{event,accContext},partialUpdate);if(typeof partialUpdate==="object"&&partialUpdate!==null){return{...accContext,...partialUpdate}}return accContext},context)}catch(error){this.logger_.error("applyAssigners__","assigner_failed_atomic",error,{event,context});return context}}destroy(){this.logger_.logMethod?.("destroy");this.eventSignal.destroy();this.stateSignal.destroy()}};function createFsmService(config){return new FsmService(config)}0&&(module.exports={FsmService,createFsmService});
|
|
144
3
|
//# sourceMappingURL=main.cjs.map
|
package/dist/main.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/main.ts", "../src/
|
|
4
|
-
"sourcesContent": ["export * from './base.js';\nexport * from './fsm.js';\nexport * from './type.js';\n", "import {packageTracer} from '@alwatr/nanolib';\nimport {AlwatrObservable, type AlwatrObservableConfig} from '@alwatr/observable';\n\nimport type {ActionName, ActionRecord, StateEventDetail, StateRecord} from './type.js';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport interface AlwatrFluxStateMachineConfig<S extends string> extends AlwatrObservableConfig {\n initialState: S;\n}\n\n/**\n * Flux (Finite) State Machine Base Class\n */\nexport abstract class AlwatrFluxStateMachineBase<S extends string, E extends string> extends AlwatrObservable<{state: S}> {\n /**\n * States and transitions config.\n */\n protected stateRecord_: StateRecord<S, E> = {};\n\n /**\n * Bind actions name to class methods\n */\n protected actionRecord_: ActionRecord<S, E> = {};\n\n protected initialState_: S;\n\n protected override message_: {state: S};\n\n constructor(config: AlwatrFluxStateMachineConfig<S>) {\n config.loggerPrefix ??= 'flux-state-machine';\n super(config);\n\n this.initialState_ = config.initialState;\n this.message_ = {state: this.initialState_};\n setTimeout(this.resetToInitialState_.bind(this), 0);\n }\n\n private firstResetToInitialState__ = true;\n /**\n * Reset machine to initial state without notify.\n */\n protected resetToInitialState_(): Promise<void> {\n this.logger_.logMethod?.('resetToInitialState_');\n if (this.firstResetToInitialState__) {\n this.firstResetToInitialState__ = false;\n const eventDetail: StateEventDetail<S, E> = {from: this.initialState_, event: 'reset', to: this.initialState_};\n this.execAction__(`on_state_${this.initialState_}_enter`, eventDetail);\n return this.postTransition__(eventDetail);\n }\n // else {\n const from = this.message_.state;\n this.message_ = {state: this.initialState_};\n const eventDetail: StateEventDetail<S, E> = {from, event: 'reset', to: this.initialState_};\n return this.postTransition__(eventDetail);\n }\n\n /**\n * Transition condition.\n */\n protected shouldTransition_(_eventDetail: StateEventDetail<S, E>): Awaitable<boolean> {\n this.logger_.logMethodFull?.('shouldTransition_', _eventDetail, true);\n return true;\n }\n\n /**\n * Transition flux state machine instance to new state.\n */\n protected async transition_(event: E): Promise<void> {\n const fromState = this.message_.state;\n const toState = this.stateRecord_[fromState]?.[event];\n\n this.logger_.logMethodArgs?.('transition_', {fromState, event, toState});\n\n if (toState == null) {\n this.logger_.incident?.('transition', 'invalid_target_state', {\n fromState,\n event,\n });\n return;\n }\n\n const eventDetail: StateEventDetail<S, E> = {from: fromState, event, to: toState};\n\n if ((await this.shouldTransition_(eventDetail)) !== true) return;\n\n this.notify_({state: toState}); // message update but notify event delayed after execActions.\n\n this.postTransition__(eventDetail);\n }\n\n /**\n * Execute all actions for current state.\n */\n private async postTransition__(eventDetail: StateEventDetail<S, E>): Promise<void> {\n this.logger_.logMethodArgs?.('postTransition__', eventDetail);\n\n await this.execAction__(`on_event_${eventDetail.event}`, eventDetail);\n\n if (eventDetail.from !== eventDetail.to) {\n await this.execAction__(`on_any_state_exit`, eventDetail);\n await this.execAction__(`on_state_${eventDetail.from}_exit`, eventDetail);\n await this.execAction__(`on_any_state_enter`, eventDetail);\n await this.execAction__(`on_state_${eventDetail.to}_enter`, eventDetail);\n }\n\n this.execAction__(`on_state_${eventDetail.from}_event_${eventDetail.event}`, eventDetail);\n }\n\n /**\n * Execute action name if defined in _actionRecord.\n */\n private execAction__(name: ActionName<S, E | 'reset'>, eventDetail: StateEventDetail<S, E>): Awaitable<void> {\n const actionFn = this.actionRecord_[name];\n if (typeof actionFn === 'function') {\n this.logger_.logMethodArgs?.('execAction__', name);\n return actionFn.call(this, eventDetail);\n }\n }\n}\n", "import {AlwatrFluxStateMachineBase} from './base.js';\n\n/**\n * Flux (Finite) State Machine Base Class\n */\nexport abstract class AlwatrFluxStateMachine<S extends string, E extends string> extends AlwatrFluxStateMachineBase<S, E> {\n /**\n * Current state.\n */\n get state(): S {\n return this.message_.state;\n }\n\n /**\n * Transition flux state machine instance to new state.\n */\n transition(event: E): void {\n this.transition_(event);\n }\n\n /**\n * Reset machine to initial state without notify.\n */\n resetToInitialState(): void {\n this.resetToInitialState_();\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": [
|
|
3
|
+
"sources": ["../src/main.ts", "../src/fsm-service.ts", "../src/facade.ts"],
|
|
4
|
+
"sourcesContent": ["export * from './facade.js';\nexport * from './fsm-service.js';\nexport type * from './type.js';\n", "import {createLogger} from '@alwatr/logger';\nimport {createStateSignal, createEventSignal} 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 Record<string, unknown>> {\n protected readonly logger_ = createLogger(`fsm:${this.config_.name}`);\n\n /** The event signal for sending events to the FSM. */\n public readonly eventSignal = createEventSignal<TEvent>({\n name: `fsm-event-${this.config_.name}`,\n });\n\n private readonly stateSignal__ = createStateSignal<MachineState<TState, TContext>>({\n name: `fsm-state-${this.config_.name}`,\n initialValue: {\n name: this.config_.initial,\n context: this.config_.context,\n },\n });\n\n /** The public, read-only state signal. Subscribe to react to state changes. */\n public readonly stateSignal = this.stateSignal__.asReadonly();\n\n public constructor(protected readonly config_: StateMachineConfig<TState, TEvent, TContext>) {\n this.logger_.logMethodArgs?.('constructor', config_);\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", "import {FsmService} from './fsm-service.js';\n\nimport type {MachineEvent, StateMachineConfig} from './type.js';\n\n/**\n * A simple and clean factory function for creating an `FsmService` instance.\n * This is the recommended way to instantiate a new state machine.\n *\n * @template TState - The union type of all possible states.\n * @template TEvent - The union type of all possible events.\n * @template TContext - The type of the machine's context.\n *\n * @param config - The machine's configuration object.\n * @returns A new, ready-to-use instance of `FsmService`.\n *\n * @example\n * ```ts\n * import {createFsmService} from '@alwatr/fsm';\n * import type {StateMachineConfig} from '@alwatr/fsm';\n *\n * // 1. Define types\n * type LightContext = {brightness: number};\n * type LightState = 'on' | 'off';\n * type LightEvent = {type: 'TOGGLE'} | {type: 'SET_BRIGHTNESS'; level: number};\n *\n * // 2. Config the state machine\n * const lightMachineConfig: StateMachineConfig<LightState, LightEvent, LightContext> = {\n * name: 'light-switch',\n * initial: 'off',\n * context: {brightness: 0},\n * states: {\n * off: {\n * on: {\n * TOGGLE: {\n * target: 'on',\n * assigners: [() => ({brightness: 100})],\n * },\n * },\n * },\n * on: {\n * on: {\n * TOGGLE: {target: 'off', assigners: [() => ({brightness: 0})]},\n * SET_BRIGHTNESS: {assigners: [(event) => ({brightness: event.level})]},\n * },\n * },\n * },\n * };\n *\n * // 3. Create the service\n * const lightService = createFsmService(lightMachineConfig);\n *\n * // 4. Use it in your application\n * lightService.stateSignal.subscribe((state) => {\n * console.log(`Light is ${state.name} with brightness ${state.context.brightness}`);\n * });\n *\n * lightService.eventSignal.dispatch({type: 'TOGGLE'}); // Light is on with brightness 100\n *\n * lightService.eventSignal.dispatch({type: 'SET_BRIGHTNESS', level: 50}); // Light is on with brightness 50\n *\n * // 5. Cleanup\n * // lightService.destroy();\n * ```\n */\nexport function createFsmService<TState extends string, TEvent extends MachineEvent, TContext extends Record<string, unknown>>(\n config: StateMachineConfig<TState, TEvent, TContext>,\n): FsmService<TState, TEvent, TContext> {\n return new FsmService(config);\n}\n"],
|
|
5
|
+
"mappings": ";qqBAAA,uJCAA,kBAA2B,0BAC3B,kBAAmD,0BAa5C,IAAM,WAAN,KAA+G,CAmB7G,YAA+B,QAAuD,CAAvD,qBAlBtC,KAAmB,WAAU,4BAAa,OAAO,KAAK,QAAQ,IAAI,EAAE,EAGpE,KAAgB,eAAc,iCAA0B,CACtD,KAAM,aAAa,KAAK,QAAQ,IAAI,EACtC,CAAC,EAED,KAAiB,iBAAgB,iCAAkD,CACjF,KAAM,aAAa,KAAK,QAAQ,IAAI,GACpC,aAAc,CACZ,KAAM,KAAK,QAAQ,QACnB,QAAS,KAAK,QAAQ,OACxB,CACF,CAAC,EAGD,KAAgB,YAAc,KAAK,cAAc,WAAW,EAG1D,KAAK,QAAQ,gBAAgB,cAAe,OAAO,EACnD,KAAK,YAAY,UAAU,KAAK,oBAAoB,KAAK,IAAI,EAAG,CAAC,gBAAiB,KAAK,CAAC,CAC1F,CAQA,MAAc,oBAAoB,MAA8B,CAC9D,MAAM,aAAe,KAAK,cAAc,IAAI,EAC5C,KAAK,QAAQ,gBAAgB,sBAAuB,CAAC,MAAO,aAAa,KAAM,KAAK,CAAC,EAErF,MAAM,WAAa,KAAK,iBAAiB,MAAO,aAAa,OAAO,EAEpE,GAAI,CAAC,WAAY,CACf,KAAK,QAAQ,WAAW,sBAAuB,gBAAiB,sCAAuC,CACrG,MAAO,aAAa,KACpB,KACF,CAAC,EACD,MACF,CAEA,MAAM,gBAAkB,WAAW,QAAU,aAAa,KAG1D,GAAI,kBAAoB,aAAa,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,KAAK,QAAQ,MAAM,mBAAoB,yBAA0B,MAAO,CACtE,MACA,OACF,CAAC,EAED,OAAO,OACT,CACF,CAMO,SAAgB,CACrB,KAAK,QAAQ,YAAY,SAAS,EAClC,KAAK,YAAY,QAAQ,EACzB,KAAK,YAAY,QAAQ,CAC3B,CACF,ECpKO,SAAS,iBACd,OACsC,CACtC,OAAO,IAAI,WAAW,MAAM,CAC9B",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|
package/dist/main.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export * from './
|
|
2
|
-
export * from './fsm.js';
|
|
3
|
-
export * from './type.js';
|
|
1
|
+
export * from './facade.js';
|
|
2
|
+
export * from './fsm-service.js';
|
|
3
|
+
export type * from './type.js';
|
|
4
4
|
//# sourceMappingURL=main.d.ts.map
|
package/dist/main.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,cAAc,
|
|
1
|
+
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,mBAAmB,WAAW,CAAC"}
|
package/dist/main.mjs
CHANGED
|
@@ -1,117 +1,3 @@
|
|
|
1
|
-
/* @alwatr/fsm
|
|
2
|
-
|
|
3
|
-
// src/base.ts
|
|
4
|
-
import { packageTracer } from "@alwatr/nanolib";
|
|
5
|
-
import { AlwatrObservable } from "@alwatr/observable";
|
|
6
|
-
__dev_mode__: packageTracer.add("@alwatr/fsm", "4.1.0");
|
|
7
|
-
var AlwatrFluxStateMachineBase = class extends AlwatrObservable {
|
|
8
|
-
constructor(config) {
|
|
9
|
-
config.loggerPrefix ??= "flux-state-machine";
|
|
10
|
-
super(config);
|
|
11
|
-
/**
|
|
12
|
-
* States and transitions config.
|
|
13
|
-
*/
|
|
14
|
-
this.stateRecord_ = {};
|
|
15
|
-
/**
|
|
16
|
-
* Bind actions name to class methods
|
|
17
|
-
*/
|
|
18
|
-
this.actionRecord_ = {};
|
|
19
|
-
this.firstResetToInitialState__ = true;
|
|
20
|
-
this.initialState_ = config.initialState;
|
|
21
|
-
this.message_ = { state: this.initialState_ };
|
|
22
|
-
setTimeout(this.resetToInitialState_.bind(this), 0);
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Reset machine to initial state without notify.
|
|
26
|
-
*/
|
|
27
|
-
resetToInitialState_() {
|
|
28
|
-
this.logger_.logMethod?.("resetToInitialState_");
|
|
29
|
-
if (this.firstResetToInitialState__) {
|
|
30
|
-
this.firstResetToInitialState__ = false;
|
|
31
|
-
const eventDetail2 = { from: this.initialState_, event: "reset", to: this.initialState_ };
|
|
32
|
-
this.execAction__(`on_state_${this.initialState_}_enter`, eventDetail2);
|
|
33
|
-
return this.postTransition__(eventDetail2);
|
|
34
|
-
}
|
|
35
|
-
const from = this.message_.state;
|
|
36
|
-
this.message_ = { state: this.initialState_ };
|
|
37
|
-
const eventDetail = { from, event: "reset", to: this.initialState_ };
|
|
38
|
-
return this.postTransition__(eventDetail);
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Transition condition.
|
|
42
|
-
*/
|
|
43
|
-
shouldTransition_(_eventDetail) {
|
|
44
|
-
this.logger_.logMethodFull?.("shouldTransition_", _eventDetail, true);
|
|
45
|
-
return true;
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Transition flux state machine instance to new state.
|
|
49
|
-
*/
|
|
50
|
-
async transition_(event) {
|
|
51
|
-
const fromState = this.message_.state;
|
|
52
|
-
const toState = this.stateRecord_[fromState]?.[event];
|
|
53
|
-
this.logger_.logMethodArgs?.("transition_", { fromState, event, toState });
|
|
54
|
-
if (toState == null) {
|
|
55
|
-
this.logger_.incident?.("transition", "invalid_target_state", {
|
|
56
|
-
fromState,
|
|
57
|
-
event
|
|
58
|
-
});
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
const eventDetail = { from: fromState, event, to: toState };
|
|
62
|
-
if (await this.shouldTransition_(eventDetail) !== true) return;
|
|
63
|
-
this.notify_({ state: toState });
|
|
64
|
-
this.postTransition__(eventDetail);
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* Execute all actions for current state.
|
|
68
|
-
*/
|
|
69
|
-
async postTransition__(eventDetail) {
|
|
70
|
-
this.logger_.logMethodArgs?.("postTransition__", eventDetail);
|
|
71
|
-
await this.execAction__(`on_event_${eventDetail.event}`, eventDetail);
|
|
72
|
-
if (eventDetail.from !== eventDetail.to) {
|
|
73
|
-
await this.execAction__(`on_any_state_exit`, eventDetail);
|
|
74
|
-
await this.execAction__(`on_state_${eventDetail.from}_exit`, eventDetail);
|
|
75
|
-
await this.execAction__(`on_any_state_enter`, eventDetail);
|
|
76
|
-
await this.execAction__(`on_state_${eventDetail.to}_enter`, eventDetail);
|
|
77
|
-
}
|
|
78
|
-
this.execAction__(`on_state_${eventDetail.from}_event_${eventDetail.event}`, eventDetail);
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Execute action name if defined in _actionRecord.
|
|
82
|
-
*/
|
|
83
|
-
execAction__(name, eventDetail) {
|
|
84
|
-
const actionFn = this.actionRecord_[name];
|
|
85
|
-
if (typeof actionFn === "function") {
|
|
86
|
-
this.logger_.logMethodArgs?.("execAction__", name);
|
|
87
|
-
return actionFn.call(this, eventDetail);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
// src/fsm.ts
|
|
93
|
-
var AlwatrFluxStateMachine = class extends AlwatrFluxStateMachineBase {
|
|
94
|
-
/**
|
|
95
|
-
* Current state.
|
|
96
|
-
*/
|
|
97
|
-
get state() {
|
|
98
|
-
return this.message_.state;
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Transition flux state machine instance to new state.
|
|
102
|
-
*/
|
|
103
|
-
transition(event) {
|
|
104
|
-
this.transition_(event);
|
|
105
|
-
}
|
|
106
|
-
/**
|
|
107
|
-
* Reset machine to initial state without notify.
|
|
108
|
-
*/
|
|
109
|
-
resetToInitialState() {
|
|
110
|
-
this.resetToInitialState_();
|
|
111
|
-
}
|
|
112
|
-
};
|
|
113
|
-
export {
|
|
114
|
-
AlwatrFluxStateMachine,
|
|
115
|
-
AlwatrFluxStateMachineBase
|
|
116
|
-
};
|
|
1
|
+
/* @alwatr/fsm v6.0.0 */
|
|
2
|
+
import{createLogger}from"@alwatr/logger";import{createStateSignal,createEventSignal}from"@alwatr/signal";var FsmService=class{constructor(config_){this.config_=config_;this.logger_=createLogger(`fsm:${this.config_.name}`);this.eventSignal=createEventSignal({name:`fsm-event-${this.config_.name}`});this.stateSignal__=createStateSignal({name:`fsm-state-${this.config_.name}`,initialValue:{name:this.config_.initial,context:this.config_.context}});this.stateSignal=this.stateSignal__.asReadonly();this.logger_.logMethodArgs?.("constructor",config_);this.eventSignal.subscribe(this.processTransition__.bind(this),{receivePrevious:false})}async processTransition__(event){const currentState=this.stateSignal__.get();this.logger_.logMethodArgs?.("processTransition__",{state:currentState.name,event});const transition=this.findTransition__(event,currentState.context);if(!transition){this.logger_.incident?.("processTransition__","ignored_event","No valid transition found for event",{state:currentState.name,event});return}const targetStateName=transition.target??currentState.name;if(targetStateName!==currentState.name){void this.executeEffects__(event,currentState.context,this.config_.states[currentState.name]?.exit)}const nextContext=this.applyAssigners__(event,currentState.context,transition.assigners);const nextState={name:targetStateName,context:nextContext};this.stateSignal__.set(nextState);if(nextState.name!==currentState.name){void this.executeEffects__(event,nextState.context,this.config_.states[nextState.name]?.entry)}}findTransition__(event,context){this.logger_.logMethod?.("findTransition__");const currentStateName=this.stateSignal__.get().name;const currentStateConfig=this.config_.states[currentStateName];const transitions=currentStateConfig?.on?.[event.type];if(!transitions)return void 0;const transitionsArray=Array.isArray(transitions)?transitions:[transitions];return transitionsArray.find((transition,index)=>{if(!transition.condition)return true;try{const conditionMet=transition.condition(event,context);this.logger_.logStep?.("findTransition__","check_condition",{state:currentStateName,eventType:event.type,transitionIndex:index,condition:transition.condition.name||"anonymous",result:conditionMet});return conditionMet}catch(error){this.logger_.error("findTransition__","condition_failed",error,{state:currentStateName,eventType:event.type,transitionIndex:index,condition:transition.condition.name||"anonymous"});return false}})}async executeEffects__(event,context,effects){if(!effects){this.logger_.logMethodArgs?.("executeEffects__//skipped",{count:0});return}const effectsArray=Array.isArray(effects)?effects:[effects];this.logger_.logMethodArgs?.("executeEffects__",{count:effectsArray.length});for(const effect of effectsArray){try{const result=await effect(event,context);if(result&&"type"in result){this.logger_.logStep?.("executeEffects__","new_event_from_effect",{effect:effect.name||"anonymous",state:this.stateSignal__.get().name,newEvent:result.type});this.eventSignal.dispatch(result)}}catch(error){this.logger_.error("executeEffects__","effect_failed",error,{effect:effect.name||"anonymous",state:this.stateSignal__.get().name,event,context})}}}applyAssigners__(event,context,assigners){if(!assigners){this.logger_.logMethodArgs?.("applyAssigners__//skipped",{count:0});return context}const assignersArray=Array.isArray(assigners)?assigners:[assigners];this.logger_.logMethodArgs?.("applyAssigners__",{count:assignersArray.length});try{return assignersArray.reduce((accContext,assigner)=>{const partialUpdate=assigner(event,accContext);this.logger_.logMethodFull?.(`event.${event.type}.action.${assigner.name||"anonymous"}`,{event,accContext},partialUpdate);if(typeof partialUpdate==="object"&&partialUpdate!==null){return{...accContext,...partialUpdate}}return accContext},context)}catch(error){this.logger_.error("applyAssigners__","assigner_failed_atomic",error,{event,context});return context}}destroy(){this.logger_.logMethod?.("destroy");this.eventSignal.destroy();this.stateSignal.destroy()}};function createFsmService(config){return new FsmService(config)}export{FsmService,createFsmService};
|
|
117
3
|
//# sourceMappingURL=main.mjs.map
|
package/dist/main.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/
|
|
4
|
-
"sourcesContent": ["import {packageTracer} from '@alwatr/nanolib';\nimport {AlwatrObservable, type AlwatrObservableConfig} from '@alwatr/observable';\n\nimport type {ActionName, ActionRecord, StateEventDetail, StateRecord} from './type.js';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport interface AlwatrFluxStateMachineConfig<S extends string> extends AlwatrObservableConfig {\n initialState: S;\n}\n\n/**\n * Flux (Finite) State Machine Base Class\n */\nexport abstract class AlwatrFluxStateMachineBase<S extends string, E extends string> extends AlwatrObservable<{state: S}> {\n /**\n * States and transitions config.\n */\n protected stateRecord_: StateRecord<S, E> = {};\n\n /**\n * Bind actions name to class methods\n */\n protected actionRecord_: ActionRecord<S, E> = {};\n\n protected initialState_: S;\n\n protected override message_: {state: S};\n\n constructor(config: AlwatrFluxStateMachineConfig<S>) {\n config.loggerPrefix ??= 'flux-state-machine';\n super(config);\n\n this.initialState_ = config.initialState;\n this.message_ = {state: this.initialState_};\n setTimeout(this.resetToInitialState_.bind(this), 0);\n }\n\n private firstResetToInitialState__ = true;\n /**\n * Reset machine to initial state without notify.\n */\n protected resetToInitialState_(): Promise<void> {\n this.logger_.logMethod?.('resetToInitialState_');\n if (this.firstResetToInitialState__) {\n this.firstResetToInitialState__ = false;\n const eventDetail: StateEventDetail<S, E> = {from: this.initialState_, event: 'reset', to: this.initialState_};\n this.execAction__(`on_state_${this.initialState_}_enter`, eventDetail);\n return this.postTransition__(eventDetail);\n }\n // else {\n const from = this.message_.state;\n this.message_ = {state: this.initialState_};\n const eventDetail: StateEventDetail<S, E> = {from, event: 'reset', to: this.initialState_};\n return this.postTransition__(eventDetail);\n }\n\n /**\n * Transition condition.\n */\n protected shouldTransition_(_eventDetail: StateEventDetail<S, E>): Awaitable<boolean> {\n this.logger_.logMethodFull?.('shouldTransition_', _eventDetail, true);\n return true;\n }\n\n /**\n * Transition flux state machine instance to new state.\n */\n protected async transition_(event: E): Promise<void> {\n const fromState = this.message_.state;\n const toState = this.stateRecord_[fromState]?.[event];\n\n this.logger_.logMethodArgs?.('transition_', {fromState, event, toState});\n\n if (toState == null) {\n this.logger_.incident?.('transition', 'invalid_target_state', {\n fromState,\n event,\n });\n return;\n }\n\n const eventDetail: StateEventDetail<S, E> = {from: fromState, event, to: toState};\n\n if ((await this.shouldTransition_(eventDetail)) !== true) return;\n\n this.notify_({state: toState}); // message update but notify event delayed after execActions.\n\n this.postTransition__(eventDetail);\n }\n\n /**\n * Execute all actions for current state.\n */\n private async postTransition__(eventDetail: StateEventDetail<S, E>): Promise<void> {\n this.logger_.logMethodArgs?.('postTransition__', eventDetail);\n\n await this.execAction__(`on_event_${eventDetail.event}`, eventDetail);\n\n if (eventDetail.from !== eventDetail.to) {\n await this.execAction__(`on_any_state_exit`, eventDetail);\n await this.execAction__(`on_state_${eventDetail.from}_exit`, eventDetail);\n await this.execAction__(`on_any_state_enter`, eventDetail);\n await this.execAction__(`on_state_${eventDetail.to}_enter`, eventDetail);\n }\n\n this.execAction__(`on_state_${eventDetail.from}_event_${eventDetail.event}`, eventDetail);\n }\n\n /**\n * Execute action name if defined in _actionRecord.\n */\n private execAction__(name: ActionName<S, E | 'reset'>, eventDetail: StateEventDetail<S, E>): Awaitable<void> {\n const actionFn = this.actionRecord_[name];\n if (typeof actionFn === 'function') {\n this.logger_.logMethodArgs?.('execAction__', name);\n return actionFn.call(this, eventDetail);\n }\n }\n}\n", "import {AlwatrFluxStateMachineBase} from './base.js';\n\n/**\n * Flux (Finite) State Machine Base Class\n */\nexport abstract class AlwatrFluxStateMachine<S extends string, E extends string> extends AlwatrFluxStateMachineBase<S, E> {\n /**\n * Current state.\n */\n get state(): S {\n return this.message_.state;\n }\n\n /**\n * Transition flux state machine instance to new state.\n */\n transition(event: E): void {\n this.transition_(event);\n }\n\n /**\n * Reset machine to initial state without notify.\n */\n resetToInitialState(): void {\n this.resetToInitialState_();\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": [
|
|
3
|
+
"sources": ["../src/fsm-service.ts", "../src/facade.ts"],
|
|
4
|
+
"sourcesContent": ["import {createLogger} from '@alwatr/logger';\nimport {createStateSignal, createEventSignal} 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 Record<string, unknown>> {\n protected readonly logger_ = createLogger(`fsm:${this.config_.name}`);\n\n /** The event signal for sending events to the FSM. */\n public readonly eventSignal = createEventSignal<TEvent>({\n name: `fsm-event-${this.config_.name}`,\n });\n\n private readonly stateSignal__ = createStateSignal<MachineState<TState, TContext>>({\n name: `fsm-state-${this.config_.name}`,\n initialValue: {\n name: this.config_.initial,\n context: this.config_.context,\n },\n });\n\n /** The public, read-only state signal. Subscribe to react to state changes. */\n public readonly stateSignal = this.stateSignal__.asReadonly();\n\n public constructor(protected readonly config_: StateMachineConfig<TState, TEvent, TContext>) {\n this.logger_.logMethodArgs?.('constructor', config_);\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", "import {FsmService} from './fsm-service.js';\n\nimport type {MachineEvent, StateMachineConfig} from './type.js';\n\n/**\n * A simple and clean factory function for creating an `FsmService` instance.\n * This is the recommended way to instantiate a new state machine.\n *\n * @template TState - The union type of all possible states.\n * @template TEvent - The union type of all possible events.\n * @template TContext - The type of the machine's context.\n *\n * @param config - The machine's configuration object.\n * @returns A new, ready-to-use instance of `FsmService`.\n *\n * @example\n * ```ts\n * import {createFsmService} from '@alwatr/fsm';\n * import type {StateMachineConfig} from '@alwatr/fsm';\n *\n * // 1. Define types\n * type LightContext = {brightness: number};\n * type LightState = 'on' | 'off';\n * type LightEvent = {type: 'TOGGLE'} | {type: 'SET_BRIGHTNESS'; level: number};\n *\n * // 2. Config the state machine\n * const lightMachineConfig: StateMachineConfig<LightState, LightEvent, LightContext> = {\n * name: 'light-switch',\n * initial: 'off',\n * context: {brightness: 0},\n * states: {\n * off: {\n * on: {\n * TOGGLE: {\n * target: 'on',\n * assigners: [() => ({brightness: 100})],\n * },\n * },\n * },\n * on: {\n * on: {\n * TOGGLE: {target: 'off', assigners: [() => ({brightness: 0})]},\n * SET_BRIGHTNESS: {assigners: [(event) => ({brightness: event.level})]},\n * },\n * },\n * },\n * };\n *\n * // 3. Create the service\n * const lightService = createFsmService(lightMachineConfig);\n *\n * // 4. Use it in your application\n * lightService.stateSignal.subscribe((state) => {\n * console.log(`Light is ${state.name} with brightness ${state.context.brightness}`);\n * });\n *\n * lightService.eventSignal.dispatch({type: 'TOGGLE'}); // Light is on with brightness 100\n *\n * lightService.eventSignal.dispatch({type: 'SET_BRIGHTNESS', level: 50}); // Light is on with brightness 50\n *\n * // 5. Cleanup\n * // lightService.destroy();\n * ```\n */\nexport function createFsmService<TState extends string, TEvent extends MachineEvent, TContext extends Record<string, unknown>>(\n config: StateMachineConfig<TState, TEvent, TContext>,\n): FsmService<TState, TEvent, TContext> {\n return new FsmService(config);\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,OAAQ,iBAAmB,iBAC3B,OAAQ,kBAAmB,sBAAwB,iBAa5C,IAAM,WAAN,KAA+G,CAmB7G,YAA+B,QAAuD,CAAvD,qBAlBtC,KAAmB,QAAU,aAAa,OAAO,KAAK,QAAQ,IAAI,EAAE,EAGpE,KAAgB,YAAc,kBAA0B,CACtD,KAAM,aAAa,KAAK,QAAQ,IAAI,EACtC,CAAC,EAED,KAAiB,cAAgB,kBAAkD,CACjF,KAAM,aAAa,KAAK,QAAQ,IAAI,GACpC,aAAc,CACZ,KAAM,KAAK,QAAQ,QACnB,QAAS,KAAK,QAAQ,OACxB,CACF,CAAC,EAGD,KAAgB,YAAc,KAAK,cAAc,WAAW,EAG1D,KAAK,QAAQ,gBAAgB,cAAe,OAAO,EACnD,KAAK,YAAY,UAAU,KAAK,oBAAoB,KAAK,IAAI,EAAG,CAAC,gBAAiB,KAAK,CAAC,CAC1F,CAQA,MAAc,oBAAoB,MAA8B,CAC9D,MAAM,aAAe,KAAK,cAAc,IAAI,EAC5C,KAAK,QAAQ,gBAAgB,sBAAuB,CAAC,MAAO,aAAa,KAAM,KAAK,CAAC,EAErF,MAAM,WAAa,KAAK,iBAAiB,MAAO,aAAa,OAAO,EAEpE,GAAI,CAAC,WAAY,CACf,KAAK,QAAQ,WAAW,sBAAuB,gBAAiB,sCAAuC,CACrG,MAAO,aAAa,KACpB,KACF,CAAC,EACD,MACF,CAEA,MAAM,gBAAkB,WAAW,QAAU,aAAa,KAG1D,GAAI,kBAAoB,aAAa,KAAM,CACzC,KAAK,K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,mBAAoB,yBAA0B,MAAO,CACtE,MACA,OACF,CAAC,EAED,OAAO,OACT,CACF,CAMO,SAAgB,CACrB,KAAK,QAAQ,YAAY,SAAS,EAClC,KAAK,YAAY,QAAQ,EACzB,KAAK,YAAY,QAAQ,CAC3B,CACF,ECpKO,SAAS,iBACd,OACsC,CACtC,OAAO,IAAI,WAAW,MAAM,CAC9B",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|
package/dist/type.d.ts
CHANGED
|
@@ -1,10 +1,99 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
export
|
|
1
|
+
import type { SignalConfig } from '@alwatr/signal';
|
|
2
|
+
/**
|
|
3
|
+
* Represents the state of a state machine, including its current finite state value
|
|
4
|
+
* and its extended state (context).
|
|
5
|
+
*
|
|
6
|
+
* @template TState The union type of the finite state values.
|
|
7
|
+
* @template TContext The type of the context object (extended state).
|
|
8
|
+
*/
|
|
9
|
+
export interface MachineState<TState extends string, TContext extends Record<string, unknown>> {
|
|
10
|
+
/** The current finite state value. */
|
|
11
|
+
readonly name: TState;
|
|
12
|
+
/** The context (extended state) of the machine, holding quantitative data. */
|
|
13
|
+
readonly context: TContext;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Represents an event that can be sent to the state machine.
|
|
17
|
+
* It must have a `type` property, which acts as a discriminator.
|
|
18
|
+
*
|
|
19
|
+
* @template TEventType The union type of event names.
|
|
20
|
+
*/
|
|
21
|
+
export interface MachineEvent<TEventType extends string = string> {
|
|
22
|
+
/** The unique type of the event. */
|
|
23
|
+
readonly type: TEventType;
|
|
24
|
+
/** An event can carry an optional payload. */
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Defines an assigner (synchronous action) that updates the context during transitions.
|
|
29
|
+
* It must return a partial context object to merge.
|
|
30
|
+
*
|
|
31
|
+
* @template TContext The type of the machine's context.
|
|
32
|
+
* @template TEvent The type of the event that triggered this assigner.
|
|
33
|
+
* @returns A partial context object to be merged into the machine's context.
|
|
34
|
+
*/
|
|
35
|
+
export type Assigner<TEvent extends MachineEvent, TContext extends Record<string, unknown>> = (event: Readonly<TEvent>, context: Readonly<TContext>) => Partial<TContext> | void;
|
|
36
|
+
/**
|
|
37
|
+
* Defines an effect (asynchronous side-effect action) executed on state entry/exit.
|
|
38
|
+
* It can interact with the outside world and can dispatch new events.
|
|
39
|
+
*
|
|
40
|
+
* @template TContext The type of the machine's context.
|
|
41
|
+
* @template TEvent The type of the event that triggered this effect.
|
|
42
|
+
* @returns void or a Promise<void>.
|
|
43
|
+
*/
|
|
44
|
+
export type Effect<TEvent extends MachineEvent, TContext extends Record<string, unknown>> = (event: Readonly<TEvent>, context: Readonly<TContext>) => Awaitable<TEvent | void>;
|
|
45
|
+
/**
|
|
46
|
+
* Defines a conditional guard function for a transition.
|
|
47
|
+
* The transition is only taken if this function returns true.
|
|
48
|
+
*
|
|
49
|
+
* @template TContext The type of the machine's context.
|
|
50
|
+
* @template TEvent The type of the event.
|
|
51
|
+
* @returns `true` if the transition should be taken, `false` otherwise.
|
|
52
|
+
*/
|
|
53
|
+
export type Condition<TEvent extends MachineEvent, TContext extends Record<string, unknown>> = (event: Readonly<TEvent>, context: Readonly<TContext>) => boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Defines a transition for a given state and event. It specifies the target state,
|
|
56
|
+
* actions, and an optional condition.
|
|
57
|
+
*
|
|
58
|
+
* @template TState The type of the state.
|
|
59
|
+
* @template TEvent The type of the event.
|
|
60
|
+
* @template TContext The type of the machine's context.
|
|
61
|
+
*/
|
|
62
|
+
export interface Transition<TState extends string, TEvent extends MachineEvent, TContext extends Record<string, unknown>> {
|
|
63
|
+
/** The target state to transition to. If undefined, it's an internal transition. */
|
|
64
|
+
readonly target?: TState;
|
|
65
|
+
/** A condition function that must return true for the transition to occur. */
|
|
66
|
+
readonly condition?: Condition<TEvent, TContext>;
|
|
67
|
+
/** An array of assigners to execute. These update context synchronously. */
|
|
68
|
+
readonly assigners?: SingleOrArray<Assigner<TEvent, TContext>>;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The declarative configuration object for creating a state machine.
|
|
72
|
+
* This object defines the entire behavior of the machine.
|
|
73
|
+
*
|
|
74
|
+
* @template TState The union type of all possible states.
|
|
75
|
+
* @template TEvent The union type of all possible events.
|
|
76
|
+
* @template TContext The type of the context object.
|
|
77
|
+
*/
|
|
78
|
+
export interface StateMachineConfig<TState extends string, TEvent extends MachineEvent, TContext extends Record<string, unknown>> extends Pick<SignalConfig, 'name'> {
|
|
79
|
+
/** The initial finite state value. */
|
|
80
|
+
readonly initial: TState;
|
|
81
|
+
/** The initial context (extended state) of the machine. */
|
|
82
|
+
readonly context: TContext;
|
|
83
|
+
/** An object defining all possible states and their transitions. */
|
|
84
|
+
readonly states: {
|
|
85
|
+
readonly [S in TState]?: {
|
|
86
|
+
/** An object mapping event types to transitions for the current state. */
|
|
87
|
+
readonly on?: {
|
|
88
|
+
readonly [E in TEvent['type']]?: SingleOrArray<Transition<TState, Extract<TEvent, {
|
|
89
|
+
type: E;
|
|
90
|
+
}>, TContext>>;
|
|
91
|
+
};
|
|
92
|
+
/** An array of side-effect effects to execute upon entering this state. */
|
|
93
|
+
readonly entry?: SingleOrArray<Effect<TEvent, TContext>>;
|
|
94
|
+
/** An array of side-effect effects to execute upon exiting this state. */
|
|
95
|
+
readonly exit?: SingleOrArray<Effect<TEvent, TContext>>;
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
}
|
|
10
99
|
//# sourceMappingURL=type.d.ts.map
|
package/dist/type.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../src/type.ts"],"names":[],"mappings":"AAAA,MAAM,
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../src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AAa,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;YACzD,0EAA0E;YAC1E,QAAQ,CAAC,IAAI,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;SACzD;KACF,CAAC;CACH"}
|
package/package.json
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/fsm",
|
|
3
|
-
"description": "A
|
|
4
|
-
"version": "
|
|
3
|
+
"description": "A tiny, type-safe, declarative, and reactive finite state machine (FSM) library for modern TypeScript applications, built on top of Alwatr Signals.",
|
|
4
|
+
"version": "6.0.0",
|
|
5
5
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com> (https://ali.mihandoost.com)",
|
|
6
6
|
"bugs": "https://github.com/Alwatr/flux/issues",
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@alwatr/
|
|
9
|
-
"@alwatr/
|
|
8
|
+
"@alwatr/logger": "^6.0.3",
|
|
9
|
+
"@alwatr/signal": "6.0.0"
|
|
10
10
|
},
|
|
11
11
|
"devDependencies": {
|
|
12
|
-
"@alwatr/nano-build": "^6.1
|
|
13
|
-
"@alwatr/prettier-config": "^5.0.
|
|
14
|
-
"@alwatr/tsconfig-base": "^6.0.
|
|
15
|
-
"@alwatr/type-helper": "^6.
|
|
16
|
-
"@types/node": "^22.18.
|
|
12
|
+
"@alwatr/nano-build": "^6.2.1",
|
|
13
|
+
"@alwatr/prettier-config": "^5.0.3",
|
|
14
|
+
"@alwatr/tsconfig-base": "^6.0.1",
|
|
15
|
+
"@alwatr/type-helper": "^6.1.0",
|
|
16
|
+
"@types/node": "^22.18.6",
|
|
17
17
|
"jest": "^30.1.3",
|
|
18
18
|
"typescript": "^5.9.2"
|
|
19
19
|
},
|
|
@@ -68,5 +68,5 @@
|
|
|
68
68
|
},
|
|
69
69
|
"type": "module",
|
|
70
70
|
"types": "./dist/main.d.ts",
|
|
71
|
-
"gitHead": "
|
|
71
|
+
"gitHead": "ca38674339f4836ffcce1e1801c7ccb6b58c90f2"
|
|
72
72
|
}
|