xstate 4.30.4 → 4.30.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es/json.js ADDED
@@ -0,0 +1,86 @@
1
+ import { mapValues, isFunction } from './utils.js';
2
+
3
+ function stringifyFunction(fn) {
4
+ return {
5
+ $function: fn.toString()
6
+ };
7
+ }
8
+
9
+ function getStateNodeId(stateNode) {
10
+ return "#".concat(stateNode.id);
11
+ } // derive config from machine
12
+
13
+
14
+ function machineToJSON(stateNode) {
15
+ var config = {
16
+ type: stateNode.type,
17
+ initial: stateNode.initial === undefined ? undefined : String(stateNode.initial),
18
+ id: stateNode.id,
19
+ key: stateNode.key,
20
+ entry: stateNode.onEntry,
21
+ exit: stateNode.onExit,
22
+ on: mapValues(stateNode.on, function (transition) {
23
+ return transition.map(function (t) {
24
+ return {
25
+ target: t.target ? t.target.map(getStateNodeId) : [],
26
+ source: getStateNodeId(t.source),
27
+ actions: t.actions,
28
+ cond: t.cond,
29
+ eventType: t.eventType
30
+ };
31
+ });
32
+ }),
33
+ invoke: stateNode.invoke,
34
+ states: {}
35
+ };
36
+ Object.values(stateNode.states).forEach(function (sn) {
37
+ config.states[sn.key] = machineToJSON(sn);
38
+ });
39
+ return config;
40
+ }
41
+ function stringify(machine) {
42
+ return JSON.stringify(machineToJSON(machine), function (_, value) {
43
+ if (isFunction(value)) {
44
+ return {
45
+ $function: value.toString()
46
+ };
47
+ }
48
+
49
+ return value;
50
+ });
51
+ }
52
+ function parse(machineString) {
53
+ var config = JSON.parse(machineString, function (_, value) {
54
+ if (typeof value === 'object' && '$function' in value) {
55
+ return new Function(value.value);
56
+ }
57
+
58
+ return value;
59
+ });
60
+ return config;
61
+ }
62
+ function jsonify(value) {
63
+ Object.defineProperty(value, 'toJSON', {
64
+ value: function () {
65
+ return mapValues(value, function (subValue) {
66
+ if (isFunction(subValue)) {
67
+ return stringifyFunction(subValue);
68
+ } else if (typeof subValue === 'object' && !Array.isArray(subValue)) {
69
+ // mostly for assignments
70
+ return mapValues(subValue, function (subSubValue) {
71
+ if (isFunction(subSubValue)) {
72
+ return stringifyFunction(subSubValue);
73
+ }
74
+
75
+ return subSubValue;
76
+ });
77
+ }
78
+
79
+ return subValue;
80
+ });
81
+ }
82
+ });
83
+ return value;
84
+ }
85
+
86
+ export { jsonify, machineToJSON, parse, stringify, stringifyFunction };
package/es/model.js ADDED
@@ -0,0 +1,50 @@
1
+ import { __assign, __spreadArray, __read } from './_virtual/_tslib.js';
2
+ import { assign } from './actions.js';
3
+ import { createMachine } from './Machine.js';
4
+ import { mapValues } from './utils.js';
5
+
6
+ function createModel(initialContext, creators) {
7
+ var eventCreators = creators === null || creators === void 0 ? void 0 : creators.events;
8
+ var actionCreators = creators === null || creators === void 0 ? void 0 : creators.actions;
9
+ var model = {
10
+ initialContext: initialContext,
11
+ assign: assign,
12
+ events: eventCreators ? mapValues(eventCreators, function (fn, eventType) {
13
+ return function () {
14
+ var args = [];
15
+
16
+ for (var _i = 0; _i < arguments.length; _i++) {
17
+ args[_i] = arguments[_i];
18
+ }
19
+
20
+ return __assign(__assign({}, fn.apply(void 0, __spreadArray([], __read(args), false))), {
21
+ type: eventType
22
+ });
23
+ };
24
+ }) : undefined,
25
+ actions: actionCreators ? mapValues(actionCreators, function (fn, actionType) {
26
+ return function () {
27
+ var args = [];
28
+
29
+ for (var _i = 0; _i < arguments.length; _i++) {
30
+ args[_i] = arguments[_i];
31
+ }
32
+
33
+ return __assign(__assign({}, fn.apply(void 0, __spreadArray([], __read(args), false))), {
34
+ type: actionType
35
+ });
36
+ };
37
+ }) : undefined,
38
+ reset: function () {
39
+ return assign(initialContext);
40
+ },
41
+ createMachine: function (config, implementations) {
42
+ return createMachine('context' in config ? config : __assign(__assign({}, config), {
43
+ context: initialContext
44
+ }), implementations);
45
+ }
46
+ };
47
+ return model;
48
+ }
49
+
50
+ export { createModel };
package/es/patterns.js ADDED
@@ -0,0 +1,48 @@
1
+ import { __assign } from './_virtual/_tslib.js';
2
+ import { toEventObject } from './utils.js';
3
+
4
+ function toggle(onState, offState, eventType) {
5
+ var _a, _b, _c;
6
+
7
+ return _a = {}, _a[onState] = {
8
+ on: (_b = {}, _b[eventType] = offState, _b)
9
+ }, _a[offState] = {
10
+ on: (_c = {}, _c[eventType] = onState, _c)
11
+ }, _a;
12
+ }
13
+ var defaultSequencePatternOptions = {
14
+ nextEvent: 'NEXT',
15
+ prevEvent: 'PREV'
16
+ };
17
+ function sequence(items, options) {
18
+ var resolvedOptions = __assign(__assign({}, defaultSequencePatternOptions), options);
19
+
20
+ var states = {};
21
+ var nextEventObject = resolvedOptions.nextEvent === undefined ? undefined : toEventObject(resolvedOptions.nextEvent);
22
+ var prevEventObject = resolvedOptions.prevEvent === undefined ? undefined : toEventObject(resolvedOptions.prevEvent);
23
+ items.forEach(function (item, i) {
24
+ var state = {
25
+ on: {}
26
+ };
27
+
28
+ if (i + 1 === items.length) {
29
+ state.type = 'final';
30
+ }
31
+
32
+ if (nextEventObject && i + 1 < items.length) {
33
+ state.on[nextEventObject.type] = items[i + 1];
34
+ }
35
+
36
+ if (prevEventObject && i > 0) {
37
+ state.on[prevEventObject.type] = items[i - 1];
38
+ }
39
+
40
+ states[item] = state;
41
+ });
42
+ return {
43
+ initial: items[0],
44
+ states: states
45
+ };
46
+ }
47
+
48
+ export { sequence, toggle };
package/es/utils.js CHANGED
@@ -1,8 +1,11 @@
1
- import { __assign, __spreadArray, __read, __values } from './_virtual/_tslib.js';
1
+ import { __values, __spreadArray, __read, __assign } from './_virtual/_tslib.js';
2
2
  import { DEFAULT_GUARD_TYPE, TARGETLESS_KEY, STATE_DELIMITER } from './constants.js';
