All files / xstate/src interpreter.ts

85.42% Statements 164/192
70.31% Branches 45/64
73.17% Functions 30/41
85.56% Lines 154/180

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 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 4231x                             1x 1x 1x                                                                           1x 39x 39x 39x 1x 21x   1x 8x   1x 8x 8x         8x   1x 10x   1x               11x 11x 13x 6x 6x       1x 11x 11x   1x     1x           1x         52x 52x 52x 52x 52x 52x 52x 52x     52x       52x   52x 52x 62x   52x         52x 52x 52x   1x       1x 1x   186x       186x 186x 186x   186x 93x     185x 136x     185x 185x             185x                 1x 41x 41x   1x       1x       1x       1x               1x 1x 1x   52x 1x 63x         50x 50x 49x   2x 2x 2x         2x     2x     2x   52x 137x 137x 1x                 136x           136x 136x     136x   136x     1x 136x   57x 57x 53x       1x 81x 81x   93x         93x 1x     92x   64x   64x   7x 7x   7x   57x     57x     57x       81x   81x   4x     4x   2x       2x   2x         2x   2x   2x   2x 1x 1x         2x       2x               2x     4x     2x 2x   2x 2x     2x       2x   2x     2x   2x     3x     3x     92x   1x           2x   2x       2x 2x     2x   1x 136x 136x       1x   1x               50x   50x    
import {
  Machine as XSMachine,
  Event,
  EventObject,
  SendAction,
  CancelAction,
  DefaultContext,
  ActionObject,
  StateSchema,
  ActivityActionObject,
  SpecialTargets,
  ActionTypes,
  Invocation
} from './types';
import { State } from './State';
import * as actionTypes from './actionTypes';
import { toEventObject } from './actions';
import { Machine } from './Machine';
 
export type StateListener = <TContext = DefaultContext>(
  state: State<TContext>
) => void;
 
export type ContextListener<TContext = DefaultContext> = (
  context: TContext,
  prevContext: TContext | undefined
) => void;
 
export type EventListener = (event: EventObject) => void;
 
export type Listener = () => void;
 
export interface Clock {
  setTimeout(fn: (...args: any[]) => void, timeout: number): number;
  clearTimeout(id: number): void;
}
 
export interface SimulatedClock extends Clock {
  start(speed: number): void;
  increment(ms: number): void;
  set(ms: number): void;
}
 
interface InterpreterOptions {
  clock: Clock;
  logger: (...args: any[]) => void;
  parent?: Interpreter<any, any, any>;
}
 
interface SimulatedTimeout {
  start: number;
  timeout: number;
  fn: (...args: any[]) => void;
}
 
export class SimulatedClock implements SimulatedClock {
  private timeouts: Map<number, SimulatedTimeout> = new Map();
  private _now: number = 0;
  private _id: number = 0;
  public now() {
    return this._now;
  }
  private getId() {
    return this._id++;
  }
  public setTimeout(fn: (...args: any[]) => void, timeout: number) {
    const id = this.getId();
    this.timeouts.set(id, {
      start: this.now(),
      timeout,
      fn
    });
    return id;
  }
  public clearTimeout(id: number) {
    this.timeouts.delete(id);
  }
  public set(time: number) {
    if (this._now > time) {
      throw new Error('Unable to travel back in time');
    }
 
    this._now = time;
    this.flushTimeouts();
  }
  private flushTimeouts() {
    this.timeouts.forEach((timeout, id) => {
      if (this.now() - timeout.start >= timeout.timeout) {
        timeout.fn.call(null);
        this.timeouts.delete(id);
      }
    });
  }
  public increment(ms: number): void {
    this._now += ms;
    this.flushTimeouts();
  }
}
 
// tslint:disable-next-line:max-classes-per-file
export class Interpreter<
  TContext,
  TStateSchema extends StateSchema = any,
  TEvents extends EventObject = EventObject
