XState JSON state machine to Stateless compiler
$ dotnet add package XStatelessCompilerXState JSON state machine to Stateless compiler
//Read XState json
var json = File.ReadAllText("xstate_machine.json");
//Compile
var compiler = new XStateCompiler(json);
var machine = compiler.Compile();
//Fire events
machine.RaiseEvent("START");
//Access state
var stateName = machine.State.Name;
Defining effects and context properties
var machine = compiler.Compile();
//Initialize context property
machine.Context["retries"] = true;
//Define effects
machine.SetEffect("increment", (context, e) => ++context["retries"]);
Using custom context and state management
//Create state and context store
var stateStore = new MemoryStateStore(initialState: new("initial"));
var contextStore = new MemoryContextStore();
//Initialize state machine with custom state and context stores
var machine = XStateMachine
.Create(stateStore)
.WithContext(contextStore);
var compiler = new XStateCompiler(json);
var machine = compiler.CompileFrom(machine);
Create custom state stores by extending BaseStateStore
public class MemoryStateStore : BaseStateStore
{
private XState _currentState;
protected override Func<XState> GetState { get; set; }
protected override Action<XState> SetState { get; set; }
public MemoryStateStore(XState initialState)
{
_currentState = initialState;
//Override SetState and GetState
SetState = (state) => _currentState = state;
GetState = () => _currentState;
}
}
Create custom context stores by extending BaseContextStore
public class MemoryContextStore : BaseContextStore
{
private readonly Dictionary<string, dynamic> _context = new();
protected override Func<string, dynamic> GetContext { get; set; }
protected override Action<string, dynamic> SetContext { get; set; }
public MemoryContextStore()
{
//Override SetContext and GetContext
SetContext = (key, value) => _context[key] = value;
GetContext = (key) => _context[key];
}
}
Copyright (c) 2023 Marco
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.