TypeScript package
Package @traxsharp/state-machineSurface TypeScriptSource index.ts, index.ts, react.ts, package.json
@traxsharp/state-machine is the TypeScript twin of Trax.StateMachine, published from Trax.StateMachine/ts.
Its exports are pinned by a committed baseline (src/exports.test.ts).
npm install @traxsharp/state-machine graphql-wsgraphql-ws 6 is an optional peer dependency: a machine's push and the client trax client generates open their
socket with it. React 18 or 19 is one too, for @traxsharp/state-machine/react and the generated hooks.
It is published to npm with every Trax release, at the same version as the NuGet packages: install the version
that matches your Trax.* packages. A twin generated by trax machine generate does not demand that version,
though: it records the IR format it was
generated for, and loads on any release of the package that reads that format, so a package upgraded without
regenerating keeps working until the format itself changes.
The client reads every answer and push with the runtime's own JSON.parse. Node 24 before 24.22.1, and Chromium
builds whose V8 lacks the same fix, can misread a one-character escaped key such as "\t" as "\\" once an earlier
parse has seen a "\\" key (nodejs/node#66916), so a context holding
such keys can reach the page with the wrong ones. Run node 24.22.1 or later.
Members
| Entry point | Holds |
|---|---|
@traxsharp/state-machine | The engine, the typed view, the framework-free stores, the IR interpreter and the generators. Pure: no I/O. |
@traxsharp/state-machine/client | Everything that talks to a Trax server: the typed executor over persisted documents, draft sessions, and the server-authoritative controller. |
@traxsharp/state-machine/react | useServerMachine and useRememberedMachine. React is an optional peer dependency. |
The engine and the typed view
| Export | What it is |
|---|---|
SnapshotMachine | The reducer, the twin of the C# SnapshotMachine: createInitialSnapshot, advance, applyOutcome, applyTimer, timer, rehydrate, serialize, canFire, availableTriggers, plan, describe. Every operation is total: advance answers with an AdvanceResult, rehydrate with a RehydrationResult. rehydrate(json, { fromServer: true }) reads a snapshot the server sent: a custom rule the twin has no handler for counts as passed, since the server evaluated it, and the shape and every built-in rule are still checked. Any other read, and every advance, refuses such a rule. |
RefusalCode, ClientProblemCode | RefusalCode holds every code a refusal carries, equal member for member to the C# enum (result codes); some, such as TOO_LARGE, only a server answers. ClientProblemCode holds the codes the package reports itself: GONE, NOT_READY, TRANSPORT_ERROR, NOTHING_TO_RETRY, DISPOSED. A problem.code is one of the two. |
TypedMachine, typedMachineFromIr(ir, schemaHash?) | The same engine with one machine's states, triggers and contexts as types (MachineSpec, StateOf, TriggerOf, ContextOf, InputOf). typedMachineFromIr builds one from an IR document; a generated twin calls it. A trigger whose edge runs an effect takes no input in a twin's types (the server's effect runner hands it the receipt), and isEffectBound(trigger) says which. predicts(state, trigger) is false when an edge the trigger could take from the state rests on a custom rule (a guard, a reduction, or the destination's requirement) the machine holds no handler for. |
plan(snapshot, { target, fields?, navigation, maxDepth? }), PlanRequest, PlanResult, PlannedEvent | On SnapshotMachine and TypedMachine: the events that take snapshot to the state target with the fields event applied, what a client sends to bring the server to where a page that ran ahead of it is. fields is the event that writes the page's fields ({ trigger, input }) or null, navigation the triggers without input that move between states, and maxDepth the longest plan to look for, twice the machine's states by default. The search is breadth first, the fields event first and then navigation in the order given, so every engine answers the same plan. It answers { result: 'plan', events } (none when the snapshot is already there, which means the target state where the fields event changes nothing), unreachable, exceeded (past maxDepth, or past 10,000 snapshots), undetermined with a trigger and the events before it when only an edge on a custom rule the machine holds no handler for might reach the target (send events, then trigger without a prediction, and plan again), or invalid with the code INVALID_INPUT or INVALID_CONTEXT when the fields input or the snapshot's context nests more than 512 arrays and objects deep, the target that is not a state, or the trigger that cannot navigate (unknown, effect-bound, an outcome, a timer, or the fields trigger listed in navigation). undetermined outranks exceeded. Snapshots are compared by their canonical wire with every null member left out, at any depth, as a host answers them, and a state where the fields event rests on a custom rule is never the goal. Never throws. |
machineFromIr(ir) | Builds the untyped MachineDefinition an IR document describes, with its declarative guards, reducers, input schemas, outcomes and timers. Throws when the IR names a rule, reduction, field type, comparison or rule source it does not know, as the C# IrMachine does. |
MachineDefinition, TransitionDefinition, MachineTimer, Guard, Reduce, ContextValidator, InputValidator | The definition SnapshotMachine runs. InputValidator is (input) => string | null: the check of one trigger's input against its declared schema, null when it matches. ContextValidator is (context, options?) => string | null, and options.fromServer is set on a snapshot the server sent. Guard is (context, input, options?) => boolean, and options.inputUnknown is set when the input is one only the server has: a guard built from the IR then counts every rule on the input, and every custom rule, as passing. |
IrDocument, IrTransition, IrOutcome, IrOutcomeEdge, IrTimer | The IR format as types. IrTimer is one state's timer: state, trigger, target, and either after or a context field with min and max (ISO-8601 durations). |
evaluateRule, applyReduction, validateSchema, validateInput | The rule interpreter. validateSchema(schema, context) checks a context; validateInput(schema, input) checks a trigger's input as the C# engine does (no input reads as {}, anything but a plain object is refused). Both answer null when valid, else a message, and never throw. |
Rule, Reduction, ValueSource, SetStep, ContextSchema, FieldSchema, ValueSchema, RuleSource, JsonFieldType, CompareOp, CustomGuards, CustomReducers | The declarative data model. ValueSchema is the shape of one value (its type, nullable, an integer's minimum and maximum, a record's fields, a map's or list's values); FieldSchema adds the field's name and constraints. |
generateContextTypes, generateMachineFactory | The generators that emit a twin from an IR. trax machine generate and the drift check call them. |
generateCSharpView(ir, options), CSharpViewOptions | The same machine's typed view for a .NET client, written from the same model of the IR as the twin: trax machine generate --lang csharp calls it. CSharpViewOptions is the namespace, the IR text the view embeds (irText) and its irHash. |
clientFormat, oldestClientFormatServed, requireClientFormat(n) | The client format: the API code trax client generates calls. Generated code calls requireClientFormat with the format it was generated for when it loads, before any twin, and the runtime throws naming both formats and whether to upgrade the package or regenerate. |
enumerate, serializeCorpus | Enumerate a machine into the differential corpus the C# engine replays. |
DifferentialSpec, DifferentialCorpus, DifferentialCase | What enumerate takes and writes. DifferentialSpec is the machine's id, version, states, triggers, outcomes, timers and seeds, the contexts to start from where no trigger reaches a state. DifferentialCorpus is the committed file: machine, version, generated and its cases. A DifferentialCase is one given snapshot, when a trigger and its input, and the expected outcome: transitioned with the canonical wire, or rejected with the code. |
MachineFactoryOptions | How generateMachineFactory writes a twin: importStyle (relative, the engine's own source, or specifier, one import from specifier, @traxsharp/state-machine by default) and the IR hash the twin exports as irHash. |
Snapshots and results
| Export | What it is |
|---|---|
Snapshot | The untyped snapshot, the only thing that crosses the wire or lands in a row: machine, version, state and context. The C# engine reads and writes the same shape (canonical wire). |
TypedSnapshot<Spec> | The snapshot as a union over the machine's states: on each state, context is that state's type. |
TypedAdvanceResult<Spec> | What a TypedMachine's advance answers: { outcome: 'transitioned', snapshot } or { outcome: 'rejected', reason, detail? }, the reason a RefusalCode. |
TypedRehydrationResult<Spec> | What its rehydrate answers: { result: 'ok', snapshot } or { result: 'error', code, message }. |
MigrationResult | One step of a migration forward: the state and context of the next version (migrations). |
InputArgs<Spec, Trigger> | The arguments a trigger's input takes in send: none for a trigger without input, its input otherwise. |
Driving a machine in memory
From @traxsharp/state-machine, for a machine no server holds (a preview, a test, a form's own steps):
| Export | What it is |
|---|---|
MachineController | A framework-free store held in memory: send, can, available, reset, subscribe, getSnapshot. It stores nothing, and a refused action still emits a view with its problem. A machine a server holds is driven through ServerMachineController instead. |
createFormView(machine, { steps, toContext, fieldsEvent?, navigation? }) | For a UI that owns its data and asks the machine: maps each UI step to a state (one to one), and gives advance, can, snapshotFor, serialize, resume and isCommitted in the UI's own step names. With fieldsEvent (the trigger that writes the form's values, and an input projection, toContext by default) and navigation (the triggers that move between steps), plan(serverSnapshotJson, step, values) answers the machine's plan from the server's snapshot to that step with those values, or null when there is no snapshot or it does not read, and sync(controller, step, values) calls the controller's syncTo with the same. Neither throws: a fields input projection that throws answers plan invalid with the fields trigger, and settles sync failed with INVALID_INPUT without calling syncTo. |
problemFromAdvance, problemFromRehydration, Problem | A refusal shaped for display. |
createDevLogger(options?) | Logs transitions and refusals in development, as a MachineObserver. DevLoggerOptions: strict, which throws on an internal error (a guard or reducer that threw) instead of logging it, and the console to write to. |
ControllerOptions<Spec> | What a MachineController is built with: the initial snapshot, or a function that makes it, and an observer. |
ControllerView<Spec> | What it holds and emits: the snapshot and the problem of the last refused action, or null. |
MachineObserver<Spec> | Callbacks on a controller: onTransition(from, trigger, to, snapshot), onRejected(trigger, problem, snapshot) and onInternalError(trigger, detail, snapshot). |
FormView, FormViewOptions, FormSyncTarget | What createFormView answers and takes: stateFor, stepFor, snapshotFor, advance, can, serialize, resume, isCommitted, plan, sync; the steps map, toContext projection, fieldsEvent and navigation; and what sync drives, anything with syncTo, a ServerMachineController among them (Drive a form from a machine). |
StepAdvance<Step>, ResumedStep<Spec, Step> | advance's answer, { ok: true, step } or { ok: false, reason, detail? }; and resume's, the step and the rehydrated snapshot. |
Talking to a server
From @traxsharp/state-machine/client (useServerMachine from @traxsharp/state-machine/react):
| Export | What it is |
|---|---|
createMachineExecutor(endpoint, { machines, ... }) | The executor for machines the host exposes on the typed root. Each machine is given its documents (MachineDocument, from the client manifest), and every operation is sent by its persisted id; a machine with none throws when the executor is built. A client never sends a document of its own. An event goes out only by the document of a trigger the machine declares as an event: an outcome, a timer or a trigger the machine lacks is refused with the code advance gives it (OUTCOME_BOUND, TIMER_BOUND, NO_TRANSITION) and sends nothing, and a trigger whose field is another operation's (start, get, discard, changed) is refused as NO_TRANSITION even for a machine given by its id alone. The effect event is held to the same rule. |
createDraftSession({ executor, machine, id }), startDraft({ executor, machine, requestId, input? }) | One draft of one machine, every method total: a refusal is a { ok: false, code, message }, an unreachable server is TRANSPORT_ERROR (ClientProblemCode.TransportError). startDraft creates a draft under an id the server mints. |
createMachineServer(endpoint, { machine, documents, socket, resubscribeDelays?, terminalStreamErrors? }) | One exposed machine's typed operations and its push stream (<machine>Changed), as the MachineServer a controller drives. persistedMessageReplacer is the graphql-ws jsonMessageReplacer it needs, DEFAULT_RESUBSCRIBE_DELAYS (1, 2, then 5 seconds) the delays before a dropped stream is subscribed again, each wait drawn uniformly between half the delay and the whole of it so the pages a host dropped together do not subscribe again together, and DEFAULT_REQUEST_TIMEOUT (30 seconds) how long a request waits for its answer unless requestTimeout says otherwise. A socket the host closed with 4401 or 4403 (the close event graphql-ws hands the sink) is not subscribed again: the stream delivers { type: 'ended', code, message } with UNAUTHENTICATED or FORBIDDEN, and a message naming the close code. graphql-ws itself gives up on 4401 at once but retries 4403 for as long as its retryAttempts allows, so pass retryClosedSocket as the client's shouldRetry: it retries every close but 4401 and 4403, and nothing that is not a close. A stream refused with a GraphQL error (a next or an error) coded TRAX_AUTHORIZATION or AUTH_NOT_AUTHORIZED ends as FORBIDDEN, and one coded AUTH_NOT_AUTHENTICATED as UNAUTHENTICATED, the same way; one coded CLIENT_OUTDATED, in a next or an error, delivers client-outdated. A socket error whose code, or a stream error whose extensions.code, is in terminalStreamErrors is not subscribed again either: the stream delivers { type: 'ended', code, message } and the controller stops with that code. A request rejected with such a code stops the controller the same way, through the server's endedBy(error), instead of failing as a transport error that retry resends. The generated client passes CONNECTION_CHANGED. |
requireSecureEndpoint(endpoint, allowInsecure) | The check every executor and server runs on its endpoint, and the generated client before each train request: it throws for an absolute http: endpoint whose host is not loopback (localhost, 127.0.0.0/8, ::1) unless allowInsecure is true, since whatever authenticates the request would travel in cleartext. A relative endpoint is the page's own origin and passes, except a scheme-relative one (//host/..., or \\host\..., which a browser reads the same way), which goes to the host it names and throws unless allowInsecure is true. |
useRememberedMachine(machine, { server, rememberKey, ...}) | From @traxsharp/state-machine/react: useServerMachine over the instance this browser keeps in localStorage under rememberKey. It opens the remembered instance, or starts one under a requestId kept until the start answers, and adds forget(), which starts over. A rememberKey that changes opens that key's instance. An instance the stream says was deleted is forgotten and a new one started; one the server answers NOT_FOUND stops the hook (error.deleted false) and stays remembered, since the server answers another caller's instance the same way. Give each user a key of their own. The code trax client generates calls it as useRemembered<Machine>(), under trax.<machine id>.<user> for the user given to configureTrax. |
ServerMachineController | The framework-free, server-authoritative store: the server applies every transition and the twin predicts. send refuses a trigger the machine does not declare as an event where it is sent, with the code advance gives it (NO_TRANSITION, OUTCOME_BOUND, TIMER_BOUND), and sends nothing. It copies the input as JSON when it is called, so a page that changes the object afterwards changes neither the event nor the prediction, and refuses one JSON cannot carry (a cycle, a BigInt) with INVALID_INPUT, sending nothing; syncTo copies its fields and navigation the same way, and settles such an input invalid with INVALID_INPUT. While it holds no instance and is not opening one (its start was refused or failed, or its first read gave up), a send settles failed with NOT_READY until retry opens it. It reads every snapshot the server sends with fromServer, so a state that requires a custom rule opens without a handler in the twin. The twin does not predict an event whose edge rests on a custom rule it holds no handler for, a guard, a reduction or the destination's requirement: the event is sent without a prediction, nothing queued after it is predicted, and the server's answer is shown. can for such an event says only whether the state has an edge for it. An effect-bound trigger is never predicted, and can for it reads only its guard's rules on the context. start, send, retry (which resends a start, the first read of an instance opened by id, or an event that failed in transport, or stayed SERVER_OUTDATED past every retry, under its first request id, and answers NOTHING_TO_RETRY once a later event has been confirmed or while one is queued or in flight), can, available, get, subscribe, dispose, and syncTo(target, { fields, navigation }), which brings the server to target with the fields event applied for a page that ran ahead of it: once every earlier event has settled it plans from the confirmed snapshot (plan), sends the first event as send does, and plans again from each answer until the plan is empty. A GUARD_FAILED, NO_TRANSITION, CLIENT_DIVERGENCE or CONFLICT reads the instance once and plans again, and a second one in the same sync settles it refused. An undetermined plan sends its events, then its trigger without a prediction; once the server has confirmed the fields event in target, a plan from there that is undetermined on the fields trigger alone (it rests on a custom rule) settles synced. A later syncTo supersedes an earlier one, which settles superseded once its event in flight answers. No sync sends more than twice the machine's states in events. useServerMachine's syncTo runs a sync that failed in transport again when the browser fires online, unless send or syncTo was called since: it resends the event that failed under its first request id (retry), so one that did reach the server is answered with what it recorded rather than applied twice, then syncs on from that answer. A resend that fails in transport again waits for the next online. |
DEFAULT_RETRY_DELAYS | The controller's default delays between retries of a SERVER_OUTDATED answer or a failed read: 250, 500, 1,000, 2,000 and 4,000 ms. Override with retryDelays. |
TRANSPORT_FAILED | The problem code (TRANSPORT_ERROR) of a send or read the controller could not deliver. It is the same string as TRANSPORT_ERROR, the sessions' code, exported under both names. |
What the clients take and answer
From @traxsharp/state-machine/client:
| Export | What it is |
|---|---|
MachineExecutorOptions, HttpExecutorOptions | createMachineExecutor's options: the machines, and the headers each request carries (called per request, so a rotating token stays fresh) and the fetch it is sent with. An absolute http: endpoint throws unless its host is loopback (localhost, 127.0.0.0/8, ::1) or allowInsecureTransport is set; a relative one is the page's own origin. Each request is sent with redirect: 'error', so a redirect fails it rather than carrying its headers to another host, and so does an answer the given fetch reached through one. maxResponseSize is the largest body read from an answer (16 MiB by default); a larger one fails the request and is not read past the limit, and a limit that is not a positive whole number of bytes (NaN among them) throws when the executor is built. requestTimeout is how long one request may take, its whole answer included (30 seconds by default, at most 2^31 - 1 ms, the longest a timer waits; Infinity to wait for as long as the host takes; NaN, zero or less, or a longer one throws when the executor is built); a request past it is aborted and fails as a transport error, which a controller's retry resends under the same request id. |
TypedMachineOperations | One machine the executor sends: the machine (a twin, or its id and version), its documents and its effectEvent, the trigger sendSnapshot fires. |
SnapshotExecutor, SnapshotOperation | What an executor is: a function from one of the six operations (startSnapshot, saveSnapshot, advanceSnapshot, loadSnapshot, sendSnapshot, discardSnapshot) and its input to the SnapshotOutput. It may throw; the sessions above it turn a throw into TRANSPORT_ERROR. |
SnapshotOutput, SnapshotProblem | Each operation's output: the snapshot as JSON or a problem (code, message), and beside them id and created from a start, discarded from a discard, the revision and the timer's dueAt. |
SnapshotClient, StartOptions, AdvanceOptions | The operations over any machine, each taking the machine name and the draft id. StartOptions carries the start input and the schemaHash; AdvanceOptions the trigger input, a requestId that makes a retry replay, the schemaHash and the twin's clientResult, which the server compares with its own and refuses CLIENT_DIVERGENCE when they differ. |
DraftSession, DraftSessionOptions | What createDraftSession answers and takes: save, advance, load, send and discard over one draft; and the executor, the machine (a twin, whose id and schema hash it reads, or a name with schemaHash), the draft id and messages. |
StartDraftOptions | What startDraft takes: the executor, machine, a requestId to keep until the start answers, the start input, schemaHash and messages. |
DraftResult, StartResult | Their answers, never thrown: { ok: true, snapshot, revision? } (with id and created from a start) or { ok: false, code, message }. |
DraftMessages | The fallback text of each refusal and transport failure, used only when the server sends none: saveRefused, saveUnavailable, advanceRefused, and so on for load, send, start and discard. |
MachineServerOptions | createMachineServer's options, HttpExecutorOptions with the machine, documents, socket, resubscribeDelays and terminalStreamErrors. Each of resubscribeDelays is from 0 to 2^31 - 1 ms; any other (NaN, a negative or infinite one) throws when the server is built. maxResponseSize bounds the requests' answers, not the push: the page's socket parses its own frames, so cap them there, for graphql-ws with a webSocketImpl that closes the socket on a message larger than the page accepts. |
PersistedSubscriptionSocket, SubscriptionSink | The part of a graphql-ws client the push needs: subscribe(payload, sink), returning the function that closes it; and the sink it delivers to, next, error, complete. |
TypedMachineServer | The MachineServer createMachineServer answers: start, event, get, subscribe and endedBy, and discard(id, requestId), which a page calls itself and so never throws: a request the transport failed answers a TRANSPORT_ERROR problem, and one rejected with a code in terminalStreamErrors (CONNECTION_CHANGED for a generated client's server) answers a problem with that code. |
ServerSnapshot | One snapshot as the server sends it: state, context, the revision every write bumps (null on an answer when the store records none, which the controller takes and cannot order; createMachineServer drops a push without one), the row's incarnation rowId, and dueAt. |
StartResponse, EventResponse, GetResponse, DiscardResponse, ServerProblem | A MachineServer's answers: started with the id and snapshot, ok with the snapshot, discarded, or a ServerProblem (kind: 'problem', code, message). A discard answered null, or with discarded: false and no problem, is a TRANSPORT_ERROR, not discarded. |
StreamMessage | What an instance's push delivers: a snapshot, gone (with notFound when the server answered NOT_FOUND), reconnected, client-outdated, or ended with a code and message. |
ServerMachineOptions<Spec> | What a ServerMachineController is built with: the machine, the server, the instance id or the startInput and startRequestId to start one, newRequestId and retryDelays, each from 0 to 2^31 - 1 ms; any other throws when the controller is built. |
ServerMachineView<Spec> | What it holds, a new object on every change: status (loading, ready, stopped), id, the snapshot shown (the prediction while one is pending), the confirmed one, rowId, revision, dueAt, pending, problem, error, and unsaved: whether a syncTo is running or the last one did not settle synced, for a leave guard. |
ServerMachineError | Why a controller stopped for good: its code (GONE, CLIENT_OUTDATED, or an ended code such as CONNECTION_CHANGED, or UNAUTHENTICATED and FORBIDDEN for a socket the host refused), message, and with GONE, deleted. |
SendOutcome | What one send came to: confirmed with the snapshot, refused or failed with the problem, or stopped with the error. |
SyncOptions<Spec>, SyncOutcome | What syncTo takes besides its target, the fields event ({ trigger, input }, or null) and the navigation triggers; and what it came to: synced with the snapshot the server confirmed, superseded, the planner's unreachable, exceeded or invalid (with its trigger, target or code), or refused, failed or stopped as for send. Before the first snapshot it settles failed with NOT_READY. |
From @traxsharp/state-machine/react:
| Export | What it is |
|---|---|
UseServerMachineOptions, UseServerMachineResult<Spec> | useServerMachine's options and answer, below. |
UseRememberedMachineOptions, UseRememberedMachineResult<Spec> | useRememberedMachine's: UseServerMachineOptions less the instance it chooses itself, with the rememberKey; and UseServerMachineResult with forget(). |
useServerMachine(machine, { server, id?, startInput?, startRequestId?, startStorageKey?, newRequestId?, retryDelays? }), from
@traxsharp/state-machine/react, is ServerMachineController as a hook. Its options, its answer and an example are under
Driving an instance from React.
useRememberedMachine reads and writes globalThis.localStorage, and keeps nothing when it is missing or throws.
Node 25 and later define a localStorage global of their own, empty without --localstorage-file, which shadows the
one a jsdom test environment provides, so in a test under vitest's jsdom environment the hook remembers nothing.
Put jsdom's back in a setup file (setupFiles in the vitest config):
Object.defineProperty(globalThis, "localStorage", { value: globalThis.jsdom.window.localStorage, configurable: true });See also
- The machines root, the operations each client sends.
- Result codes, the codes every result carries.
- IR format, what
machineFromIrreads. - The codegen pipeline, how a twin is generated.