All files / xstate/lib interpreter.js

0% Statements 0/205
0% Branches 0/71
0% Functions 0/44
0% Lines 0/195

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var types_1 = require("./types");
var actionTypes = require("./actionTypes");
var actions_1 = require("./actions");
var Machine_1 = require("./Machine");
var SimulatedClock = /** @class */ (function () {
    function SimulatedClock() {
        this.timeouts = new Map();
        this._now = 0;
        this._id = 0;
    }
    SimulatedClock.prototype.now = function () {
        return this._now;
    };
    SimulatedClock.prototype.getId = function () {
        return this._id++;
    };
    SimulatedClock.prototype.setTimeout = function (fn, timeout) {
        var id = this.getId();
        this.timeouts.set(id, {
            start: this.now(),
            timeout: timeout,
            fn: fn
        });
        return id;
    };
    SimulatedClock.prototype.clearTimeout = function (id) {
        this.timeouts.delete(id);
    };
    SimulatedClock.prototype.set = function (time) {
        if (this._now > time) {
            throw new Error('Unable to travel back in time');
        }
        this._now = time;
        this.flushTimeouts();
    };
    SimulatedClock.prototype.flushTimeouts = function () {
        var _this = this;
        this.timeouts.forEach(function (timeout, id) {
            if (_this.now() - timeout.start >= timeout.timeout) {
                timeout.fn.call(null);
                _this.timeouts.delete(id);
            }
        });
    };
    SimulatedClock.prototype.increment = function (ms) {
        this._now += ms;
        this.flushTimeouts();
    };
    return SimulatedClock;
}());
exports.SimulatedClock = SimulatedClock;
// tslint:disable-next-line:max-classes-per-file
var Interpreter = /** @class */ (function () {
    function Interpreter(machine, options) {
        if (options === void 0) { options = Interpreter.defaultOptions; }
        var _this = this;
        this.machine = machine;
        this.eventQueue = [];
        this.delayedEventsMap = {};
        this.activitiesMap = {};
        this.listeners = new Set();
        this.contextListeners = new Set();
        this.stopListeners = new Set();
        this.doneListeners = new Set();
        this.eventListeners = new Set();
        this.initialized = false;
        this.children = new Set();
        this.init = this.start;
        this.send = function (event) {
            var eventObject = actions_1.toEventObject(event);
            if (!_this.initialized) {
                throw new Error("Unable to send event \"" + eventObject.type + "\" to an uninitialized interpreter (ID: " + _this.machine.id + "). Event: " + JSON.stringify(event));
            }
            var nextState = _this.machine.transition(_this.state, eventObject, _this.state.context); // TODO: fixme
            _this.update(nextState, event);
            _this.flushEventQueue();
            // Forward copy of event to child interpreters
            _this.forward(eventObject);
            return nextState;
            // tslint:disable-next-line:semicolon
        };
        var resolvedOptions = __assign({}, Interpreter.defaultOptions, options);
        this.clock = resolvedOptions.clock;
        this.logger = resolvedOptions.logger;
        this.parent = resolvedOptions.parent;
    }
    Object.defineProperty(Interpreter.prototype, "initialState", {
        /**
         * The initial state of the statechart.
         */
        get: function () {
            return this.machine.initialState;
        },
        enumerable: true,
        configurable: true
    });
    Interpreter.prototype.update = function (state, event) {
        var _this = this;
        this.state = state;
        var context = this.state.context;
        var eventObject = event ? actions_1.toEventObject(event) : undefined;
        this.state.actions.forEach(function (action) {
            _this.exec(action, context, eventObject);
        }, context);
        if (eventObject) {
            this.eventListeners.forEach(function (listener) { return listener(eventObject); });
        }
        this.listeners.forEach(function (listener) { return listener(state); });
        this.contextListeners.forEach(function (ctxListener) {
            return ctxListener(_this.state.context, _this.state.history ? _this.state.history.context : undefined);
        });
        if (this.state.tree && this.state.tree.done) {
            this.doneListeners.forEach(function (listener) { return listener(state); });
            this.stop();
        }
    };
    /*
     * Adds a listener that is called whenever a state transition happens.
     * @param listener The listener to add
     */
    Interpreter.prototype.onTransition = function (listener) {
        this.listeners.add(listener);
        return this;
    };
    Interpreter.prototype.onEvent = function (listener) {
        this.eventListeners.add(listener);
        return this;
    };
    Interpreter.prototype.onChange = function (listener) {
        this.contextListeners.add(listener);
        return this;
    };
    Interpreter.prototype.onStop = function (listener) {
        this.stopListeners.add(listener);
        return this;
    };
    Interpreter.prototype.onDone = function (listener) {
        this.doneListeners.add(listener);
        return this;
    };
    /**
     * Removes a listener.
     * @param listener The listener to remove
     */
    Interpreter.prototype.off = function (listener) {
        this.listeners.delete(listener);
        return this;
    };
    Interpreter.prototype.start = function (initialState) {
        if (initialState === void 0) { initialState = this.machine.initialState; }
        this.initialized = true;
        this.update(initialState);
        return this;
    };
    Interpreter.prototype.stop = function () {
        var _this = this;
        this.listeners.forEach(function (listener) { return _this.off(listener); });
        this.stopListeners.forEach(function (listener) {
            // call listener, then remove
            listener();
            _this.stopListeners.delete(listener);
        });
        this.contextListeners.forEach(function (ctxListener) {
            return _this.contextListeners.delete(ctxListener);
        });
        this.doneListeners.forEach(function (doneListener) {
            return _this.doneListeners.delete(doneListener);
        });
        return this;
    };
    Interpreter.prototype.forward = function (event) {
        this.children.forEach(function (childInterpreter) { return childInterpreter.send(event); });
    };
    Interpreter.prototype.defer = function (sendAction) {
        var _this = this;
        return this.clock.setTimeout(function () { return _this.send(sendAction.event); }, sendAction.delay || 0);
    };
    Interpreter.prototype.cancel = function (sendId) {
        this.clock.clearTimeout(this.delayedEventsMap[sendId]);
        delete this.delayedEventsMap[sendId];
    };
    Interpreter.prototype.exec = function (action, context, event) {
        var _this = this;
        if (action.exec) {
            return action.exec(context, event);
        }
        switch (action.type) {
            case actionTypes.send:
                var sendAction = action;
                switch (sendAction.target) {
                    case types_1.SpecialTargets.Parent:
                        if (this.parent) {
                            this.parent.send(sendAction.event);
                        }
                        break;
                    default:
                        if (!sendAction.delay) {
                            this.eventQueue.push(sendAction.event);
                        }
                        else {
                            this.delayedEventsMap[sendAction.id] = this.defer(sendAction);
                        }
                        break;
                }
            case actionTypes.cancel:
                this.cancel(action.sendId);
                break;
            case actionTypes.start: {
                var activity = action
                    .activity;
                if (activity.type === types_1.ActionTypes.Invoke) {
                    var service = this.machine.options.services && activity.src
                        ? this.machine.options.services[activity.src]
                        : undefined;
                    var autoForward = !!activity.forward;
                    if (!service) {
                        console.warn("No service found for invocation '" + activity.src + "'");
                        return;
                    }
                    if (typeof service !== 'string') {
                        // TODO: try/catch here
                        var interpreter_1 = this.spawn(Machine_1.Machine(service), autoForward);
                        interpreter_1.start();
                        this.activitiesMap[activity.id] = function () {
                            _this.children.delete(interpreter_1);
                            interpreter_1.stop();
                        };
                    }
                }
                else {
                    var implementation = this.machine.options && this.machine.options.activities
                        ? this.machine.options.activities[activity.type]
                        : undefined;
                    if (!implementation) {
                        console.warn("No implementation found for activity '" + activity.type + "'");
                        return;
                    }
                    // Start implementation
                    this.activitiesMap[activity.id] = implementation(context, activity);
                }
                break;
            }
            case actionTypes.stop: {
                var activity = action.activity;
                var dispose = this.activitiesMap[activity.id];
                if (dispose) {
                    dispose();
                }
                break;
            }
            case actionTypes.log:
                var expr = action.expr ? action.expr(context, event) : undefined;
                if (action.label) {
                    this.logger(action.label, expr);
                }
                else {
                    this.logger(expr);
                }
                break;
            default:
                // tslint:disable-next-line:no-console
                console.warn("No implementation found for action type '" + action.type + "'");
                break;
        }
        return undefined;
    };
    Interpreter.prototype.spawn = function (machine, autoForward) {
        if (autoForward === void 0) { autoForward = false; }
        var childInterpreter = new Interpreter(machine, {
            parent: this
        });
        if (autoForward) {
            this.children.add(childInterpreter);
        }
        return childInterpreter;
    };
    Interpreter.prototype.flushEventQueue = function () {
        var flushedEvent = this.eventQueue.shift();
        if (flushedEvent) {
            this.send(flushedEvent);
        }
    };
    // TODO: fixme
    Interpreter.defaultOptions = {
        clock: { setTimeout: setTimeout, clearTimeout: clearTimeout },
        logger: global.console.log.bind(console)
    };
    Interpreter.interpret = interpret;
    return Interpreter;
}());
exports.Interpreter = Interpreter;
function interpret(machine, options) {
    var interpreter = new Interpreter(machine, options);
    return interpreter;
}
exports.interpret = interpret;