xstate 4.19.2 → 4.22.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.
@@ -1,6 +1,5 @@
1
- import { StateMachine, Event, EventObject, DefaultContext, StateSchema, StateValue, InterpreterOptions, SingleOrArray, DoneEvent, MachineOptions, SCXML, EventData, Observer, Spawnable, Typestate } from './types';
1
+ import { StateMachine, Event, EventObject, DefaultContext, StateSchema, StateValue, InterpreterOptions, SingleOrArray, DoneEvent, MachineOptions, SCXML, EventData, Observer, Spawnable, Typestate, ActorRef, ActorRefFrom, Behavior, Subscription } from './types';
2
2
  import { State } from './State';
3
- import { ActorRefFrom, SpawnedActorRef, Subscription } from '.';
4
3
  export declare type StateListener<TContext, TEvent extends EventObject, TStateSchema extends StateSchema<TContext> = any, TTypestate extends Typestate<TContext> = {
5
4
  value: any;
6
5
  context: TContext;
@@ -25,7 +24,7 @@ export declare enum InterpreterStatus {
25
24
  export declare class Interpreter<TContext, TStateSchema extends StateSchema = any, TEvent extends EventObject = EventObject, TTypestate extends Typestate<TContext> = {
26
25
  value: any;
27
26
  context: TContext;
28
- }> implements SpawnedActorRef<TEvent, State<TContext, TEvent, TStateSchema, TTypestate>> {
27
+ }> implements ActorRef<TEvent, State<TContext, TEvent, TStateSchema, TTypestate>> {
29
28
  machine: StateMachine<TContext, TStateSchema, TEvent, TTypestate>;
30
29
  /**
31
30
  * The default interpreter options:
@@ -64,7 +63,7 @@ export declare class Interpreter<TContext, TStateSchema extends StateSchema = an
64
63
  * The globally unique process ID for this invocation.
65
64
  */
66
65
  sessionId: string;
67
- children: Map<string | number, SpawnedActorRef<any>>;
66
+ children: Map<string | number, ActorRef<any>>;
68
67
  private forwardTo;
69
68
  private devTools?;
70
69
  /**
@@ -165,12 +164,13 @@ export declare class Interpreter<TContext, TStateSchema extends StateSchema = an
165
164
  private exec;
166
165
  private removeChild;
167
166
  private stopChild;
168
- spawn(entity: Spawnable, name: string, options?: SpawnOptions): SpawnedActorRef<any>;
167
+ spawn(entity: Spawnable, name: string, options?: SpawnOptions): ActorRef<any>;
169
168
  spawnMachine<TChildContext, TChildStateSchema, TChildEvent extends EventObject>(machine: StateMachine<TChildContext, TChildStateSchema, TChildEvent>, options?: {
170
169
  id?: string;
171
170
  autoForward?: boolean;
172
171
  sync?: boolean;
173
- }): SpawnedActorRef<TChildEvent, State<TChildContext, TChildEvent>>;
172
+ }): ActorRef<TChildEvent, State<TChildContext, TChildEvent>>;
173
+ private spawnBehavior;
174
174
  private spawnPromise;
175
175
  private spawnCallback;
176
176
  private spawnObservable;
@@ -183,8 +183,9 @@ export declare class Interpreter<TContext, TStateSchema extends StateSchema = an
183
183
  };
184
184
  getSnapshot(): State<TContext, TEvent, TStateSchema, TTypestate>;
185
185
  }
186
+ export declare function spawn<T extends Behavior<any, any>>(entity: T, nameOrOptions?: string | SpawnOptions): ActorRefFrom<T>;
186
187
  export declare function spawn<TC, TE extends EventObject>(entity: StateMachine<TC, any, TE>, nameOrOptions?: string | SpawnOptions): ActorRefFrom<StateMachine<TC, any, TE>>;
187
- export declare function spawn(entity: Spawnable, nameOrOptions?: string | SpawnOptions): SpawnedActorRef<any>;
188
+ export declare function spawn(entity: Spawnable, nameOrOptions?: string | SpawnOptions): ActorRef<any>;
188
189
  /**
189
190
  * Creates a new Interpreter instance for the given machine with the provided options, if any.
190
191
  *
package/es/interpreter.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { __values, __assign, __spreadArray, __read } from './_virtual/_tslib.js';
2
2
  import { IS_PRODUCTION } from './environment.js';
3
- import { warn, mapContext, isFunction, keys, toSCXMLEvent, toInvokeSource, isPromiseLike, isObservable, isMachine, reportUnhandledExceptionOnInvocation, symbolObservable, isArray, toEventObject, isString, isActor, uniqueId, toObserver } from './utils.js';
3
+ import { warn, mapContext, isFunction, keys, toSCXMLEvent, toInvokeSource, isMachine, isPromiseLike, isObservable, isBehavior, reportUnhandledExceptionOnInvocation, symbolObservable, isArray, toEventObject, isString, isActor, uniqueId, toObserver } from './utils.js';
4
4
  import { ActionTypes, SpecialTargets } from './types.js';
5
5
  import { isInFinalState } from './stateUtils.js';
6
6
  import { errorPlatform, log, stop, start, cancel, send, update, error as error$1 } from './actionTypes.js';
@@ -11,6 +11,7 @@ import { isSpawnedActor, createDeferredActor } from './Actor.js';
11
11
  import { Scheduler } from './scheduler.js';
12
12
  import { registry } from './registry.js';
13
13
  import { registerService, getGlobal } from './devTools.js';
14
+ import { spawnBehavior } from './behaviors.js';
14
15
  var DEFAULT_SPAWN_OPTIONS = {
15
16
  sync: false,
16
17
  autoForward: false
@@ -830,24 +831,32 @@ function () {
830
831
  }
831
832
 
832
833
  var resolvedData = data ? mapContext(data, context, _event) : undefined;
834
+
835
+ if (typeof serviceCreator === 'string') {
836
+ // TODO: warn
837
+ return;
838
+ }
839
+
833
840
  var source = isFunction(serviceCreator) ? serviceCreator(context, _event.data, {
834
841
  data: resolvedData,
835
842
  src: invokeSource
836
843
  }) : serviceCreator;
837
844
 
838
- if (isPromiseLike(source)) {
839
- this.spawnPromise(Promise.resolve(source), id);
840
- } else if (isFunction(source)) {
841
- this.spawnCallback(source, id);
842
- } else if (isObservable(source)) {
843
- this.spawnObservable(source, id);
844
- } else if (isMachine(source)) {
845
- // TODO: try/catch here
846
- this.spawnMachine(resolvedData ? source.withContext(resolvedData) : source, {
847
- id: id,
845
+ if (!source) {
846
+ // TODO: warn?
847
+ return;
848
+ }
849
+
850
+ var options = void 0;
851
+
852
+ if (isMachine(source)) {
853
+ source = resolvedData ? source.withContext(resolvedData) : source;
854
+ options = {
848
855
  autoForward: autoForward
849
- });
850
- } else ;
856
+ };
857
+ }
858
+
859
+ this.spawn(source, id, options);
851
860
  } else {
852
861
  this.spawnActivity(activity);
853
862
  }
@@ -917,6 +926,8 @@ function () {
917
926
  return this.spawnMachine(entity, __assign(__assign({}, options), {
918
927
  id: name
919
928
  }));
929
+ } else if (isBehavior(entity)) {
930
+ return this.spawnBehavior(entity, name);
920
931
  } else {
921
932
  throw new Error("Unable to spawn entity \"" + name + "\" of type \"" + typeof entity + "\".");
922
933
  }
@@ -962,11 +973,20 @@ function () {
962
973
  return actor;
963
974
  };
964
975
 
976
+ Interpreter.prototype.spawnBehavior = function (behavior, id) {
977
+ var actorRef = spawnBehavior(behavior, {
978
+ id: id,
979
+ parent: this
980
+ });
981
+ this.children.set(id, actorRef);
982
+ return actorRef;
983
+ };
984
+
965
985
  Interpreter.prototype.spawnPromise = function (promise, id) {
966
986
  var _this = this;
967
987
 
968
988
  var canceled = false;
969
- var resolvedData = undefined;
989
+ var resolvedData;
970
990
  promise.then(function (response) {
971
991
  if (!canceled) {
972
992
  resolvedData = response;
@@ -1060,7 +1080,7 @@ function () {
1060
1080
  var canceled = false;
1061
1081
  var receivers = new Set();
1062
1082
  var listeners = new Set();
1063
- var emitted = undefined;
1083
+ var emitted;
1064
1084
 
1065
1085
  var receive = function (e) {
1066
1086
  emitted = e;
@@ -1131,7 +1151,7 @@ function () {
1131
1151
  Interpreter.prototype.spawnObservable = function (source, id) {
1132
1152
  var _this = this;
1133
1153
 
1134
- var emitted = undefined;
1154
+ var emitted;
1135
1155
  var subscription = source.subscribe(function (value) {
1136
1156
  emitted = value;
1137
1157
 
@@ -1263,6 +1283,10 @@ function () {
1263
1283
  };
1264
1284
 
1265
1285
  Interpreter.prototype.getSnapshot = function () {
1286
+ if (this.status === InterpreterStatus.NotStarted) {
1287
+ return this.initialState;
1288
+ }
1289
+
1266
1290
  return this._state;
1267
1291
  };
1268
1292
  /**
package/es/model.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AssignAction, Assigner, PropertyAssigner, ExtractEvent, EventObject } from './types';
1
+ import type { AssignAction, Assigner, PropertyAssigner, ExtractEvent, EventObject, MachineConfig, StateMachine, MachineOptions } from './types';
2
2
  declare type AnyFunction = (...args: any[]) => any;
3
3
  declare type Cast<A1 extends any, A2 extends any> = A1 extends A2 ? A1 : A2;
4
4
  declare type Compute<A extends any> = {
@@ -10,6 +10,7 @@ export interface Model<TContext, TEvent extends EventObject, TModelCreators = vo
10
10
  assign: <TEventType extends TEvent['type'] = TEvent['type']>(assigner: Assigner<TContext, ExtractEvent<TEvent, TEventType>> | PropertyAssigner<TContext, ExtractEvent<TEvent, TEventType>>, eventType?: TEventType) => AssignAction<TContext, ExtractEvent<TEvent, TEventType>>;
11
11
  events: Prop<TModelCreators, 'events'>;
12
12
  reset: () => AssignAction<TContext, any>;
13
+ createMachine: (config: MachineConfig<TContext, any, TEvent>, implementations?: Partial<MachineOptions<TContext, TEvent>>) => StateMachine<TContext, any, TEvent, any>;
13
14
  }
14
15
  export declare type ModelContextFrom<TModel extends Model<any, any, any>> = TModel extends Model<infer TContext, any, any> ? TContext : never;
15
16
  export declare type ModelEventsFrom<TModel extends Model<any, any, any>> = TModel extends Model<any, infer TEvent, any> ? TEvent : never;
@@ -10,5 +10,6 @@ export declare function getValue<TC, TE extends EventObject>(rootNode: StateNode
10
10
  export declare function has<T>(iterable: Iterable<T>, item: T): boolean;
11
11
  export declare function nextEvents<TC, TE extends EventObject>(configuration: Array<StateNode<TC, any, TE>>): Array<TE['type']>;
12
12
  export declare function isInFinalState<TC, TE extends EventObject>(configuration: Array<StateNode<TC, any, TE, any>>, stateNode: StateNode<TC, any, TE, any>): boolean;
13
+ export declare function getMeta(configuration?: StateNode[]): Record<string, any>;
13
14
  export {};
14
15
  //# sourceMappingURL=stateUtils.d.ts.map
package/es/stateUtils.js CHANGED
@@ -247,4 +247,18 @@ function isInFinalState(configuration, stateNode) {
247
247
  return false;
248
248
  }
249
249
 
250
- export { getAdjList, getAllStateNodes, getChildren, getConfiguration, getValue, has, isInFinalState, isLeafNode, nextEvents };
250
+ function getMeta(configuration) {
251
+ if (configuration === void 0) {
252
+ configuration = [];
253
+ }
254
+
255
+ return configuration.reduce(function (acc, stateNode) {
256
+ if (stateNode.meta !== undefined) {
257
+ acc[stateNode.id] = stateNode.meta;
258
+ }
259
+
260
+ return acc;
261
+ }, {});
262
+ }
263
+
264
+ export { getAdjList, getAllStateNodes, getChildren, getConfiguration, getMeta, getValue, has, isInFinalState, isLeafNode, nextEvents };
package/es/types.d.ts CHANGED
@@ -134,7 +134,7 @@ export interface PayloadSender<TEvent extends EventObject> {
134
134
  <K extends TEvent['type']>(eventType: K, payload: NeverIfEmpty<ExtractExtraParameters<TEvent, K>>): void;
135
135
  }
136
136
  export declare type Receiver<TEvent extends EventObject> = (listener: (event: TEvent) => void) => void;
137
- export declare type InvokeCallback<TEvent extends EventObject = AnyEventObject> = (callback: Sender<TEvent>, onReceive: Receiver<TEvent>) => any;
137
+ export declare type InvokeCallback<TEvent extends EventObject = AnyEventObject, TSentEvent extends EventObject = AnyEventObject> = (callback: Sender<TSentEvent>, onReceive: Receiver<TEvent>) => (() => void) | Promise<any> | void;
138
138
  export interface InvokeMeta {
139
139
  data: any;
140
140
  src: InvokeSourceDefinition;
@@ -152,7 +152,7 @@ export interface InvokeMeta {
152
152
  * @param context The current machine `context`
153
153
  * @param event The event that invoked the service
154
154
  */
155
- export declare type InvokeCreator<TContext, TEvent extends EventObject = AnyEventObject, TFinalContext = any> = (context: TContext, event: TEvent, meta: InvokeMeta) => PromiseLike<TFinalContext> | StateMachine<TFinalContext, any, any> | Subscribable<EventObject> | InvokeCallback<TEvent>;
155
+ export declare type InvokeCreator<TContext, TEvent extends EventObject, TFinalContext = any> = (context: TContext, event: TEvent, meta: InvokeMeta) => PromiseLike<TFinalContext> | StateMachine<TFinalContext, any, any> | Subscribable<EventObject> | InvokeCallback<any, TEvent> | Behavior<any>;
156
156
  export interface InvokeDefinition<TContext, TEvent extends EventObject> extends ActivityDefinition<TContext, TEvent> {
157
157
  /**
158
158
  * The source of the machine to be invoked, or the machine itself.
@@ -490,6 +490,8 @@ export interface StateMachine<TContext, TStateSchema extends StateSchema, TEvent
490
490
  }> extends StateNode<TContext, TStateSchema, TEvent, TTypestate> {
491
491
  id: string;
492
492
  states: StateNode<TContext, TStateSchema, TEvent>['states'];
493
+ withConfig(options: Partial<MachineOptions<TContext, TEvent>>, context?: TContext): StateMachine<TContext, TStateSchema, TEvent, TTypestate>;
494
+ withContext(context: TContext): StateMachine<TContext, TStateSchema, TEvent, TTypestate>;
493
495
  }
494
496
  export declare type StateFrom<TMachine extends StateMachine<any, any, any>> = ReturnType<TMachine['transition']>;
495
497
  export interface ActionMap<TContext, TEvent extends EventObject> {
@@ -876,23 +878,42 @@ export interface Subscribable<T> {
876
878
  subscribe(observer: Observer<T>): Subscription;
877
879
  subscribe(next: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
878
880
  }
879
- export declare type Spawnable = StateMachine<any, any, any> | Promise<any> | InvokeCallback | Subscribable<any>;
881
+ export declare type Spawnable = StateMachine<any, any, any> | PromiseLike<any> | InvokeCallback | Subscribable<any> | Behavior<any>;
880
882
  export declare type ExtractEvent<TEvent extends EventObject, TEventType extends TEvent['type']> = TEvent extends {
881
883
  type: TEventType;
882
884
  } ? TEvent : never;
885
+ export interface BaseActorRef<TEvent extends EventObject> {
886
+ send: (event: TEvent) => void;
887
+ }
883
888
  export interface ActorRef<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> {
884
889
  send: Sender<TEvent>;
885
- }
886
- export interface SpawnedActorRef<TEvent extends EventObject, TEmitted = any> extends ActorRef<TEvent, TEmitted> {
887
890
  id: string;
888
891
  getSnapshot: () => TEmitted | undefined;
889
892
  stop?: () => void;
890
893
  toJSON?: () => any;
891
894
  }
892
- export declare type ActorRefFrom<T extends StateMachine<any, any, any> | Promise<any>> = T extends StateMachine<infer TContext, any, infer TEvent, infer TTypestate> ? SpawnedActorRef<TEvent, State<TContext, TEvent, any, TTypestate>> & {
895
+ /**
896
+ * @deprecated Use `ActorRef` instead.
897
+ */
898
+ export declare type SpawnedActorRef<TEvent extends EventObject, TEmitted = any> = ActorRef<TEvent, TEmitted>;
899
+ export declare type ActorRefFrom<T extends StateMachine<any, any, any> | Promise<any> | Behavior<any>> = T extends StateMachine<infer TContext, any, infer TEvent, infer TTypestate> ? ActorRef<TEvent, State<TContext, TEvent, any, TTypestate>> & {
900
+ /**
901
+ * @deprecated Use `.getSnapshot()` instead.
902
+ */
893
903
  state: State<TContext, TEvent, any, TTypestate>;
894
- } : T extends Promise<infer U> ? SpawnedActorRef<never, U> : never;
904
+ } : T extends Promise<infer U> ? ActorRef<never, U> : T extends Behavior<infer TEvent, infer TEmitted> ? ActorRef<TEvent, TEmitted> : never;
895
905
  export declare type AnyInterpreter = Interpreter<any, any, any, any>;
896
906
  export declare type InterpreterFrom<T extends StateMachine<any, any, any, any>> = T extends StateMachine<infer TContext, infer TStateSchema, infer TEvent, infer TTypestate> ? Interpreter<TContext, TStateSchema, TEvent, TTypestate> : never;
907
+ export interface ActorContext<TEvent extends EventObject, TEmitted> {
908
+ parent?: ActorRef<any, any>;
909
+ self: ActorRef<TEvent, TEmitted>;
910
+ id: string;
911
+ observers: Set<Observer<TEmitted>>;
912
+ }
913
+ export interface Behavior<TEvent extends EventObject, TEmitted = any> {
914
+ transition: (state: TEmitted, event: TEvent, actorCtx: ActorContext<TEvent, TEmitted>) => TEmitted;
915
+ initialState: TEmitted;
916
+ start?: (actorCtx: ActorContext<TEvent, TEmitted>) => TEmitted;
917
+ }
897
918
  export {};
898
919
  //# sourceMappingURL=types.d.ts.map
package/es/utils.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { Event, StateValue, ActionType, Action, EventObject, PropertyMapper, Mapper, EventType, HistoryValue, AssignAction, Condition, Subscribable, StateMachine, ConditionPredicate, SCXML, StateLike, EventData, TransitionConfig, TransitionConfigTarget, NullEvent, SingleOrArray, Guard, InvokeSourceDefinition } from './types';
1
+ import { Event, StateValue, ActionType, Action, EventObject, PropertyMapper, Mapper, EventType, HistoryValue, AssignAction, Condition, Subscribable, StateMachine, ConditionPredicate, SCXML, StateLike, EventData, TransitionConfig, TransitionConfigTarget, NullEvent, SingleOrArray, Guard, InvokeSourceDefinition, Observer, Behavior } from './types';
2
2
  import { StateNode } from './StateNode';
3
- import { Observer, State } from '.';
3
+ import { State } from './State';
4
4
  import { Actor } from './Actor';
5
5
  export declare function keys<T extends object>(value: T): Array<keyof T & string>;
6
6
  export declare function matchesState(parentStateId: StateValue, childStateId: StateValue, delimiter?: string): boolean;
@@ -40,6 +40,7 @@ export declare function toArray<T>(value: T[] | T | undefined): T[];
40
40
  export declare function mapContext<TContext, TEvent extends EventObject>(mapper: Mapper<TContext, TEvent, any> | PropertyMapper<TContext, TEvent, any>, context: TContext, _event: SCXML.Event<TEvent>): any;
41
41
  export declare function isBuiltInEvent(eventType: EventType): boolean;
42
42
  export declare function isPromiseLike(value: any): value is PromiseLike<any>;
43
+ export declare function isBehavior(value: any): value is Behavior<any, any>;
43
44
  export declare function partition<T, A extends T, B extends T>(items: T[], predicate: (item: T) => item is A): [A[], B[]];
44
45
  export declare function updateHistoryStates(hist: HistoryValue, stateValue: StateValue): Record<string, HistoryValue | undefined>;
45
46
  export declare function updateHistoryValue(hist: HistoryValue, stateValue: StateValue): HistoryValue;
package/es/utils.js CHANGED
@@ -301,6 +301,10 @@ function isPromiseLike(value) {
301
301
  return false;
302
302
  }
303
303
 
304
+ function isBehavior(value) {
305
+ return value !== null && typeof value === 'object' && 'transition' in value && typeof value.transition === 'function';
306
+ }
307
+
304
308
  function partition(items, predicate) {
305
309
  var e_6, _a;
306
310
 
@@ -617,4 +621,4 @@ function toObserver(nextHandler, errorHandler, completionHandler) {
617
621
  };
618
622
  }
619
623
 
620
- export { evaluateGuard, flatten, getEventType, isActor, isArray, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isStateLike, isString, keys, mapContext, mapFilterValues, mapValues, matchesState, nestedPath, normalizeTarget, partition, path, pathToStateValue, reportUnhandledExceptionOnInvocation, symbolObservable, toArray, toArrayStrict, toEventObject, toGuard, toInvokeSource, toObserver, toSCXMLEvent, toStatePath, toStatePaths, toStateValue, toTransitionConfigArray, uniqueId, updateContext, updateHistoryStates, updateHistoryValue, warn };
624
+ export { evaluateGuard, flatten, getEventType, isActor, isArray, isBehavior, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isStateLike, isString, keys, mapContext, mapFilterValues, mapValues, matchesState, nestedPath, normalizeTarget, partition, path, pathToStateValue, reportUnhandledExceptionOnInvocation, symbolObservable, toArray, toArrayStrict, toEventObject, toGuard, toInvokeSource, toObserver, toSCXMLEvent, toStatePath, toStatePaths, toStateValue, toTransitionConfigArray, uniqueId, updateContext, updateHistoryStates, updateHistoryValue, warn };
package/lib/Actor.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { EventObject, Subscribable, InvokeDefinition, AnyEventObject, StateMachine, Spawnable, SCXML } from './types';
2
- import { ActorRef, SpawnedActorRef } from '.';
2
+ import { ActorRef, BaseActorRef } from '.';
3
3
  export interface Actor<TContext = any, TEvent extends EventObject = AnyEventObject> extends Subscribable<TContext> {
4
4
  id: string;
5
5
  send: (event: TEvent) => any;
@@ -11,15 +11,16 @@ export interface Actor<TContext = any, TEvent extends EventObject = AnyEventObje
11
11
  state?: any;
12
12
  deferred?: boolean;
13
13
  }
14
- export declare function createNullActor(id: string): SpawnedActorRef<any>;
14
+ export declare function createNullActor(id: string): ActorRef<any>;
15
15
  /**
16
16
  * Creates a deferred actor that is able to be invoked given the provided
17
17
  * invocation information in its `.meta` value.
18
18
  *
19
19
  * @param invokeDefinition The meta information needed to invoke the actor.
20
20
  */
21
- export declare function createInvocableActor<TC, TE extends EventObject>(invokeDefinition: InvokeDefinition<TC, TE>, machine: StateMachine<TC, any, TE, any>, context: TC, _event: SCXML.Event<TE>): SpawnedActorRef<any>;
22
- export declare function createDeferredActor(entity: Spawnable, id: string, data?: any): SpawnedActorRef<any, undefined>;
21
+ export declare function createInvocableActor<TC, TE extends EventObject>(invokeDefinition: InvokeDefinition<TC, TE>, machine: StateMachine<TC, any, TE, any>, context: TC, _event: SCXML.Event<TE>): ActorRef<any>;
22
+ export declare function createDeferredActor(entity: Spawnable, id: string, data?: any): ActorRef<any, undefined>;
23
23
  export declare function isActor(item: any): item is ActorRef<any>;
24
- export declare function isSpawnedActor(item: any): item is SpawnedActorRef<any>;
24
+ export declare function isSpawnedActor(item: any): item is ActorRef<any>;
25
+ export declare function toActorRef<TEvent extends EventObject, TEmitted = any, TActorRefLike extends BaseActorRef<TEvent> = BaseActorRef<TEvent>>(actorRefLike: TActorRefLike): ActorRef<TEvent, TEmitted>;
25
26
  //# sourceMappingURL=Actor.d.ts.map
package/lib/Actor.js CHANGED
@@ -1,6 +1,17 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isSpawnedActor = exports.isActor = exports.createDeferredActor = exports.createInvocableActor = exports.createNullActor = void 0;
14
+ exports.toActorRef = exports.isSpawnedActor = exports.isActor = exports.createDeferredActor = exports.createInvocableActor = exports.createNullActor = void 0;
4
15
  var utils_1 = require("./utils");
5
16
  var serviceScope = require("./serviceScope");
6
17
  function createNullActor(id) {
@@ -44,8 +55,8 @@ function createDeferredActor(entity, id, data) {
44
55
  tempActor.deferred = true;
45
56
  if (utils_1.isMachine(entity)) {
46
57
  // "mute" the existing service scope so potential spawned actors within the `.initialState` stay deferred here
47
- // @ts-ignore
48
- tempActor.state = serviceScope.provide(undefined, function () { return (data ? entity.withContext(data) : entity).initialState; });
58
+ var initialState_1 = (tempActor.state = serviceScope.provide(undefined, function () { return (data ? entity.withContext(data) : entity).initialState; }));
59
+ tempActor.getSnapshot = function () { return initialState_1; };
49
60
  }
50
61
  return tempActor;
51
62
  }
@@ -63,3 +74,7 @@ function isSpawnedActor(item) {
63
74
  return isActor(item) && 'id' in item;
64
75
  }
65
76
  exports.isSpawnedActor = isSpawnedActor;
77
+ function toActorRef(actorRefLike) {
78
+ return __assign({ subscribe: function () { return ({ unsubscribe: function () { return void 0; } }); }, id: 'anonymous', getSnapshot: function () { return undefined; } }, actorRefLike);
79
+ }
80
+ exports.toActorRef = toActorRef;
package/lib/Machine.d.ts CHANGED
@@ -1,13 +1,18 @@
1
1
  import { StateMachine, MachineOptions, DefaultContext, MachineConfig, StateSchema, EventObject, AnyEventObject, Typestate } from './types';
2
2
  import { Model, ModelContextFrom, ModelEventsFrom } from './model';
3
+ /**
4
+ * @deprecated Use `createMachine(...)` instead.
5
+ */
3
6
  export declare function Machine<TContext = any, TEvent extends EventObject = AnyEventObject>(config: MachineConfig<TContext, any, TEvent>, options?: Partial<MachineOptions<TContext, TEvent>>, initialContext?: TContext): StateMachine<TContext, any, TEvent>;
4
7
  export declare function Machine<TContext = DefaultContext, TStateSchema extends StateSchema = any, TEvent extends EventObject = AnyEventObject>(config: MachineConfig<TContext, TStateSchema, TEvent>, options?: Partial<MachineOptions<TContext, TEvent>>, initialContext?: TContext): StateMachine<TContext, TStateSchema, TEvent>;
5
8
  export declare function createMachine<TModel extends Model<any, any, any>, TContext = ModelContextFrom<TModel>, TEvent extends EventObject = ModelEventsFrom<TModel>, TTypestate extends Typestate<TContext> = {
6
9
  value: any;
7
10
  context: TContext;
8
- }>(config: MachineConfig<TContext, any, TEvent>, options?: Partial<MachineOptions<TContext, TEvent>>): StateMachine<TContext, any, TEvent, TTypestate>;
11
+ }>(config: MachineConfig<TContext, any, TEvent> & {
12
+ context: TContext;
13
+ }, options?: Partial<MachineOptions<TContext, TEvent>>): StateMachine<TContext, any, TEvent, TTypestate>;
9
14
  export declare function createMachine<TContext, TEvent extends EventObject = AnyEventObject, TTypestate extends Typestate<TContext> = {
10
15
  value: any;
11
16
  context: TContext;
12
- }>(config: MachineConfig<TContext, any, TEvent>, options?: Partial<MachineOptions<TContext, TEvent>>): StateMachine<TContext, any, TEvent, TTypestate>;
17
+ }>(config: TContext extends Model<any, any, any> ? never : MachineConfig<TContext, any, TEvent>, options?: Partial<MachineOptions<TContext, TEvent>>): StateMachine<TContext, any, TEvent, TTypestate>;
13
18
  //# sourceMappingURL=Machine.d.ts.map
package/lib/Machine.js CHANGED
@@ -4,16 +4,10 @@ exports.createMachine = exports.Machine = void 0;
4
4
  var StateNode_1 = require("./StateNode");
5
5
  function Machine(config, options, initialContext) {
6
6
  if (initialContext === void 0) { initialContext = config.context; }
7
- var resolvedInitialContext = typeof initialContext === 'function'
8
- ? initialContext()
9
- : initialContext;
10
- return new StateNode_1.StateNode(config, options, resolvedInitialContext);
7
+ return new StateNode_1.StateNode(config, options, initialContext);
11
8
  }
12
9
  exports.Machine = Machine;
13
10
  function createMachine(config, options) {
14
- var resolvedInitialContext = typeof config.context === 'function'
15
- ? config.context()
16
- : config.context;
17
- return new StateNode_1.StateNode(config, options, resolvedInitialContext);
11
+ return new StateNode_1.StateNode(config, options);
18
12
  }
19
13
  exports.createMachine = createMachine;
package/lib/State.js CHANGED
@@ -114,7 +114,7 @@ var State = /** @class */ (function () {
114
114
  this.history = config.history;
115
115
  this.actions = config.actions || [];
116
116
  this.activities = config.activities || constants_1.EMPTY_ACTIVITY_MAP;
117
- this.meta = config.meta || {};
117
+ this.meta = stateUtils_1.getMeta(config.configuration);
118
118
  this.events = config.events || [];
119
119
  this.matches = this.matches.bind(this);
120
120
  this.toStrings = this.toStrings.bind(this);
@@ -11,7 +11,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
11
11
  /**
12
12
  * The initial extended state
13
13
  */
14
- context: Readonly<TContext>;
14
+ private _context;
15
15
  /**
16
16
  * The relative key of the state node, which represents its location in the overall state value.
17
17
  */
@@ -122,7 +122,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
122
122
  /**
123
123
  * The initial extended state
124
124
  */
125
- context?: Readonly<TContext>);
125
+ _context?: Readonly<TContext> | (() => Readonly<TContext>));
126
126
  private _init;
127
127
  /**
128
128
  * Clones this state machine with custom options and context.
@@ -130,13 +130,14 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
130
130
  * @param options Options (actions, guards, activities, services) to recursively merge with the existing options.
131
131
  * @param context Custom context (will override predefined context)
132
132
  */
133
- withConfig(options: Partial<MachineOptions<TContext, TEvent>>, context?: TContext | undefined): StateNode<TContext, TStateSchema, TEvent, TTypestate>;
133
+ withConfig(options: Partial<MachineOptions<TContext, TEvent>>, context?: TContext): StateNode<TContext, TStateSchema, TEvent, TTypestate>;
134
134
  /**
135
135
  * Clones this state machine with custom context.
136
136
  *
137
137
  * @param context Custom context (will override predefined context, not recursive)
138
138
  */
139
- withContext(context: TContext): StateNode<TContext, TStateSchema, TEvent>;
139
+ withContext(context: TContext): StateNode<TContext, TStateSchema, TEvent, TTypestate>;
140
+ get context(): TContext;
140
141
  /**
141
142
  * The well-structured state node definition.
142
143
  */
package/lib/StateNode.js CHANGED
@@ -99,13 +99,13 @@ var StateNode = /** @class */ (function () {
99
99
  /**
100
100
  * The initial extended state
101
101
  */
102
- context // TODO: this is unsafe, but we're removing it in v5 anyway
102
+ _context // TODO: this is unsafe, but we're removing it in v5 anyway
103
103
  ) {
104
104
  var _this = this;
105
- if (context === void 0) { context = undefined; }
105
+ if (_context === void 0) { _context = config.context; }
106
106
  var _a;
107
107
  this.config = config;
108
- this.context = context;
108
+ this._context = _context;
109
109
  /**
110
110
  * The order this state node appears. Corresponds to the implicit SCXML document order.
111
111
  */
@@ -255,7 +255,6 @@ var StateNode = /** @class */ (function () {
255
255
  * @param context Custom context (will override predefined context)
256
256
  */
257
257
  StateNode.prototype.withConfig = function (options, context) {
258
- if (context === void 0) { context = this.context; }
259
258
  var _a = this.options, actions = _a.actions, activities = _a.activities, guards = _a.guards, services = _a.services, delays = _a.delays;
260
259
  return new StateNode(this.config, {
261
260
  actions: __assign(__assign({}, actions), options.actions),
@@ -263,7 +262,7 @@ var StateNode = /** @class */ (function () {
263
262
  guards: __assign(__assign({}, guards), options.guards),
264
263
  services: __assign(__assign({}, services), options.services),
265
264
  delays: __assign(__assign({}, delays), options.delays)
266
- }, context);
265
+ }, context !== null && context !== void 0 ? context : this.context);
267
266
  };
268
267
  /**
269
268
  * Clones this state machine with custom context.
@@ -273,6 +272,13 @@ var StateNode = /** @class */ (function () {
273
272
  StateNode.prototype.withContext = function (context) {
274
273
  return new StateNode(this.config, this.options, context);
275
274
  };
275
+ Object.defineProperty(StateNode.prototype, "context", {
276
+ get: function () {
277
+ return utils_1.isFunction(this._context) ? this._context() : this._context;
278
+ },
279
+ enumerable: false,
280
+ configurable: true
281
+ });
276
282
  Object.defineProperty(StateNode.prototype, "definition", {
277
283
  /**
278
284
  * The well-structured state node definition.
@@ -716,7 +722,7 @@ var StateNode = /** @class */ (function () {
716
722
  var resolvedStateValue = utils_1.isString(state)
717
723
  ? this.resolve(utils_1.pathToStateValue(this.getResolvedPath(state)))
718
724
  : this.resolve(state);
719
- var resolvedContext = context ? context : this.machine.context;
725
+ var resolvedContext = context !== null && context !== void 0 ? context : this.machine.context;
720
726
  currentState = this.resolveState(State_1.State.from(resolvedStateValue, resolvedContext));
721
727
  }
722
728
  if (!environment_1.IS_PRODUCTION && _event.name === WILDCARD) {
@@ -817,12 +823,6 @@ var StateNode = /** @class */ (function () {
817
823
  : currentState
818
824
  ? currentState.configuration
819
825
  : [];
820
- var meta = resolvedConfiguration.reduce(function (acc, stateNode) {
821
- if (stateNode.meta !== undefined) {
822
- acc[stateNode.id] = stateNode.meta;
823
- }
824
- return acc;
825
- }, {});
826
826
  var isDone = stateUtils_1.isInFinalState(resolvedConfiguration, this);
827
827
  var nextState = new State_1.State({
828
828
  value: resolvedStateValue || currentState.value,
@@ -846,11 +846,6 @@ var StateNode = /** @class */ (function () {
846
846
  : currentState
847
847
  ? currentState.activities
848
848
  : {},
849
- meta: resolvedStateValue
850
- ? meta
851
- : currentState
852
- ? currentState.meta
853
- : undefined,
854
849
  events: [],
855
850
  configuration: resolvedConfiguration,
856
851
  transitions: stateTransition.transitions,
@@ -865,15 +860,27 @@ var StateNode = /** @class */ (function () {
865
860
  if (history) {
866
861
  delete history.history;
867
862
  }
868
- if (!resolvedStateValue) {
863
+ // There are transient transitions if the machine is not in a final state
864
+ // and if some of the state nodes have transient ("always") transitions.
865
+ var isTransient = !isDone &&
866
+ (this._transient ||
867
+ configuration.some(function (stateNode) {
868
+ return stateNode._transient;
869
+ }));
870
+ // If there are no enabled transitions, check if there are transient transitions.
871
+ // If there are transient transitions, continue checking for more transitions
872
+ // because an transient transition should be triggered even if there are no
873
+ // enabled transitions.
874
+ //
875
+ // If we're already working on an transient transition (by checking
876
+ // if the event is a NULL_EVENT), then stop to prevent an infinite loop.
877
+ //
878
+ // Otherwise, if there are no enabled nor transient transitions, we are done.
879
+ if (!willTransition && (!isTransient || _event.name === NULL_EVENT)) {
869
880
  return nextState;
870
881
  }
871
882
  var maybeNextState = nextState;
872
883
  if (!isDone) {
873
- var isTransient = this._transient ||
874
- configuration.some(function (stateNode) {
875
- return stateNode._transient;
876
- });
877
884
  if (isTransient) {
878
885
  maybeNextState = this.resolveRaisedTransition(maybeNextState, {
879
886
  type: actionTypes.nullEvent
@@ -0,0 +1,37 @@
1
+ import { ActorContext, ActorRef, Behavior, EventObject } from '.';
2
+ /**
3
+ * Returns an actor behavior from a reducer and its initial state.
4
+ *
5
+ * @param transition The pure reducer that returns the next state given the current state and event.
6
+ * @param initialState The initial state of the reducer.
7
+ * @returns An actor behavior
8
+ */
9
+ export declare function fromReducer<TState, TEvent extends EventObject>(transition: (state: TState, event: TEvent, actorContext: ActorContext<TEvent, TState>) => TState, initialState: TState): Behavior<TEvent, TState>;
10
+ declare type PromiseEvents<T> = {
11
+ type: 'fulfill';
12
+ data: T;
13
+ } | {
14
+ type: 'reject';
15
+ error: unknown;
16
+ };
17
+ declare type PromiseState<T> = {
18
+ status: 'pending';
19
+ data: undefined;
20
+ error: undefined;
21
+ } | {
22
+ status: 'fulfilled';
23
+ data: T;
24
+ error: undefined;
25
+ } | {
26
+ status: 'rejected';
27
+ data: undefined;
28
+ error: any;
29
+ };
30
+ export declare function fromPromise<T>(promiseFn: () => Promise<T>): Behavior<PromiseEvents<T>, PromiseState<T>>;
31
+ interface SpawnBehaviorOptions {
32
+ id?: string;
33
+ parent?: ActorRef<any>;
34
+ }
35
+ export declare function spawnBehavior<TEvent extends EventObject, TEmitted>(behavior: Behavior<TEvent, TEmitted>, options?: SpawnBehaviorOptions): ActorRef<TEvent, TEmitted>;
36
+ export {};
37
+ //# sourceMappingURL=behaviors.d.ts.map