> {
  // TODO: fixme
  public static defaultOptions: InterpreterOptions = {
    clock: { setTimeout, clearTimeout },
    logger: global.console.log.bind(console)
  };
  public state: State<TContext, TEvents>;
  public eventQueue: TEvents[] = [];
  public delayedEventsMap: Record<string, number> = {};
  public activitiesMap: Record<string, any> = {};
  public listeners: Set<StateListener> = new Set();
  public contextListeners: Set<ContextListener<TContext>> = new Set();
  public stopListeners: Set<Listener> = new Set();
  public doneListeners: Set<StateListener> = new Set();
  public eventListeners: Set<EventListener> = new Set();
  public clock: Clock;
  public logger: (...args: any[]) => void;
  public initialized = false;
 
  // Actor
  public parent?: Interpreter<any>;
  private children: Set<Interpreter<any>> = new Set();
 
  constructor(
    public machine: XSMachine<TContext, TStateSchema, TEvents>,
    options: Partial<InterpreterOptions> = Interpreter.defaultOptions
  ) {
    const resolvedOptions: InterpreterOptions = {
      ...Interpreter.defaultOptions,
      ...options
    };
 
    this.clock = resolvedOptions.clock;
    this.logger = resolvedOptions.logger;
    this.parent = resolvedOptions.parent;
  }
  public static interpret = interpret;
  /**
   * The initial state of the statechart.
   */
  public get initialState(): State<TContext, TEvents> {
    return this.machine.initialState;
  }
  private update(
    state: State<TContext, TEvents>,
    event?: Event<TEvents>
  ): void {
    this.state = state;
    const { context } = this.state;
    const eventObject = event ? toEventObject(event) : undefined;
 
    this.state.actions.forEach(action => {
      this.exec(action, context, eventObject);
    }, context);
 
    if (eventObject) {
      this.eventListeners.forEach(listener => listener(eventObject));
    }
 
    this.listeners.forEach(listener => listener(state));
    this.contextListeners.forEach(ctxListener =>
      ctxListener(
        this.state.context,
        this.state.history ? this.state.history.context : undefined
      )
    );
 
    Iif (this.state.tree && this.state.tree.done) {
      this.doneListeners.forEach(listener => listener(state));
      this.stop();
    }
  }
  /*
   * Adds a listener that is called whenever a state transition happens.
   * @param listener The listener to add
   */
  public onTransition(listener: StateListener): Interpreter<TContext> {
    this.listeners.add(listener);
    return this;
  }
  public onEvent(listener: EventListener): Interpreter<TContext> {
    this.eventListeners.add(listener);
    return this;
  }
  public onChange(listener: ContextListener<TContext>): Interpreter<TContext> {
    this.contextListeners.add(listener);
    return this;
  }
  public onStop(listener: Listener): Interpreter<TContext> {
    this.stopListeners.add(listener);
    return this;
  }
  public onDone(listener: StateListener): Interpreter<TContext> {
    this.doneListeners.add(listener);
    return this;
  }
  /**
   * Removes a listener.
   * @param listener The listener to remove
   */
  public off(listener: StateListener): Interpreter<TContext> {
    this.listeners.delete(listener);
    return this;
  }
  public init = this.start;
  public start(
    initialState: State<TContext, TEvents> = this.machine.initialState as State<
      TContext,
      TEvents
    >
  ): Interpreter<TContext> {
    this.initialized = true;
    this.update(initialState);
    return this;
  }
  public stop(): Interpreter<TContext> {
    this.listeners.forEach(listener => this.off(listener));
    this.stopListeners.forEach(listener => {
      // call listener, then remove
      listener();
      this.stopListeners.delete(listener);
    });
    this.contextListeners.forEach(ctxListener =>
      this.contextListeners.delete(ctxListener)
    );
    this.doneListeners.forEach(doneListener =>
      this.doneListeners.delete(doneListener)
    );
    return this;
  }
  public send = (event: Event<TEvents>): State<TContext, TEvents> => {
    const eventObject = 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)}`
      );
    }
 
    const nextState = this.machine.transition(
      this.state,
      eventObject,
      this.state.context
    ) as State<TContext, TEvents>; // 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
  };
  private forward(event: Event<TEvents>): void {
    this.children.forEach(childInterpreter => childInterpreter.send(event));
  }
  private defer(sendAction: SendAction<TContext, TEvents>): number {
    return this.clock.setTimeout(
      () => this.send(sendAction.event),
      sendAction.delay || 0
    );
  }
  private cancel(sendId: string | number): void {
    this.clock.clearTimeout(this.delayedEventsMap[sendId]);
    delete this.delayedEventsMap[sendId];
  }
  private exec(
    action: ActionObject<TContext>,
    context: TContext,
    event?: TEvents
  ): Partial<TContext> | undefined {
    if (action.exec) {
      return action.exec(context, event);
    }
 
    switch (action.type) {
      case actionTypes.send:
        const sendAction = action as SendAction<TContext, TEvents>;
 
        switch (sendAction.target) {
          case SpecialTargets.Parent:
            Eif (this.parent) {
              this.parent.send(sendAction.event);
            }
            break;
          default:
            Iif (!sendAction.delay) {
              this.eventQueue.push(sendAction.event);
            } else {
              this.delayedEventsMap[sendAction.id] = this.defer(sendAction);
            }
 
            break;
        }
 
      case actionTypes.cancel:
        this.cancel((action as CancelAction).sendId);
 
        break;
      case actionTypes.start: {
        const activity = (action as ActivityActionObject<TContext>)
          .activity as Invocation<TContext>;
 
        if (activity.type === ActionTypes.Invoke) {
          const service =
            this.machine.options.services && activity.src
              ? this.machine.options.services[activity.src]
              : undefined;
 
          const autoForward = !!activity.forward;
 
          Iif (!service) {
            console.warn(`No service found for invocation '${activity.src}'`);
            return;
          }
 
          Eif (typeof service !== 'string') {
            // TODO: try/catch here
            const interpreter = this.spawn(Machine(service), autoForward);
 
            interpreter.start();
 
            this.activitiesMap[activity.id] = () => {
              this.children.delete(interpreter);
              interpreter.stop();
            };
          }
        } else {
          const implementation =
            this.machine.options && this.machine.options.activities
              ? this.machine.options.activities[activity.type]
              : undefined;
 
          Iif (!implementation) {
            console.warn(
              `No implementation found for activity '${activity.type}'`
            );
            return;
          }
 
          // Start implementation
          this.activitiesMap[activity.id] = implementation(context, activity);
        }
 
        break;
      }
      case actionTypes.stop: {
        const { activity } = action as ActivityActionObject<TContext>;
        const dispose = this.activitiesMap[activity.id];
 
        Eif (dispose) {
          dispose();
        }
 
        break;
      }
 
      case actionTypes.log:
        const expr = action.expr ? action.expr(context, event) : undefined;
 
        Iif (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;
  }
  private spawn<
    TChildContext,
    TChildStateSchema,
    TChildEvents extends EventObject
  >(
    machine: XSMachine<TChildContext, TChildStateSchema, TChildEvents>,
    IautoForward: boolean = false
  ): Interpreter<TChildContext, TChildStateSchema, TChildEvents> {
    const childInterpreter = new Interpreter(machine, {
      parent: this
    });
 
    Eif (autoForward) {
      this.children.add(childInterpreter);
    }
 
    return childInterpreter;
  }
  private flushEventQueue() {
    const flushedEvent = this.eventQueue.shift();
    Iif (flushedEvent) {
      this.send(flushedEvent);
    }
  }
}
 
export function interpret<
  TContext = DefaultContext,
  TStateSchema extends StateSchema = any,
  TEvents extends EventObject = EventObject
>(
  machine: XSMachine<TContext, TStateSchema, TEvents>,
  options?: Partial<InterpreterOptions>
) {
  const interpreter = new Interpreter(machine, options);
 
  return interpreter;
}