# All files core.js

98.41% Statements 372/378
98.18% Branches 108/110
100% Functions 24/24
98.41% Lines 372/378

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
    3791x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    80x
    80x
    80x
    2x
    2x
    80x
    80x
    1x
    1x
    1x
    1x
    1x
    28x
    28x
    28x
    27x
    27x
    46x
    46x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    25x
    25x
    25x
    25x
    25x
    1x
    25x
    25x
    45x
    6x
    1x
    1x
    6x
    45x
    28x
    28x
    1x
    1x
    28x
    27x
    43x
    23x
    1x
    1x
    1x
    1x
    46x
    46x
    46x
    46x
    46x
    46x
    46x
    50x
    50x
    28x
    28x
    46x
    6x
    22x
    11x
    16x
    4x
    5x
    1x
    1x
    1x
    1x
    50x
    45x
    45x
    45x
    45x
    45x
    45x
    45x
    45x
    45x
    1x
    11x
    11x
    11x
    1x
    4x
    4x
    4x
    1x
    25x
    25x
    25x
    25x
    25x
    1x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    1x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    56x
    56x
    56x
    56x
    23x
    23x
    20x
    20x
    20x
    20x
    23x
    36x
    56x
    56x
    56x
    56x
    56x
    32x
    31x
    31x
    32x
    5x
    5x
    5x
    1x
    1x
    1x
    1x
    1x
    1x
    55x
    55x
    55x
    55x
    55x
    55x
    55x
    55x
    30x
    4x
    4x
    30x
    55x
    55x
    55x
    55x
    55x
    55x
    50x
    13x
    13x
    50x
    55x
    55x
    8x
    4x
    4x
    8x
    51x
    55x
    17x
    17x
    51x
    55x
    46x
    13x
    2x
    2x
    13x
    13x
    5x
    5x
    13x
    46x
    51x
    51x
    51x
    1x
    40x
    40x
    40x
    1x
    72x
    72x
    34x
    34x
    32x
    32x
    34x
    72x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    21x
    21x
    21x
    21x
    21x
    11x
    11x
    10x
    19x
    3x
    3x
    7x
    7x
    7x
    21x
    1x
    2x
    2x
    2x
    2x
    2x
    2x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    69x
    69x
    69x
    69x
    283x
    283x
    69x
    69x
    283x
    283x
    283x
    283x
    138x
    138x
    138x
    138x
    283x
    283x
    283x
    283x
    283x
    69x
    69x
    69x
    1x
    1x
    1x
    1x
    1x
    2x
    2x
    2x
    2x
    2x
    1x
    1x
    1x
    1x
    2x
    1x
    1x
    1x
    1x
    2x
    2x
    2x
    2x
    2x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    44x
    44x
    44x
    7x
    6x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    6x
    5x
    5x
    6x
    7x
    7x
    7x

    7x
    5x
    5x
    5x
    5x
    5x
    5x
    7x
    44x
    44x
    44x
    1x
    1x
    51x
    5x
    5x
    51x
    51x
     const hookKeys = {
      guard: 'guards',
      reduce: 'reducers',
      effect: 'effects',
      invoke: 'invokes',
    }

    const transitionHooks = ['assign', 'reduce', 'action', 'guard']
    const enterHooks = ['assign', 'reduce', 'action', 'invoke', 'effect']
    const exitHooks = ['assign', 'reduce', 'action']

    const mappedHooks = {
      assign: ['reduce', assignToReduce],
      action: ['reduce', actionToReduce],
    }

    const ACTION = {}

    const env = (process && process.env && process.env.NODE_ENV) || 'development'

    function warn(msg) {
      if (env !== 'production') {
        console.warn(msg)
      }
    }

    function arg(argument, type, error) {
      if (type === 'string') {
        if (typeof argument !== 'string') {
          throw new Error(error)
        }
      }
    }

    /**
     * Parse the machine DSL into a machine object.
     */
    export function createMachine(create) {
      const machine = { states: {} }

      if (create) {
        create({
          state: (name, ...opts) => {
            machine.states[name] = createState(name, ...opts)
          },
          enter: createEnter,
          exit: createExit,
          transition: createTransition,
          immediate: createImmediate,
          internal: createInternal,
        })
      }

      validate(machine)

      return machine
    }

    function validate(machine) {
      for (const [, state] of Object.entries(machine.states)) {
        for (const transition of state.immediates) {
          if (!machine.states[transition.target]) {
            throw new Error(`Invalid transition target '${transition.target}'`)
          }
        }
        for (const transitions of Object.values(state.transitions)) {
          for (const transition of transitions) {
            if (!transition.internal && !machine.states[transition.target]) {
              throw new Error(`Invalid transition target '${transition.target}'`)
            }
          }
        }
      }
    }

    /**
     * Create a state node.
     */
    function createState(name, ...opts) {
      const enter = []
      const exit = []
      const transitions = {}
      const immediates = []

      for (const opt of opts) {
        const { type, event } = opt
        if (type === 'transition') {
          if (!transitions[event]) transitions[event] = []
          transitions[event].push(opt)
        } else if (type === 'immediate') {
          immediates.push(opt)
        } else if (type === 'enter') {
          enter.push(opt)
        } else if (type === 'exit') {
          exit.push(opt)
        } else {
          throw new Error(
            `State '${name}' should be passed one of enter(), exit(), transition(), immediate() or internal()`
          )
        }
      }

      return {
        name,
        enter,
        exit,
        transitions,
        immediates,
      }
    }

    function createEnter(opts) {
      return { type: 'enter', ...merge(opts, enterHooks) }
    }

    function createExit(opts) {
      return { type: 'exit', ...merge(opts, exitHooks) }
    }

    function createTransition(event, target, opts) {
      arg(event, 'string', 'First argument of the transition must be the name of the event')
      arg(target, 'string', 'Second argument of the transition must be the name of the target state')
      return { type: 'transition', event, target, ...merge(opts, transitionHooks) }
    }

    function createInternal(event, opts) {
      arg(event, 'string', 'First argument of the internal transition must be the name of the event')
      return {
        type: 'transition',
        event,
        internal: true,
        ...merge(opts, transitionHooks),
      }
    }

    function createImmediate(target, opts) {
      arg(
        target,
        'string',
        'First argument of the immediate transition must be the name of the target state'
      )
      return { type: 'immediate', target, ...merge(opts, transitionHooks) }
    }

    /**
     * Transition the given machine, with the given state
     * to the next state based on the event. Returns the tuple
     * of the next state and any events to execute. In case no external
     * transition took place, return null as effects, to indicate
     * that the active effects should continue running.
     */
    export function transition(machine = {}, state = {}, event) {
      event = typeof event === 'string' ? { type: event } : event

      // initial transition
      if (!state.name && event && event.type === null) {
        const stateNames = Object.keys(machine.states)
        if (stateNames.length > 0) {
          const initialStateName = stateNames[0]
          const initialTransition = createImmediate(initialStateName)
          return applyTransition(machine, state, event, initialTransition)
        }
      }

      const currState = machine.states[state.name] || {}
      const transitions = currState.transitions || {}
      const candidates = transitions[event.type] || []

      for (const candidate of candidates) {
        if (checkGuards(state.context, event, candidate)) {
          return applyTransition(machine, state, event, candidate)
        }
      }

      return [state, null]
    }

    /**
     * The logic of applying a transition to the machine. Exit states,
     * apply transition hooks, enter states and collect any events. Do this
     * recursively untill all immediate transitions settle.
     */
    function applyTransition(machine, curr, event, transition) {
      const next = { ...curr }
      const target = transition.internal ? curr.name : transition.target
      const currState = machine.states[curr.name]
      const nextState = machine.states[target]
      const effects = transition.internal ? null : []

      if (currState && !transition.internal) {
        for (const exit of currState.exit) {
          applyReducers(next, event, exit.reducers)
        }
      }

      next.name = target

      applyReducers(next, event, transition.reducers)

      if (!transition.internal) {
        for (const enter of nextState.enter) {
          applyReducers(next, event, enter.reducers)
        }
      }

      for (const candidate of nextState.immediates) {
        if (checkGuards(next.context, event, candidate)) {
          return applyTransition(machine, next, event, candidate)
        }
      }

      if (Object.keys(nextState.transitions).length === 0 && nextState.immediates.length === 0) {
        next.final = true
      }

      if (!transition.internal) {
        for (const enter of nextState.enter) {
          for (const invoke of enter.invokes) {
            effects.push({ run: promiseEffect(invoke), event })
          }

          for (const effect of enter.effects) {
            effects.push({ run: effect, event })
          }
        }
      }

      return [next, effects]
    }

    function checkGuards(context, event, transition) {
      return !transition.guards.length || transition.guards.every((g) => g(context, event))
    }

    function applyReducers(next, event, reducers) {
      for (const reduce of reducers) {
        const result = reduce(next.context, event)
        if (result !== ACTION) {
          next.context = result
        }
      }
    }

    /**
     * A common operation is to assign event payload
     * to the context, this allows to do in several ways:
     * true - assign the full event payload to context
     * fn - assign the result of the fn(context, data) to context
     * val - assign the constant provided value to context
     */
    function assignToReduce(assign) {
      return (context, event) => {
        const { type, ...data } = event

        if (assign === true) {
          return { ...context, ...data }
        }

        if (typeof assign === 'function') {
          return { ...context, ...assign(context, data) }
        }

        return { ...context, ...assign }
      }
    }

    function actionToReduce(action) {
      return (context, event) => {
        action(context, event)
        return ACTION
      }
    }

    /**
     * Allow to pass each hook as a function, or a list of functions
     *   transition(..., { reduce: fn })
     *   transition(..., { reduce: [fn1, fn2] })
     * Convert both of those into arrays, and also remap some of the
     * hooks to different hooks (i.e. assign -> reduce)
     */
    function merge(opts = {}, allowedHooks) {
      const merged = {}

      for (const hook of allowedHooks) {
        add(hook)
      }

      function add(hook) {
        let t = opts[hook] || []
        t = Array.isArray(t) ? t : [t]

        if (mappedHooks[hook]) {
          const [newName, transform] = mappedHooks[hook]
          hook = newName
          t = t.map(transform)
        }

        const key = hookKeys[hook]
        merged[key] = merged[key] || []
        merged[key] = merged[key].concat(t)
      }

      return merged
    }

    /**
     * Convert an async function into an effect
     * that sends 'done' and 'error' events
     */
    function promiseEffect(fn) {
      return (curr, event, send) => {
        let disposed = false
        Promise.resolve(fn(curr, event))
          .then((data) => {
            if (!disposed) {
              send({ type: 'done', data })
            }
          })
          .catch((error) => {
            if (!disposed) {
              send({ type: 'error', error })
            }
          })
        return () => {
          disposed = true
        }
      }
    }

    /**
     * createMachine and transition are pure, stateless functions. After
     * transitioning the machine to the next state, the caller must clean
     * up all of the running effects, and then run the newly provided effects.
     */
    export function runEffects(effects = [], state, send) {
      const runningEffects = []

      for (const effect of effects) {
        const safeSend = (...args) => {
          if (effect.disposed) {
            warn(
              [
                "Can't send events in an effect after it has been cleaned up.",
                'This is a no-op, but indicates a memory leak in your application.',
                "To fix, cancel all subscriptions and asynchronous tasks in the effect's cleanup function.",
              ].join(' ')
            )
          } else {
            return send(...args)
          }
        }

        const dispose = effect.run(state.context, effect.event, safeSend)
        if (dispose && dispose.then) {
          warn(
            [
              'Effect function must return a cleanup function or nothing.',
              'Use invoke instead of effect for async functions, or call the async function inside the synchronous effect function.',
            ].join(' ')
          )
        } else if (dispose) {
          effect.dispose = () => {
            effect.disposed = true
            return dispose()
          }
          runningEffects.push(effect)
        }
      }

      return runningEffects
    }

    export function cleanEffects(runningEffects = []) {
      for (const effect of runningEffects) {
        effect.dispose()
      }
      return []
    }