### Creating a Transition Actor with xstate Source: https://www.jsdocs.io/package/xstate/index Example demonstrating how to create an actor using `fromTransition` in xstate. It shows the setup of context, events, input, and the logic for state transitions. ```typescript import { fromTransition, createActor, type AnyActorSystem } from 'xstate'; //* The actor's stored context. type Context = { // The current count. count: number; // The amount to increase `count` by. step: number; }; // The events the actor receives. type Event = { type: 'increment' }; // The actor's input. type Input = { step?: number }; // Actor logic that increments `count` by `step` when it receives an event of // type `increment`. const logic = fromTransition( (state, event, actorScope) => { actorScope.self; // ^? TransitionActorRef if (event.type === 'increment') { return { ...state, count: state.count + state.step }; } return state; }, ({ input, self }) => { self; // ^? TransitionActorRef return { count: 0, step: input.step ?? 1 }; } ); const actor = createActor(logic, { input: { step: 10 } }); // ^? TransitionActorRef ``` -------------------------------- ### Machine Setup Configuration in XState Source: https://www.jsdocs.io/package/xstate/index The `setup` function in XState provides a way to configure machines with actors, actions, guards, and delays. It returns utility functions like `createStateConfig`, `createAction`, and `createMachine` for building state configurations. ```typescript setup: < TContext extends MachineContext, TEvent extends AnyEventObject, TActors extends Record = {}, TChildrenMap extends Record = {}, TActions extends Record = {}, TGuards extends Record = {}, TDelay extends string = never, TTag extends string = string, TInput = {}, TOutput extends {} = {}, TEmitted extends EventObject = EventObject, TMeta extends MetaObject = MetaObject >({ schemas, actors, actions, guards, delays, }: { schemas?: unknown; types?: SetupTypes< TContext, TEvent, TChildrenMap, TTag, TInput, TOutput, TEmitted, TMeta >; actors?: { [K in keyof TActors | Values]: K extends keyof TActors ? TActors[K] : never; }; actions?: { [K in keyof TActions]: ActionFunction< TContext, TEvent, TEvent, TActions[K], ToProvidedActor, ToParameterizedObject, ToParameterizedObject, TDelay, TEmitted >; }; guards?: { [K in keyof TGuards]: GuardPredicate< TContext, TEvent, TGuards[K], ToParameterizedObject >; }; delays?: { [K in TDelay]: DelayConfig< TContext, TEvent, ToParameterizedObject['params'], TEvent >; }; } & { [K in RequiredSetupKeys]: unknown }) => { createStateConfig: < TStateConfig extends StateNodeConfig< TContext, TEvent, ToProvidedActor, ToParameterizedObject, ToParameterizedObject, TDelay, TTag, unknown, TEmitted, TMeta > >( config: TStateConfig ) => TStateConfig; createAction: ( action: ActionFunction< TContext, TEvent, TEvent, unknown, ToProvidedActor, ToParameterizedObject, ToParameterizedObject, TDelay, TEmitted > ) => ActionFunction< TContext, TEvent, TEvent, unknown, ToProvidedActor, ToParameterizedObject, ToParameterizedObject, TDelay, TEmitted >; createMachine: () => const; }; ``` -------------------------------- ### Example Usage of fromTransition (JavaScript) Source: https://www.jsdocs.io/package/xstate/index Demonstrates creating and using a transition actor. An initial state `{ count: 0 }` is provided. The actor subscribes to snapshots, starts, and sends an 'increment' event, logging the resulting state changes. ```javascript const transitionLogic = fromTransition( (state, event) => { if (event.type === 'increment') { return { ...state, count: state.count + 1 }; } return state; }, { count: 0 } ); const transitionActor = createActor(transitionLogic); transitionActor.subscribe((snapshot) => { console.log(snapshot); }); transitionActor.start(); // => { // status: 'active', // context: { count: 0 }, // ... // } transitionActor.send({ type: 'increment' }); // => { // status: 'active', // context: { count: 1 }, // ... // } ``` -------------------------------- ### Start Method for StateNode in xstate Source: https://www.jsdocs.io/package/xstate/index The `start` method initializes or resumes the state node with a given snapshot. It returns void and is fundamental for activating a state within the machine. ```typescript start: ( snapshot: MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig > ) => void; ``` -------------------------------- ### XState Machine Methods Source: https://www.jsdocs.io/package/xstate/index This section describes the methods available on an XState machine, including getting initial snapshots, state nodes, and transitions. ```APIDOC ## XState Machine Methods ### Method: `getInitialSnapshot` #### Description Returns the initial `State` instance, with reference to `self` as an `ActorRef`. #### Parameters - **actorScope** (`ActorScope>`) - The actor scope for the machine. - **input** (`TInput?`) - Optional input for the initial state. #### Returns ```typescript MachineSnapshot; ``` ### Method: `getPersistedSnapshot` #### Description Gets a snapshot suitable for persistence. #### Parameters - **snapshot** (`MachineSnapshot<...>`) - The current machine snapshot. - **options** (`unknown?`) - Optional persistence options. #### Returns ```typescript Snapshot; ``` ### Method: `getStateNodeById` #### Description Retrieves a state node by its ID. #### Parameters - **stateId** (`string`) - The ID of the state node to retrieve. #### Returns ```typescript StateNode; ``` ### Method: `getTransitionData` #### Description Gets transition data for a given snapshot and event. #### Parameters - **snapshot** (`MachineSnapshot<...>`) - The current machine snapshot. - **event** (`TEvent`) - The event that triggered the transition. #### Returns ```typescript Array>; ``` ### Method: `microstep` #### Description Determines the next state given the current `state` and `event`. Calculates a microstep. #### Parameters - **snapshot** (`MachineSnapshot<...>`) - The current machine snapshot. - **event** (`TEvent`) - The received event. - **actorScope** (`AnyActorScope`) - The actor scope. #### Returns ```typescript Array>; ``` ### Method: `provide` #### Description Clones this state machine with the provided implementations. #### Parameters - **implementations** (`InternalMachineImplementations>`) - Options (`actions`, `guards`, `actors`, `delays`) to recursively merge with the existing options. #### Returns A new `StateMachine` instance with the provided implementations. ### Method: `resolveState` #### Description Resolves a machine snapshot from configuration. #### Parameters - **config** (`{ value: StateValue; context?: TContext; historyValue?: HistoryValue; status?: SnapshotStatus; output?: TOutput; error?: unknown; } & (Equals extends false ? { context: unknown } : {})) - The configuration object for resolving the state. #### Returns ```typescript MachineSnapshot; ``` ``` -------------------------------- ### Example: Creating an Observable Actor with XState (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Demonstrates how to create an actor using `fromObservable` in xstate. The actor uses RxJS's `interval` to increment a counter over time, configurable by an input `period`. The example shows how to type the actor's context and input, and how `self` within the logic resolves to `ObservableActorRef`. ```typescript import { fromObservable, createActor } from 'xstate'; import { interval } from 'rxjs'; // The type of the value observed by the actor's logic. type Context = number; // The actor's input. type Input = { period?: number }; // Actor logic that observes a number incremented every `input.period` // milliseconds (default: 1_000). const logic = fromObservable(({ input, self }) => { self; // ^? ObservableActorRef return interval(input.period ?? 1_000); }); const actor = createActor(logic, { input: { period: 2_000 } }); // ^? ObservableActorRef ``` -------------------------------- ### Start and Stop Actor (JavaScript) Source: https://www.jsdocs.io/package/xstate/index Provides methods to control the lifecycle of an Actor. 'start()' initiates the actor from its initial state, and 'stop()' halts the actor and unsubscribes all listeners. ```javascript start: () => this; ``` ```javascript stop: () => this; ``` -------------------------------- ### Actor Methods Source: https://www.jsdocs.io/package/xstate/index Methods for interacting with XState actors, including subscribing to snapshots, sending events, starting, stopping, and serializing actors. ```APIDOC ## Actor Methods ### method on ```javascript on: ['type'] | '*'>(type: TType, handler: (emitted: EmittedFrom & (TType extends '*' ? unknown : { type: TType })) => void) => Subscription; ``` * Subscribes a handler function to specific emitted event types or all event types from an actor. ### method send ```javascript send: (event: EventFromLogic) => void; ``` * Sends an event to the running Actor to trigger a transition. #### Parameter event * **event** (EventFromLogic) - The event to send. ### method start ```javascript start: () => this; ``` * Starts the Actor from the initial state. ### method stop ```javascript stop: () => this; ``` * Stops the Actor and unsubscribes all listeners. ### method subscribe ```javascript subscribe: { (observer: Observer>): Subscription; (nextListener?: (snapshot: SnapshotFrom) => void, errorListener?: (error: any) => void, completeListener?: () => void): Subscription; }; ``` * Subscribe an observer to an actor’s snapshot values. #### Parameter observer * **observer** (Observer> | ((snapshot: SnapshotFrom) => void)) - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot. #### Remarks The observer will receive the actor’s snapshot value when it is emitted. The observer can be: - A plain function that receives the latest snapshot - An observer object whose `.next(snapshot)` method receives the latest snapshot #### Example 1 ```javascript // Observer as a plain function const subscription = actor.subscribe((snapshot) => { console.log(snapshot); }); ``` #### Example 2 ```javascript // Observer as an object const subscription = actor.subscribe({ next(snapshot) { console.log(snapshot); }, error(err) { // ... }, complete() { // ... } }); ``` The return value of `actor.subscribe(observer)` is a subscription object that has an `.unsubscribe()` method. You can call `subscription.unsubscribe()` to unsubscribe the observer: #### Example 3 ```javascript const subscription = actor.subscribe((snapshot) => { // ... }); // Unsubscribe the observer subscription.unsubscribe(); ``` When the actor is stopped, all of its observers will automatically be unsubscribed. ### method toJSON ```javascript toJSON: () => { xstate$$type: number; id: string }; ``` * Serializes the actor's state for debugging or persistence. ``` -------------------------------- ### Get Initial State Machine Snapshot (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Retrieves the initial snapshot of the state machine, providing the starting state with a reference to the actor scope. It can optionally accept an input value. ```typescript getInitialSnapshot: ( actorScope: ActorScope< MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >, TEvent, AnyActorSystem, TEmitted >, input?: TInput ) => MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >; ``` -------------------------------- ### Create and Use XState Callback Actor Source: https://www.jsdocs.io/package/xstate/index This example shows how to create a callback actor using `fromCallback` and then instantiate it with `createActor`. The actor is configured to log a message when it receives a specific event. It demonstrates the basic structure for defining actor logic and its associated types. ```javascript import { fromCallback, createActor } from 'xstate'; // The events the actor receives. type Event = { type: 'someEvent' }; // The actor's input. type Input = { name: string }; // Actor logic that logs whenever it receives an event of type `someEvent`. const logic = fromCallback(({ self, input, receive }) => { self; // ^? CallbackActorRef receive((event) => { if (event.type === 'someEvent') { console.log(`${input.name}: received "someEvent" event`); // logs 'myActor: received "someEvent" event' } }); }); const actor = createActor(logic, { input: { name: 'myActor' } }); // ^? CallbackActorRef ``` -------------------------------- ### Get Initial Transition Result (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Provides the initial snapshot and any executable actions for an actor logic without a previous state. It takes the actor logic and an optional input, returning a tuple containing the snapshot and an array of actions to be executed. ```typescript initialTransition: ( logic: T, ...[input]: undefined extends InputFrom ? [input?: InputFrom] : [input: InputFrom] ) => [SnapshotFrom, ExecutableActionsFrom[]]; ``` -------------------------------- ### Example Usage of getNextSnapshot (JavaScript) Source: https://www.jsdocs.io/package/xstate/index Illustrates how to use `getNextSnapshot` to determine future states. It shows calculating the next snapshot from an undefined state with a 'TIMER' event, and then again from the previous result with another 'TIMER' event, demonstrating state progression. ```javascript import { getNextSnapshot } from 'xstate'; import { trafficLightMachine } from './trafficLightMachine.ts'; const nextSnapshot = getNextSnapshot( trafficLightMachine, // actor logic undefined, // snapshot (or initial state if undefined) { type: 'TIMER' } ); // event object console.log(nextSnapshot.value); // => 'yellow' const nextSnapshot2 = getNextSnapshot( trafficLightMachine, // actor logic nextSnapshot, // snapshot { type: 'TIMER' } ); // event object console.log(nextSnapshot2.value); // =>'red' ``` -------------------------------- ### ActorRef Interface Source: https://www.jsdocs.io/package/xstate/index Defines the `ActorRef` interface, outlining the core methods and properties available on an actor reference, including `send`, `start`, `stop`, `on`, and `getSnapshot`. ```APIDOC ## ActorRef Interface ### Description The `ActorRef` interface represents a reference to an actor, providing methods to interact with it and subscribe to its state changes. ### Interface Definition ```typescript interface ActorRef< TSnapshot extends Snapshot, TEvent extends EventObject, TEmitted extends EventObject = EventObject > extends Subscribable, InteropObservable {} ``` ### Properties and Methods - **getPersistedSnapshot** (() => Snapshot) - Returns the persisted snapshot of the actor. - **getSnapshot** (() => TSnapshot) - Returns the current snapshot of the actor. - **id** (string) - The unique identifier for this actor relative to its parent. - **on** ((type, handler) => Subscription) - Registers a listener for specific emitted event types. - **send** ((event: TEvent) => void) - Sends an event to the actor. - **sessionId** (string) - The session ID of the actor. - **src** (string | AnyActorLogic) - The source actor logic. - **start** (() => void) - Starts the actor. - **stop** (() => void) - Stops the actor. - **system** (AnyActorSystem) - The actor system the actor belongs to. - **toJSON** (() => any) - Optional method to serialize the actor reference. ``` -------------------------------- ### SimulatedClock Methods Source: https://www.jsdocs.io/package/xstate/index Methods for simulating time within XState, including clearing timeouts, getting the current time, and setting timeouts. ```APIDOC ## SimulatedClock Methods ### method clearTimeout ```javascript clearTimeout: (id: number) => void; ``` * Clears a previously scheduled timeout. ### method now ```javascript now: () => number; ``` * Returns the current simulated time. ### method setTimeout ```javascript setTimeout: (fn: (...args: any[]) => void, timeout: number) => number; ``` * Schedules a function to be executed after a specified delay. ``` -------------------------------- ### XState Function: createActor - Create Actor Instance Source: https://www.jsdocs.io/package/xstate/index The 'createActor' function generates a new actor instance from the provided actor logic and optional configuration. This function implicitly creates an actor system with the new actor as the root. Actors must be explicitly started using 'actor.start()' and can be stopped with 'actor.stop()'. ```javascript createActor: ( logic: TLogic, ...[options]: ConditionalRequired< [ options?: ActorOptions & { [K in RequiredActorOptionsKeys]: unknown; } ], IsNotNever> > ) => Actor; ``` ```javascript import { createActor } from 'xstate'; import { someActorLogic } from './someActorLogic.ts'; // Creating the actor, which implicitly creates an actor system with itself as the root actor const actor = createActor(someActorLogic); actor.subscribe((snapshot) => { console.log(snapshot); }); // Actors must be started by calling `actor.start()`, which will also start the actor system. actor.start(); // Actors can receive events actor.send({ type: 'someEvent' }); // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system. actor.stop(); ``` -------------------------------- ### Define Initial Transition in TypeScript Source: https://www.jsdocs.io/package/xstate/index Specifies the initial transition configuration for a state node. This is an optional property, typically used in compound or parallel states to define the starting state. ```typescript initial: InitialTransitionDefinition | undefined; ``` -------------------------------- ### Get Transition Data (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Calculates and returns the transition definition for a given snapshot and event. This method is crucial for understanding how the state machine will transition. ```typescript getTransitionData: ( snapshot: MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >, event: TEvent ) => Array>; ``` -------------------------------- ### Define Interop Observable Interface Source: https://www.jsdocs.io/package/xstate/index Defines an interface for objects that are compatible with the Observable protocol, allowing them to be subscribed to. It includes a method to get an InteropSubscribable. ```typescript interface InteropObservable {} ``` -------------------------------- ### SimulatedClock Interface Definition (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Defines the interface for a simulated clock, extending the base Clock interface. It includes methods for incrementing, setting, and starting the clock, essential for testing time-dependent logic within state machines. ```typescript interface SimulatedClock extends Clock {} ``` -------------------------------- ### Index Signature Example Source: https://www.jsdocs.io/package/xstate/index An example of an index signature, allowing any string key to map to any value. This is a flexible way to define object properties. ```typescript [key: string]: any; ``` -------------------------------- ### SetupTypes Interface Definition (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Defines the configuration types for setting up a state machine, including context, events, child actor maps, tags, input, output, emitted events, and meta information. This interface is fundamental for configuring the initial state and behavior of a machine. ```typescript interface SetupTypes, TTag extends string, TInput, TOutput, TEmitted extends EventObject, TMeta extends MetaObject> {} ``` -------------------------------- ### InitialTransitionConfig Interface Source: https://www.jsdocs.io/package/xstate/index Configuration for the initial transition of a state machine. ```APIDOC ## InitialTransitionConfig Interface ### Description Configuration for the initial transition of a state machine. ### Properties * **target** (string) - The target state for the initial transition. ``` -------------------------------- ### Action Utility: raise Source: https://www.jsdocs.io/package/xstate/index Raises an event, placing it into the internal event queue for immediate consumption by the machine in the current step. ```APIDOC ## raise ### Description Raises an event. This places the event in the internal event queue, so that the event is immediately consumed by the machine in the current step. ### Method Function Definition ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript raise( eventOrExpr: DoNotInfer | SendExpr, TEvent>, options?: RaiseActionOptions, TUsedDelay> ) ``` ### Response #### Success Response (200) - **ActionFunction** - An action function that raises the specified event. #### Response Example ```json // Returns an action function ``` ``` -------------------------------- ### StateMachine Constructor Source: https://www.jsdocs.io/package/xstate/index Constructor for creating a new StateMachine instance. ```APIDOC ## StateMachine Constructor ### constructor ```javascript constructor( config: Omit< StateNodeConfig< DoNotInfer, DoNotInfer, any, any, any, any, any, DoNotInfer, any, any >, 'output' > & { version?: string; output?: | TOutput | Mapper, TOutput, TEvent>; } & ( | { context?: InitialContext } | { context: InitialContext } ) & { schemas?: unknown }, implementations?: MachineImplementationsSimplified< TContext, TEvent, ProvidedActor, ParameterizedObject, ParameterizedObject > ); ``` * Initializes a new state machine with its configuration and implementations. #### Parameters * **config** (StateNodeConfig) - The configuration object for the state machine, including states, transitions, actions, guards, etc. * **implementations** (MachineImplementationsSimplified) - Optional implementations for actors, services, and delays used within the state machine. ``` -------------------------------- ### XState Machine Actions: entry, exit, assertEvent Source: https://www.jsdocs.io/package/xstate/index Demonstrates the use of 'entry' and 'exit' actions within an XState machine configuration. It also shows how to use 'assertEvent' to validate incoming events within these actions. These are core to defining behavior when entering or leaving states, and for ensuring events conform to expected structures. ```javascript // ... entry: ({ event }) => { assertEvent(event, 'doNothing'); // event is { type: 'doNothing' } }, // ... exit: ({ event }) => { assertEvent(event, 'greet'); // event is { type: 'greet'; message: string } assertEvent(event, ['greet', 'notify']); // event is { type: 'greet'; message: string } // or { type: 'notify'; message: string; level: 'info' | 'error' } }, ``` -------------------------------- ### Transition Definition 'source' Property in TypeScript Source: https://www.jsdocs.io/package/xstate/index The source state node from which this transition originates. It points to the `StateNode` object representing the starting state. ```typescript source: StateNode; ``` -------------------------------- ### Variable: interpret Source: https://www.jsdocs.io/package/xstate/index Creates a new Interpreter instance for the given machine with the provided options, if any. Use `createActor` instead. ```APIDOC ## Variable interpret ### Description Creates a new Interpreter instance for the given machine with the provided options, if any. #### Deprecated Use `createActor` instead ### Code ```typescript const interpret: (logic: TLogic, ...[options]: ConditionalRequired<[options?: ActorOptions & { [K in RequiredActorOptionsKeys]: unknown; }], IsNotNever>>) => Actor; ``` ``` -------------------------------- ### Actor Creation with Inspection Source: https://www.jsdocs.io/package/xstate/index Demonstrates how to create an actor with an inspect callback to monitor system events like actor creation, event sending, and snapshot emissions. ```APIDOC ## Actor Creation with Inspection ### Description This section details how to create an actor and provide an `inspect` callback function to observe various system events. The callback can handle events such as `@xstate.actor`, `@xstate.event`, and `@xstate.snapshot`. ### Method `createActor(logic, options?) ### Parameters #### Options - **inspect** (function | object) - A callback function or observer object to inspect system events. - **callback function**: Receives an `inspectionEvent` argument. - **observer object**: An object with `next`, `error`, and `complete` methods. ### Request Example (Callback Function) ```javascript import { createActor } from 'xstate'; const actor = createActor(machine, { inspect: (inspectionEvent) => { if (inspectionEvent.type === '@xstate.event') { console.log(inspectionEvent.event); } } }); ``` ### Request Example (Observer Object) ```javascript const actor = createActor(machine, { inspect: { next: (inspectionEvent) => { if (inspectionEvent.type === '@xstate.snapshot') { console.log(inspectionEvent.snapshot); } } } }); ``` ### Remarks The `inspect` callback provides insights into the actor's lifecycle and interactions within the XState system. You can filter events based on their type or the involved actor references. ``` -------------------------------- ### XState Machine Properties Source: https://www.jsdocs.io/package/xstate/index This section describes the properties available on an XState machine, including its configuration, events, definition, and more. ```APIDOC ## XState Machine Properties ### Property: `config` #### Description The raw configuration used to create the machine. #### Type ```typescript Omit< StateNodeConfig, 'output' > & { version?: string; output?: TOutput | Mapper, TOutput, TEvent>; } & ( | { context?: InitialContext } | { context: InitialContext } ) & { schemas?: unknown }; ``` ### Property: `definition` #### Description The resolved definition of the state machine. #### Type ```typescript StateMachineDefinition; ``` ### Property: `events` #### Description A list of event descriptors for the machine. #### Type ```typescript EventDescriptor[]; ``` ### Property: `id` #### Description The unique identifier of the machine. #### Type ```string; ``` ### Property: `implementations` #### Description Simplified machine implementations. #### Type ```typescript MachineImplementationsSimplified< TContext, TEvent, ProvidedActor, ParameterizedObject, ParameterizedObject >; ``` ### Property: `root` #### Description The root state node of the machine. #### Type ```typescript StateNode; ``` ### Property: `schemas` #### Description Schemas for the machine's state and events. #### Type ``` {}; ``` ### Property: `states` #### Description Configuration for the states within the machine. #### Type ```typescript StateNodesConfig; ``` ### Property: `version` #### Description The machine's version. #### Type ```string?; ``` ``` -------------------------------- ### Get Persisted State Machine Snapshot (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Returns a persisted snapshot of the current state machine state. This method is useful for serialization and saving the machine's state. ```typescript getPersistedSnapshot: ( snapshot: MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >, options?: unknown ) => Snapshot; ``` -------------------------------- ### XState ActorOptions Interface Source: https://www.jsdocs.io/package/xstate/index Configuration options for creating an actor, including clock, ID, input, and inspection callbacks. ```typescript interface ActorOptions { clock?: Clock; devTools?: never; // Deprecated, use inspect instead. id?: string; input?: InputFrom; inspect?: | Observer | ((inspectionEvent: InspectionEvent) => void); } ``` -------------------------------- ### Get State Node by ID (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Retrieves a specific state node within the state machine hierarchy using its unique ID. This allows direct access to a particular state's configuration and definition. ```typescript getStateNodeById: (stateId: string) => StateNode; ``` -------------------------------- ### Get State Nodes from State Value (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Retrieves the specific state nodes that correspond to a given state value within a state machine. This function is useful for inspecting the structure of a machine's state. ```typescript getStateNodes: ( stateNode: AnyStateNode, stateValue: StateValue ) => Array; ``` -------------------------------- ### Add jsDocs.io Badge (HTML) Source: https://www.jsdocs.io/package/xstate/index This snippet demonstrates how to embed a jsDocs.io badge in your README using HTML. The badge links to the jsDocs.io documentation for the 'xstate' package. This method provides more control over styling and placement if your README supports HTML. ```html jsDocs.io ``` -------------------------------- ### initialTransition API Source: https://www.jsdocs.io/package/xstate/index Calculates the initial transition for an actor logic, returning the initial snapshot and any actions to be executed. ```APIDOC ## `initialTransition` Function ### Description Given actor `logic` and optional `input`, returns a tuple of the `nextSnapshot` and `actions` to execute from the initial transition (no previous state). This is a pure function that does not execute `actions`. ### Method `initialTransition` ### Parameters #### Path Parameters - **logic** (AnyActorLogic) - The actor logic. - **input** (optional) - The input provided to the actor. ### Returns - `[SnapshotFrom, ExecutableActionsFrom[]]` - A tuple containing the initial snapshot and an array of executable actions. ``` -------------------------------- ### XState Function: createEmptyActor - Create Undefined Snapshot Actor Source: https://www.jsdocs.io/package/xstate/index The 'createEmptyActor' function creates an actor with an undefined snapshot. This is a utility function for creating actors that do not immediately have a defined state, often used in initial setup or specific advanced scenarios. ```javascript createEmptyActor: () => ActorRef< Snapshot, AnyEventObject, AnyEventObject >; ``` -------------------------------- ### Define Initial Transition Configuration Source: https://www.jsdocs.io/package/xstate/index Configures the initial transition of a state machine, extending the generic TransitionConfig. It specifies the target state and other transition-related properties. ```typescript interface InitialTransitionConfig< TContext extends MachineContext, TEvent extends EventObject, TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string > extends TransitionConfig< TContext, TEvent, TEvent, TActor, TAction, TGuard, TDelay, TODO, // TEmitted TODO > {} ``` -------------------------------- ### StateMachine Constructor (TypeScript) Source: https://www.jsdocs.io/package/xstate/index The constructor for the StateMachine class. It accepts configuration and optional implementations to define the state machine's behavior, initial context, and output. ```typescript constructor( config: Omit, DoNotInfer, any, any, any, any, any, DoNotInfer, any, any>, 'output'> & { version?: string; output?: TOutput | Mapper, TOutput, TEvent>; } & ( | { context?: InitialContext } | { context: InitialContext } ) & { schemas?: unknown }, implementations?: MachineImplementationsSimplified ); ``` -------------------------------- ### Actor Configuration Properties Source: https://www.jsdocs.io/package/xstate/index Details the available properties that can be provided when configuring an actor, such as logger, parent, snapshot, src, and systemId. ```APIDOC ## Actor Configuration Properties ### Description These properties allow for detailed configuration when creating or managing actors. ### Properties - **logger** (function) - Specifies the logger to be used for `log(...)` actions. Defaults to `console.log`. - **parent** (AnyActorRef) - The parent actor ref. - **snapshot** (Snapshot) - Initializes actor logic from a specific persisted internal state. Actions from machine actors will not be re-executed. Invocations will be restarted, and spawned actors will be restored recursively. Can be generated with `Actor.getPersistedSnapshot()`. - **src** (string | AnyActorLogic) - The source actor logic. - **systemId** (string) - The system ID to register this actor under. ### Remarks - The `snapshot` property is crucial for persistence and resuming actor states. Ensure the provided snapshot is compatible with the actor's logic. - Refer to https://stately.ai/docs/persistence for more details on persistence. ``` -------------------------------- ### Actor Get Persisted Snapshot Method (JavaScript) Source: https://www.jsdocs.io/package/xstate/index The `getPersistedSnapshot` method retrieves the internal state of an actor, which can be persisted. This internal state is distinct from the actor's last emitted snapshot and can be restored using `ActorOptions.state`. It's applicable to all actor types. ```javascript getPersistedSnapshot: () => Snapshot; ``` -------------------------------- ### Actor Constructor (JavaScript) Source: https://www.jsdocs.io/package/xstate/index The constructor for the `Actor` class initializes a new actor instance. It requires the actor's logic and accepts optional actor options. The logic defines the actor's behavior, while options can configure aspects like state persistence. ```javascript constructor( logic: ActorLogic, options?: ActorOptions ); ``` -------------------------------- ### Define State Machine Configuration (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Defines the configuration object for creating a state machine, including optional versioning and output mapping. It allows for either a defined or undefined context initialization. ```typescript config: Omit< StateNodeConfig< DoNotInfer, DoNotInfer, any, any, any, any, any, DoNotInfer, any, any >, 'output' > & { version?: string; output?: | TOutput | Mapper, TOutput, TEvent>; } & ( | { context?: InitialContext } | { context: InitialContext } ) & { schemas?: unknown }; ``` -------------------------------- ### Get Next Snapshot of Actor Logic (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Calculates the subsequent snapshot for a given actor logic, current snapshot, and event. If the provided snapshot is undefined, it defaults to the actor logic's initial snapshot. This function is a pure computation of the next state. ```typescript getNextSnapshot: ( actorLogic: T, snapshot: SnapshotFrom, event: EventFromLogic ) => SnapshotFrom; ``` -------------------------------- ### Actor Get Snapshot Method (JavaScript) Source: https://www.jsdocs.io/package/xstate/index The `getSnapshot` method synchronously reads an actor's last emitted value (snapshot). Note that actors like callback actors might not emit snapshots. This method is useful for inspecting the current state of an actor without waiting for events. ```javascript getSnapshot: () => SnapshotFrom; ``` -------------------------------- ### Interface for Transition Configuration in TypeScript Source: https://www.jsdocs.io/package/xstate/index Defines the configuration options for a transition within an xstate machine. This includes actions, guards, target states, and other transition-related properties. ```typescript interface TransitionConfig {} ``` -------------------------------- ### AtomicStateNodeConfig Interface Source: https://www.jsdocs.io/package/xstate/index Configuration for an atomic state node. ```APIDOC ## AtomicStateNodeConfig Interface ### Description Configuration options for an atomic state node within a machine. ### Properties - **initial** (undefined): Atomic states do not have an initial state. - **onDone** (undefined): Atomic states do not have a done state. - **parallel** (false | undefined): Atomic states are not parallel. - **states** (undefined): Atomic states do not contain nested states. ``` -------------------------------- ### toObserver Function Source: https://www.jsdocs.io/package/xstate/index Converts optional next, error, and completion handlers into an Observer object. ```APIDOC ## POST /toObserver ### Description Converts optional next, error, and completion handlers into an Observer object. ### Method POST ### Endpoint /toObserver ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **nextHandler** (Observer | ((value: T) => void)) - Optional - The handler for received values. - **errorHandler** ((error: any) => void) - Optional - The handler for errors. - **completionHandler** (() => void) - Optional - The handler for completion. ### Request Example ```json { "nextHandler": "function(value) { console.log(value); }", "errorHandler": "function(error) { console.error(error); }", "completionHandler": "function() { console.log('completed'); }" } ``` ### Response #### Success Response (200) - **observer** (Observer) - The created Observer object. #### Response Example ```json { "observer": { "next": "function(value) { console.log(value); }", "error": "function(error) { console.error(error); }", "complete": "function() { console.log('completed'); }" } } ``` ``` -------------------------------- ### ExecutableSpawnAction Interface Source: https://www.jsdocs.io/package/xstate/index Defines an action for spawning a child actor. It extends ExecutableActionObject and specifies the information and parameters required for spawning. ```APIDOC ## ExecutableSpawnAction Interface ### Description Defines an action for spawning a child actor. It extends ExecutableActionObject and specifies the information and parameters required for spawning. ### Properties * **info** (ActionArgs) - Information related to the spawn action. * **params** (object) - Parameters for spawning the actor. * **id** (string) - The ID of the spawned actor. * **actorRef** (AnyActorRef | undefined) - The reference to the actor. * **src** (string | AnyActorLogic) - The source of the actor logic. * **type** (string) - Must be set to 'xstate.spawnChild'. ``` -------------------------------- ### Inspect Actor Events with Callback Function Source: https://www.jsdocs.io/package/xstate/index Demonstrates how to use a callback function with the 'inspect' option to observe various actor events like '@xstate.actor', '@xstate.event', and '@xstate.snapshot'. This allows for real-time monitoring of actor lifecycle and communication. ```javascript import { createMachine, createActor } from 'xstate'; const machine = createMachine({ // ... }); const actor = createActor(machine, { inspect: (inspectionEvent) => { if (inspectionEvent.actorRef === actor) { // This event is for the root actor } if (inspectionEvent.type === '@xstate.actor') { console.log(inspectionEvent.actorRef); } if (inspectionEvent.type === '@xstate.event') { console.log(inspectionEvent.sourceRef); console.log(inspectionEvent.actorRef); console.log(inspectionEvent.event); } if (inspectionEvent.type === '@xstate.snapshot') { console.log(inspectionEvent.actorRef); console.log(inspectionEvent.event); console.log(inspectionEvent.snapshot); } } }); ``` -------------------------------- ### Resolve State Machine Snapshot (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Creates a machine snapshot from a configuration object, including the state value, context, and optional history, status, output, or error. This is useful for initializing or updating the machine's state. ```typescript resolveState: ( config: { value: StateValue; context?: TContext; historyValue?: HistoryValue; status?: SnapshotStatus; output?: TOutput; error?: unknown; } & ( Equals extends false ? { context: unknown } : {} ) ) => MachineSnapshot< TContext, TEvent, TChildren, TStateValue, TTag, TOutput, TMeta, TConfig >; ``` -------------------------------- ### Add jsDocs.io Badge (Markdown) Source: https://www.jsdocs.io/package/xstate/index This snippet shows how to add a jsDocs.io badge to your README using Markdown. The badge links to the jsDocs.io page for the 'xstate' package and uses a blue color scheme. Ensure your README supports Markdown image links. ```markdown [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/xstate) ``` -------------------------------- ### Provide Machine Implementations (TypeScript) Source: https://www.jsdocs.io/package/xstate/index Clones the current state machine and merges it with new implementations for actions, guards, actors, and delays. This allows for extending or overriding existing machine behaviors. ```typescript provide: ( implementations: InternalMachineImplementations< ResolvedStateMachineTypes< TContext, DoNotInfer, TActor, TAction, TGuard, TDelay, TTag, TEmitted > > ) => StateMachine< TContext, TEvent, TChildren, TActor, TAction, TGuard, TDelay, TStateValue, TTag, TInput, TOutput, TEmitted, TMeta, TConfig >; ``` -------------------------------- ### XState ActorLogic Interface Source: https://www.jsdocs.io/package/xstate/index Defines the core logic for an actor, including snapshot management, event handling, and initialization. ```typescript interface ActorLogic< in out TSnapshot extends Snapshot, in out TEvent extends EventObject, in TInput = NonReducibleUnknown, TSystem extends AnyActorSystem = AnyActorSystem, in out TEmitted extends EventObject = EventObject > { config?: unknown; getInitialSnapshot: ( actorScope: ActorScope, input: TInput ) => TSnapshot; getPersistedSnapshot: ( snapshot: TSnapshot, options?: unknown ) => Snapshot; restoreSnapshot?: ( persistedState: Snapshot, actorScope: ActorScope ) => TSnapshot; start?: ( snapshot: TSnapshot, actorScope: ActorScope ) => void; transition: ( snapshot: TSnapshot, event: TEvent, actorScope: ActorScope ) => TSnapshot; } ``` -------------------------------- ### Define Executable Spawn Action Interface Source: https://www.jsdocs.io/package/xstate/index Extends ExecutableActionObject to define a specific spawn action. It includes an 'info' property for action arguments and a 'params' property detailing the spawned actor's configuration, including its ID, actor reference, and source. ```typescript interface ExecutableSpawnAction extends ExecutableActionObject {} ```