3
3
  import { IS_PRODUCTION } from './environment.js';
4
4
 
5
5
  var _a;
6
+ function keys(value) {
7
+ return Object.keys(value);
8
+ }
6
9
  function matchesState(parentStateId, childStateId, delimiter) {
7
10
  if (delimiter === void 0) {
8
11
  delimiter = STATE_DELIMITER;
@@ -39,6 +42,13 @@ function getEventType(event) {
39
42
  throw new Error('Events must be strings or objects with a string event.type property.');
40
43
  }
41
44
  }
45
+ function getActionType(action) {
46
+ try {
47
+ return isString(action) || typeof action === 'number' ? "".concat(action) : isFunction(action) ? action.name : action.type;
48
+ } catch (e) {
49
+ throw new Error('Actions must be strings or objects with a string action.type property.');
50
+ }
51
+ }
42
52
  function toStatePath(stateId, delimiter) {
43
53
  try {
44
54
  if (isArray(stateId)) {
@@ -213,6 +223,46 @@ function toStatePaths(stateValue) {
213
223
  }));
214
224
  return result;
215
225
  }
226
+ function pathsToStateValue(paths) {
227
+ var e_4, _a;
228
+
229
+ var result = {};
230
+
231
+ if (paths && paths.length === 1 && paths[0].length === 1) {
232
+ return paths[0][0];
233
+ }
234
+
235
+ try {
236
+ for (var paths_1 = __values(paths), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {
237
+ var currentPath = paths_1_1.value;
238
+ var marker = result; // tslint:disable-next-line:prefer-for-of
239
+
240
+ for (var i = 0; i < currentPath.length; i++) {
241
+ var subPath = currentPath[i];
242
+
243
+ if (i === currentPath.length - 2) {
244
+ marker[subPath] = currentPath[i + 1];
245
+ break;
246
+ }
247
+
248
+ marker[subPath] = marker[subPath] || {};
249
+ marker = marker[subPath];
250
+ }
251
+ }
252
+ } catch (e_4_1) {
253
+ e_4 = {
254
+ error: e_4_1
255
+ };
256
+ } finally {
257
+ try {
258
+ if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);
259
+ } finally {
260
+ if (e_4) throw e_4.error;
261
+ }
262
+ }
263
+
264
+ return result;
265
+ }
216
266
  function flatten(array) {
217
267
  var _a;
218
268
 
@@ -573,4 +623,4 @@ function createInvokeId(stateNodeId, index) {
573
623
  return "".concat(stateNodeId, ":invocation[").concat(index, "]");
574
624
  }
575
625
 
576
- export { createInvokeId, evaluateGuard, flatten, getEventType, interopSymbols, isActor, isArray, isBehavior, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isStateLike, isString, 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 };
626
+ export { createInvokeId, evaluateGuard, flatten, getActionType, getEventType, interopSymbols, isActor, isArray, isBehavior, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isStateLike, isString, keys, mapContext, mapFilterValues, mapValues, matchesState, nestedPath, normalizeTarget, partition, path, pathToStateValue, pathsToStateValue, reportUnhandledExceptionOnInvocation, symbolObservable, toArray, toArrayStrict, toEventObject, toGuard, toInvokeSource, toObserver, toSCXMLEvent, toStatePath, toStatePaths, toStateValue, toTransitionConfigArray, uniqueId, updateContext, updateHistoryStates, updateHistoryValue, warn };
@@ -1,83 +1,85 @@
1
- "use strict";
2
- var __read = (this && this.__read) || function (o, n) {
3
- var m = typeof Symbol === "function" && o[Symbol.iterator];
4
- if (!m) return o;
5
- var i = m.call(o), r, ar = [], e;
6
- try {
7
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var _tslib = require('./_virtual/_tslib.js');
6
+
7
+ var SimulatedClock =
8
+ /*#__PURE__*/
9
+
10
+ /** @class */
11
+ function () {
12
+ function SimulatedClock() {
13
+ this.timeouts = new Map();
14
+ this._now = 0;
15
+ this._id = 0;
16
+ }
17
+
18
+ SimulatedClock.prototype.now = function () {
19
+ return this._now;
20
+ };
21
+
22
+ SimulatedClock.prototype.getId = function () {
23
+ return this._id++;
24
+ };
25
+
26
+ SimulatedClock.prototype.setTimeout = function (fn, timeout) {
27
+ var id = this.getId();
28
+ this.timeouts.set(id, {
29
+ start: this.now(),
30
+ timeout: timeout,
31
+ fn: fn
32
+ });
33
+ return id;
34
+ };
35
+
36
+ SimulatedClock.prototype.clearTimeout = function (id) {
37
+ this.timeouts.delete(id);
38
+ };
39
+
40
+ SimulatedClock.prototype.set = function (time) {
41
+ if (this._now > time) {
42
+ throw new Error('Unable to travel back in time');
8
43
  }
9
- catch (error) { e = { error: error }; }
10
- finally {
11
- try {
12
- if (r && !r.done && (m = i["return"])) m.call(i);
13
- }
14
- finally { if (e) throw e.error; }
15
- }
16
- return ar;
17
- };
18
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
19
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
20
- if (ar || !(i in from)) {
21
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
22
- ar[i] = from[i];
23
- }
24
- }
25
- return to.concat(ar || Array.prototype.slice.call(from));
26
- };
27
- Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.SimulatedClock = void 0;
29
- var SimulatedClock = /** @class */ (function () {
30
- function SimulatedClock() {
31
- this.timeouts = new Map();
32
- this._now = 0;
33
- this._id = 0;
34
- }
35
- SimulatedClock.prototype.now = function () {
36
- return this._now;
37
- };
38
- SimulatedClock.prototype.getId = function () {
39
- return this._id++;
40
- };
41
- SimulatedClock.prototype.setTimeout = function (fn, timeout) {
42
- var id = this.getId();
43
- this.timeouts.set(id, {
44
- start: this.now(),
45
- timeout: timeout,
46
- fn: fn
47
- });
48
- return id;
49
- };
50
- SimulatedClock.prototype.clearTimeout = function (id) {
51
- this.timeouts.delete(id);
52
- };
53
- SimulatedClock.prototype.set = function (time) {
54
- if (this._now > time) {
55
- throw new Error('Unable to travel back in time');
56
- }
57
- this._now = time;
58
- this.flushTimeouts();
59
- };
60
- SimulatedClock.prototype.flushTimeouts = function () {
61
- var _this = this;
62
- __spreadArray([], __read(this.timeouts), false).sort(function (_a, _b) {
63
- var _c = __read(_a, 2), _idA = _c[0], timeoutA = _c[1];
64
- var _d = __read(_b, 2), _idB = _d[0], timeoutB = _d[1];
65
- var endA = timeoutA.start + timeoutA.timeout;
66
- var endB = timeoutB.start + timeoutB.timeout;
67
- return endB > endA ? -1 : 1;
68
- })
69
- .forEach(function (_a) {
70
- var _b = __read(_a, 2), id = _b[0], timeout = _b[1];
71
- if (_this.now() - timeout.start >= timeout.timeout) {
72
- _this.timeouts.delete(id);
73
- timeout.fn.call(null);
74
- }
75
- });
76
- };
77
- SimulatedClock.prototype.increment = function (ms) {
78
- this._now += ms;
79
- this.flushTimeouts();
80
- };
81
- return SimulatedClock;
82
- }());
44
+
45
+ this._now = time;
46
+ this.flushTimeouts();
47
+ };
48
+
49
+ SimulatedClock.prototype.flushTimeouts = function () {
50
+ var _this = this;
51
+
52
+ _tslib.__spreadArray([], _tslib.__read(this.timeouts), false).sort(function (_a, _b) {
53
+ var _c = _tslib.__read(_a, 2);
54
+ _c[0];
55
+ var timeoutA = _c[1];
56
+
57
+ var _d = _tslib.__read(_b, 2);
58
+ _d[0];
59
+ var timeoutB = _d[1];
60
+
61
+ var endA = timeoutA.start + timeoutA.timeout;
62
+ var endB = timeoutB.start + timeoutB.timeout;
63
+ return endB > endA ? -1 : 1;
64
+ }).forEach(function (_a) {
65
+ var _b = _tslib.__read(_a, 2),
66
+ id = _b[0],
67
+ timeout = _b[1];
68
+
69
+ if (_this.now() - timeout.start >= timeout.timeout) {
70
+ _this.timeouts.delete(id);
71
+
72
+ timeout.fn.call(null);
73
+ }
74
+ });
75
+ };
76
+
77
+ SimulatedClock.prototype.increment = function (ms) {
78
+ this._now += ms;
79
+ this.flushTimeouts();
80
+ };
81
+
82
+ return SimulatedClock;
83
+ }();
84
+
83
85
  exports.SimulatedClock = SimulatedClock;
package/lib/State.js CHANGED
@@ -4,10 +4,10 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var _tslib = require('./_virtual/_tslib.js');
6
6
  var constants = require('./constants.js');
7
- var environment = require('./environment.js');
8
7
  var utils = require('./utils.js');
9
- var actions = require('./actions.js');
10
8
  var stateUtils = require('./stateUtils.js');
9
+ var actions = require('./actions.js');
10
+ var environment = require('./environment.js');
11
11
 
12
12
  function stateValuesEqual(a, b) {
13
13
  if (a === b) {
@@ -35,6 +35,11 @@ function isStateConfig(state) {
35
35
 
36
36
  return 'value' in state && '_event' in state;
37
37
  }
38
+ /**
39
+ * @deprecated Use `isStateConfig(object)` or `state instanceof State` instead.
40
+ */
41
+
42
+ var isState = isStateConfig;
38
43
  function bindActionToState(action, state) {
39
44
  var exec = action.exec;
40
45
 
@@ -219,12 +224,12 @@ function () {
219
224
  };
220
225
 
221
226
  State.prototype.toJSON = function () {
222
- var _a = this,
223
- configuration = _a.configuration,
224
- transitions = _a.transitions,
225
- tags = _a.tags,
226
- machine = _a.machine,
227
- jsonValues = _tslib.__rest(_a, ["configuration", "transitions", "tags", "machine"]);
227
+ var _a = this;
228
+ _a.configuration;
229
+ _a.transitions;
230
+ var tags = _a.tags;
231
+ _a.machine;
232
+ var jsonValues = _tslib.__rest(_a, ["configuration", "transitions", "tags", "machine"]);
228
233
 
229
234
  return _tslib.__assign(_tslib.__assign({}, jsonValues), {
230
235
  tags: Array.from(tags)
@@ -272,5 +277,6 @@ function () {
272
277
 
273
278
  exports.State = State;
274
279
  exports.bindActionToState = bindActionToState;
280
+ exports.isState = isState;
275
281
  exports.isStateConfig = isStateConfig;
276
282
  exports.stateValuesEqual = stateValuesEqual;
package/lib/StateNode.js CHANGED
@@ -3,15 +3,15 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var _tslib = require('./_virtual/_tslib.js');
6
+ var utils = require('./utils.js');
6
7
  var types = require('./types.js');
8
+ var State = require('./State.js');
7
9
  var actionTypes = require('./actionTypes.js');
8
- var constants = require('./constants.js');
9
- var environment = require('./environment.js');
10
- var utils = require('./utils.js');
11
10
  var actions = require('./actions.js');
12
- var Actor = require('./Actor.js');
11
+ var environment = require('./environment.js');
12
+ var constants = require('./constants.js');
13
13
  var stateUtils = require('./stateUtils.js');
14
- var State = require('./State.js');
14
+ var Actor = require('./Actor.js');
15
15
  var invokeUtils = require('./invokeUtils.js');
16
16
 
17
17
  var NULL_EVENT = '';
package/lib/actions.js CHANGED
@@ -5,8 +5,8 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var _tslib = require('./_virtual/_tslib.js');
6
6
  var types = require('./types.js');
7
7
  var actionTypes = require('./actionTypes.js');
8
- var environment = require('./environment.js');
9
8
  var utils = require('./utils.js');
9
+ var environment = require('./environment.js');
10
10
 
11
11
  var initEvent = /*#__PURE__*/utils.toSCXMLEvent({
12
12
  type: actionTypes.init
package/lib/behaviors.js CHANGED
@@ -2,12 +2,78 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- require('./types.js');
6
- require('./actionTypes.js');
7
- require('./environment.js');
8
- var utils = require('./utils.js');
5
+ var actions = require('./actions.js');
9
6
  var Actor = require('./Actor.js');
7
+ var utils = require('./utils.js');
8
+
9
+ /**
10
+ * Returns an actor behavior from a reducer and its initial state.
11
+ *
12
+ * @param transition The pure reducer that returns the next state given the current state and event.
13
+ * @param initialState The initial state of the reducer.
14
+ * @returns An actor behavior
15
+ */
16
+
17
+ function fromReducer(transition, initialState) {
18
+ return {
19
+ transition: transition,
20
+ initialState: initialState
21
+ };
22
+ }
23
+ function fromPromise(promiseFn) {
24
+ var initialState = {
25
+ error: undefined,
26
+ data: undefined,
27
+ status: 'pending'
28
+ };
29
+ return {
30
+ transition: function (state, event, _a) {
31
+ var parent = _a.parent,
32
+ id = _a.id,
33
+ observers = _a.observers;
10
34
 
35
+ switch (event.type) {
36
+ case 'fulfill':
37
+ parent === null || parent === void 0 ? void 0 : parent.send(actions.doneInvoke(id, event.data));
38
+ return {
39
+ error: undefined,
40
+ data: event.data,
41
+ status: 'fulfilled'
42
+ };
43
+
44
+ case 'reject':
45
+ parent === null || parent === void 0 ? void 0 : parent.send(actions.error(id, event.error));
46
+ observers.forEach(function (observer) {
47
+ observer.error(event.error);
48
+ });
49
+ return {
50
+ error: event.error,
51
+ data: undefined,
52
+ status: 'rejected'
53
+ };
54
+
55
+ default:
56
+ return state;
57
+ }
58
+ },
59
+ initialState: initialState,
60
+ start: function (_a) {
61
+ var self = _a.self;
62
+ promiseFn().then(function (data) {
63
+ self.send({
64
+ type: 'fulfill',
65
+ data: data
66
+ });
67
+ }, function (reason) {
68
+ self.send({
69
+ type: 'reject',
70
+ error: reason
71
+ });
72
+ });
73
+ return initialState;
74
+ }
75
+ };
76
+ }
11
77
  function spawnBehavior(behavior, options) {
12
78
  if (options === void 0) {
13
79
  options = {};
@@ -66,4 +132,6 @@ function spawnBehavior(behavior, options) {
66
132
  return actor;
67
133
  }
68
134
 
135
+ exports.fromPromise = fromPromise;
136
+ exports.fromReducer = fromReducer;
69
137
  exports.spawnBehavior = spawnBehavior;
package/lib/each.js CHANGED
@@ -1,15 +1,17 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.each = void 0;
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
4
5
  function each(collection, item, indexOrActions, maybeActions) {
5
- var actions = maybeActions || indexOrActions;
6
- var index = maybeActions ? indexOrActions : undefined;
7
- return {
8
- type: 'xstate.foreach',
9
- collection: collection,
10
- item: item,
11
- index: index,
12
- actions: actions
13
- };
6
+ var actions = maybeActions || indexOrActions;
7
+ var index = maybeActions ? indexOrActions : undefined;
8
+ return {
9
+ type: 'xstate.foreach',
10
+ collection: collection,
11
+ item: item,
12
+ index: index,
13
+ actions: actions
14
+ };
14
15
  }
16
+
15
17
  exports.each = each;