-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.d.ts
1323 lines (1288 loc) · 35.9 KB
/
index.d.ts
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
declare module 'statebot' {
/**
* A description of all the states in a machine, plus all of the
* permitted transitions between them.
*
* This is defined using a `string` or an `array` of strings, but
* [Template Literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)
* are much more convenient.
*
* An arrow `->` configures a **permitted transition** between two states:
*
* ```
* from-state -> to-state
* ```
*
* It's the only operator needed to build any chart:
*
* ```js
* let promiseLikeChart = `
* pending -> resolved
* pending -> rejected
* resolved -> done
* rejected -> done
* `
* ```
*
* The "OR" operator `|` can help us remove some redundancy from the above example:
*
* ```js
* let promiseLikeChart = `
* pending -> resolved | rejected
* resolved | rejected -> done
* `
* ```
*
* In both charts, `pending` can transition to `resolved` or `rejected`, and
* `resolved` or `rejected` can both transition to `done`.
*
* We can streamline this even further:
*
* ```js
* let promiseLikeChart = `
* pending -> (resolved | rejected) -> done
* `
* ```
*
* Again, this is exactly equivalent to the previous two examples.
*
* Notice in this one that we have parentheses `(` `)` surrounding `resolved`
* and `rejected`. They are actually completely ignored by the parser, and
* you can use them as you please to help make your charts more readable.
*
* A chart works exactly the same without them:
*
* ```js
* let promiseLikeChart = `
* pending -> resolved | rejected -> done
* `
* ```
*
* Charts can also be split across multiple-lines:
*
* ```js
* let promiseLikeChart = `
* pending ->
* resolved |
* rejected ->
* done
* `
* ```
* Notice that all white-space is ignored on either side of the `->`
* and `|`.
*
* `// Comments of this kind are allowed, too:`
*
* ```js
* let promiseLikeChart = `
* pending -> // Where do we go from here?
* (resolved | rejected) -> // Ah, yes
*
* // And now we're all finished
* done
* `
* ```
*
* Finally, here's a more full example:
*
* ```js
* let dragDropChart = `
* idle ->
* drag-detect ->
* (dragging | clicked)
*
* // Just a click, bail-out!
* clicked -> idle
*
* // Drag detected!
* dragging ->
* drag-wait -> dragged -> drag-wait
*
* // Drag finished...
* (drag-wait | dragged) ->
* (drag-done | drag-cancel) ->
* idle
* `
* ```
*/
export type TStatebotChart = string | string[]
export type TEventName =
| 'onEntered'
| 'onEntering'
| 'onEvent'
| 'onExited'
| 'onExiting'
| 'onSwitched'
| 'onSwitching'
export type TListenersRemover = Function
/**
* Options for creating a Statebot.
*/
export interface TStatebotOptions {
/**
* The state-chart.
*/
chart: TStatebotChart
/**
* The state in which to start. If unspecified, the first state in the
* chart will be used.
*/
startIn?: string
/**
* How noisy the logging is, from 1 to 3:
* ```
* 1) console.warn
* 2) console.warn/log/table
* 3) console.warn/log/table/info
* ```
* `3` is the default. Argument type-errors will always `throw`.
*/
logLevel?: 0 | 1 | 2 | 3
/**
* Limit how much history the state-machine keeps. Accessed via
* {@link TStatebotFsm.history}.
*/
historyLimit?: number
/**
* If you wish to have your Statebots listen to events coming from
* a shared EventEmitter, you can pass it in here. The `emit()`/`onEvent()`/
* `performTransitions()` methods will use it.
*
* It should have the same signature as [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
*
* - Since v2.5.0 [mitt](https://npmjs.com/mitt) is also compatible.
* - Since v2.6.0 [mitt](https://npmjs.com/mitt) is used internally.
*/
events?: any
}
export interface TStatebotFsm {
/**
* For identifying Statebot objects.
*
* @ignore
*/
__STATEBOT__: number
/**
* Tests to see if we can transition to the specified state from
* the {@link TStatebotFsm.currentState}.
*
* If more than one state is specified, `true` is returned only if
* **ALL** states are available.
*
* See also: {@link TStatebotFsm.peek}.
*
* Can test if a certain state will be entered after
* emitting an event. Use `{ afterEmitting: 'eventName' }` as the
* second argument. Works only after using {@link TStatebotFsm.performTransitions}.
*
* @param states
* @param [options]
* @param options.afterEmitting
* @returns Whether the transition is possible.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('game-menus', {
* chart: `
* loading ->
* menu ->
* play |
* options |
* sound |
* quit
*
* // Go back to menu
* play | options | sound -> menu
*
* // Can quit from main game, too
* play -> quit
* `
* })
*
* machine.canTransitionTo('play')
* // false
*
* machine.enter('menu')
* machine.canTransitionTo(['play', 'options'])
* // true
*
* machine.canTransitionTo('play', {
* afterEmitting: 'startGame'
* })
* // false
* ```
*/
canTransitionTo(
stateOrStates: string | string[],
options?: {
/**
* Test if a certain state will be entered after emitting an event.
* Works only after using {@link TStatebotFsm.performTransitions}.
*/
afterEmitting: string
}
): boolean
/**
* Returns the current state.
*
* @returns The current state.
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('coroutine', {
* chart: `
* suspended -> running -> (suspended | dead)
* `
* })
*
* machine.currentState()
* // "suspended"
* ```
*/
currentState(): string
/**
* Immediately emits an event, firing any listeners added using
* {@link TStatebotFsm.performTransitions} or {@link TStatebotFsm.onEvent}.
*
* @param eventName
* @param [args] Optional arguments to pass to listeners.
* @returns Whether or not the event had listeners.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('basic-form', {
* chart: `
* idle -> sending -> redirect
* `
* })
*
* machine.performTransitions({
* 'idle -> sending': {
* on: 'post-data',
* then: (...args) => {
* console.log('Event args: ', args)
* // setTimeout(machine.Enter('redirect'), 5000)
* }
* }
* })
*
* machine.emit('post-data', 'Hello, world!')
* // Event args: ["Hello, world!"]
*
* machine.currentState()
* // "sending"
* ```
*/
emit(eventName: string, ...args: any[]): boolean
/**
* Creates a function that emits the specified event.
*
* (This is essentially a convenience wrapper around {@link TStatebotFsm.emit}.)
*
* @param eventName The desired event to {@link TStatebotFsm.emit}.
* @param [curriedArgs] Arguments that will curry into the returned `emit()`
* function whenever it is called.
* @returns A function that emits that event.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('traffic-lights', {
* chart: `
* go ->
* prepare-to-stop ->
* stop
*
* // ...gotta keep that traffic flowing
* stop ->
* prepare-to-go ->
* go
* `,
* startIn: 'stop'
* })
*
* machine.performTransitions({
* 'stop -> prepare-to-go': { on: 'timer' },
* 'prepare-to-go -> go': { on: 'timer' },
* 'go -> prepare-to-stop': { on: 'timer' },
* 'prepare-to-stop -> stop': { on: 'timer' }
* })
*
* let nextTrafficLight = machine.Emit('timer')
* machine.currentState()
* // "stop"
*
* nextTrafficLight()
* nextTrafficLight()
* nextTrafficLight()
*
* machine.currentState()
* // "prepare-to-stop"
* ```
*/
Emit(eventName: string, ...curriedArgs: any[]): (...args: any[]) => boolean
/**
* Immediately changes to the specified state, so long as it is
* accessible from the {@link TStatebotFsm.currentState}.
*
* @param state The desired state to switch-to.
* @param [args] Optional arguments to pass to transition callbacks.
* @returns Whether or not the state changed.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('dialog', {
* chart: `
* idle -> showing-modal -> (saving | idle)
* saving -> idle
* `
* })
*
* machine.currentState()
* // "idle"
*
* machine.enter('saving')
* // false
*
* // Statebot[dialog]: Invalid transition "idle->saving", not switching
* // > Previous transition: "[undefined]->idle"
* // > From "idle", valid states are: ["showing-modal"]
*
* machine.enter('showing-modal')
* // true
* ```
*/
enter(state: string, ...args: any[]): boolean
/**
* Creates a function that changes to the specified state, so long
* as it is accessible from the {@link TStatebotFsm.currentState}.
*
* (This is essentially a convenience wrapper around {@link TStatebotFsm.enter}.)
*
* @param state The desired state to switch-to.
* @param [curriedArgs] Arguments that will curry into the returned
* `enter()` function whenever it is called.
* @returns A function that can change the state when called.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('popup-menu', {
* chart: `
* idle -> menu-opened ->
* (item-clicked | idle)
*
* item-clicked -> idle
* `,
* startIn: 'menu-opened'
* })
*
* button.onclick = machine.Enter('item-clicked')
* machine.currentState()
* // "menu-opened"
*
* button.onclick()
* machine.currentState()
* // "item-clicked"
* ```
*/
Enter(state: string, ...curriedArgs: any[]): (...args: any[]) => boolean
/**
* Returns all states the machine has been in so far, up to a limit set
* by `historyLimit` in {@link TStatebotOptions}.
*
* @returns A copy of the state-history.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('downloader', {
* chart: `
* loading -> (failure | success)
* failure -> loading
* success -> done
* `,
* historyLimit: 4
* })
*
* machine.enter('failure')
* machine.enter('loading')
* machine.enter('success')
* machine.enter('done')
* machine.history()
* // ["failure", "loading", "success", "done"]
* ```
*/
history(): string[]
/**
* Print information about the current machine to the console.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('half-duplex', {
* chart: `
* idle -> sending | receiving -> done
* `
* })
*
* machine.info()
* // [half-duplex]: Information about this state-machine.
* // [half-duplex]: Listening for the following state-changes:
* // ┌---------┬-------------┬--------┐
* // │ (index) │ states │ # │
* // ├---------┼-------------┼--------┤
* // │ 0 │ 'done' │ 'None' │
* // │ 1 │ 'idle' │ 'None' │
* // │ 2 │ 'receiving' │ 'None' │
* // │ 3 │ 'sending' │ 'None' │
* // └---------┴-------------┴--------┘
* // [half-duplex] Listening for the following transitions:
* // ┌---------┬-------------------┬--------┐
* // │ (index) │ transitions │ # │
* // ├---------┼-------------------┼--------┤
* // │ 0 │ 'idle->receiving' │ 'None' │
* // │ 1 │ 'idle->sending' │ 'None' │
* // │ 2 │ 'receiving->done' │ 'None' │
* // │ 3 │ 'sending->done' │ 'None' │
* // └---------┴-------------------┴--------┘
* // [half-duplex]: Listening for the following events:
* // (No information)
* ```
*/
info(): void
/**
* Get information about the current machine.
*
* Same details as {@link TStatebotFsm.info} in object-form.
*
* @returns An object containing information about the current machine.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('half-duplex', {
* chart: `
* idle -> sending | receiving -> done
* `
* })
*
* machine.inspect()
* // Will return an object with the following signature:
* // { states, transitions, events }
*
* // These will each have key-values, the key being the name
* // and the value being the number of listeners attached.
* ```
*/
inspect(): { states: any[]; transitions: any[]; events: any[] }
/**
* Checks if the {@link TStatebotFsm.currentState}
* matches the specified `state`, immediately returning either
* `true` or `false`.
*
* An object can be used instead of a string, with the keys
* being the states, and the values corresponding to their
* `outputWhenTrue` value. See the example.
*
* If `outputWhenTrue` is specified, then it will be returned
* instead of `true`, and `null` will be returned instead of
* `false`. If a function is specified, then its return-value
* will be used as the `true`-value.
*
* @param state
* The state to test against. This can be a string if you have a
* single condition, or an object for multiple. (See example.)
* @param [outputWhenTrue]
* When a string is specified as the first argment, this becomes
* an optional `true`-value that is returned if the state matches.
* If a function is specified, it will be called and its return
* value will be used.
* @param [fnArgs]
* Arguments that will pass into `outputWhenTrue()` if it has
* been defined as a function.
* @returns
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('little-revver', {
* chart: `
* idle ->
* (gear-1 | gear-2 | reverse) ->
* idle
* `
* })
*
* machine.inState('idle')
* // true
*
* machine.inState('idle', 'Purrrr...')
* // "Purrrr..."
*
* machine.enter('gear-1')
*
* machine.inState({
* 'idle': 'Purrrr...',
* 'gear-1': () => 'Chugga-chugga-chugga...',
* 'gear-2': () => 'Brumma-brumma-brum-brum...',
* 'reverse': false,
* })
* // "Chugga-chugga-chugga..."
*
* machine.inState('idle', () => {
* console.log('Idling!')
* return 'Purrrr...'
* })
* // null
* // ^ the function is not called at all in the `false` case,
* // so no console.log either.
* ```
*/
inState(state: string): boolean
inState(state: string, outputWhenTrue?: any, ...fnArgs: any[]): any
inState(state: object): any
/**
* Returns a function which, when run, tests that
* {@link TStatebotFsm.currentState} matches the
* specified state, returning either `true` or `false`.
*
* If `outputWhenTrue` is specified, then it will be returned
* instead of `true`, and `null` will be returned instead of
* `false`.
*
* (This is essentially a convenience wrapper around {@link TStatebotFsm.inState}.)
*
* @param state The state to test against.
* @param [outputWhenTrue]
* Optional `true`-value. If a function is specified, it will be
* called and its return value will be used.
* @param [curriedFnArgs]
* Arguments that will curry into `outputWhenTrue()` if it has
* been defined as a function.
* @returns
* A function that calls {@link TStatebotFsm.inState}.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('little-revver', {
* chart: `
* idle ->
* (gear-1 | gear-2 | reverse) ->
* idle
* `
* })
*
* let idling = machine.InState('idle')
* let purring = machine.InState('idle', () => {
* console.log('Idling!')
* return 'Purrrr...'
* })
*
* idling()
* // true
*
* purring()
* // Idling!
* // "Purrrr..."
*
* machine.enter('gear-1')
* purring()
* // null
* // ^ the function is not called at all in the `false` case,
* // so no console.log either.
* ```
*/
InState(state: string): (...fnArgs: any[]) => boolean
InState(state: string, outputWhenTrue?: any): (...fnArgs: any[]) => any
InState(state: object): () => any
/**
* Returns the name of the state-machine.
*
* Used for logging and also by {@link assert.assertRoute}
* for the same.
*
* @returns The name of the state-machine.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('Ay, there’s the rub.', {
* chart: `
* the-question -> (to-be | not-to-be)
* not-to-be -> perchance-to-dream
* `
* })
*
* machine.name()
* // "Ay, there’s the rub."
* ```
*/
name(): string
/**
* Adds a listener that runs a callback immediately **AFTER** the
* specified-state becomes the current one.
*
* A function is returned that will remove the listener.
*
* @param state The state.
* @param cb
* A callback function with the signature:
*
* `(fromState, ...args?)`
* @returns A function that removes the listener.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('half-duplex', {
* chart: `
* idle -> sending | receiving -> done
* `
* })
*
* machine.onEntered('done', fromState => {
* console.log('Entered from:', fromState)
* })
*
* machine.enter('receiving')
* machine.enter('done')
* // Entered from: receiving
* ```
*/
onEntered(
state: string,
cb: (fromState?: string, ...args: any[]) => void
): TListenersRemover
/**
* Adds a listener that runs a callback immediately **BEFORE** the
* specified-state becomes the current one.
*
* A function is returned that will remove the listener.
*
* @memberof TStatebotFsm
* @instance
* @function
* @param {string} state The state.
* @param {enterCallback} cb
* A callback function with the signature:
*
* `(fromState, ...args?)`
* @returns {function} A function that removes the listener.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('half-duplex', {
* chart: `
* idle -> sending | receiving -> done
* `
* })
*
* machine.onEntered('done', () => {
* console.log('We made it!')
* })
*
* machine.onEntering('done', fromState => {
* console.log('Entering from:', fromState)
* })
*
* machine.enter('sending')
* machine.enter('done')
* // Entering from: sending
* // We made it!
* ```
*/
onEntering(
state: string,
cb: (fromState?: string, ...args: any[]) => void
): TListenersRemover
/**
* Adds a listener that runs a callback immediately after the specified
* event is called.
*
* A function is returned that will remove the listener.
*
* @param name The event name.
* @param cb The callback.
* @returns A function that removes the listener.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('traffic-lights', {
* chart: `
* go ->
* prepare-to-stop ->
* stop
*
* // ...gotta keep that traffic flowing
* stop ->
* prepare-to-go ->
* go
* `
* })
*
* machine.performTransitions({
* 'stop -> prepare-to-go -> go': { on: 'timer' },
* 'go -> prepare-to-stop -> stop': { on: 'timer' },
* })
*
* machine.onEvent('timer', () => {
* redrawTrafficLights()
* })
*
* setInterval(machine.Emit('timer'), 2000)
* ```
*/
onEvent(eventName: string, cb: (...args: any[]) => void): TListenersRemover
/**
* Adds a listener that runs a callback immediately **AFTER** the
* specified-state is no longer the current one.
*
* A function is returned that will remove the listener.
*
* @param state The state.
* @param cb
* A callback function with the signature:
*
* `(toState, ...args?)`
* @returns A function that removes the listener.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('half-duplex', {
* chart: `
* idle -> sending | receiving -> done
* `
* })
*
* machine.onExited('idle', toState => {
* console.log('We are heading to:', toState)
* })
*
* machine.enter('sending')
* // We are heading to: sending
* ```
*/
onExited(
state: string,
cb: (toState?: string, ...args: any[]) => void
): TListenersRemover
/**
* Adds a listener that runs a callback immediately **BEFORE** the
* specified-state is no longer the current one.
*
* A function is returned that will remove the listener.
*
* @param state The state.
* @param cb
* A callback function with the signature:
*
* `(toState, ...args?)`
* @returns A function that removes the listener.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('half-duplex', {
* chart: `
* idle -> sending | receiving -> done
* `
* })
*
* machine.onExited('idle', () => {
* console.log('Peace out!')
* })
*
* machine.onExiting('idle', toState => {
* console.log('Heading to:', toState)
* })
*
* machine.enter('receiving')
* machine.enter('done')
* // Heading to: receiving
* // Peace out!
* ```
*/
onExiting(
state: string,
cb: (toState?: string, ...args: any[]) => void
): TListenersRemover
/**
* Adds a listener that runs a callback immediately after **ANY**
* state-change.
*
* A function is returned that will remove the listener.
*
* @param cb
* A callback function with the signature:
*
* `(toState, fromState, ...args?)`
* @returns A function that removes the listener.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('half-duplex', {
* chart: `
* idle -> sending | receiving -> done
* `
* })
*
* machine.onSwitched((toState, fromState) => {
* console.log(`We went from "${fromState}" to "${toState}"`)
* })
*
* machine.enter('receiving')
* // We went from "idle" to "receiving"
* ```
*/
onSwitched(
cb: (toState?: string, fromState?: string, ...args: any[]) => void
): TListenersRemover
/**
* Adds a listener that runs a callback immediately before **ANY**
* state-change.
*
* A function is returned that will remove the listener.
*
* @param cb
* A callback function with the signature:
*
* `(toState, fromState, ...args?)`
* @returns A function that removes the listener.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('half-duplex', {
* chart: `
* idle -> sending | receiving -> done
* `
* })
*
* machine.onSwitching((toState, fromState) => {
* console.log(`Going from "${fromState}" to "${toState}"`)
* })
*
* machine.enter('receiving')
* // Going from "idle" to "receiving"
* ```
*/
onSwitching(
cb: (toState?: string, fromState?: string, ...args: any[]) => void
): TListenersRemover
/**
* Run callbacks when transitions happen.
*
* If a callback returns a function, it will be invoked when
* the state is exited in the same manner as if an {@link TStatebotFsm.onExiting}
* handler was created using it.
*
* @param transitions
* Configuration in the form of an object, or a function that
* returns an object. If a function is used, there will be a single
* argument passed-in: an object with the following methods
* attached as a convenience:
*
* - {@link TStatebotFsm.enter}, {@link TStatebotFsm.emit}, {@link TStatebotFsm.Enter}, {@link TStatebotFsm.Emit}
*
* @returns A function that removes all listeners added
* by this method.
*
* @example
* ```js
* import { Statebot } from 'statebot'
*
* let machine = Statebot('half-duplex', {
* chart: `
* idle -> sending | receiving -> done
* `
* })
*
* machine.onTransitions({
* 'idle -> sending': () => {
* sendData()
* .then(machine.Enter('done', 'sent'))
* .catch(machine.Enter('done', 'failed'))
* },
* 'idle -> receiving': () => {
* receiveData()
* .then(machine.Enter('done', 'received'))
* .catch(machine.Enter('done', 'failed'))
* },
* 'sending | receiving -> done': whatHappened => {
* console.log('All finished: ', whatHappened)
* }
* })
*
* machine.enter('sending')
*
* function sendData() {
* return new Promise((resolve, reject) => {
* setTimeout(resolve, 1000)
* setTimeout(reject, 750 + Math.round(Math.random() * 750))
* })
* }
*
* function receiveData() {
* return new Promise((resolve, reject) => {
* setTimeout(resolve, 1000)
* setTimeout(reject, 750 + Math.round(Math.random() * 750))
* })
* }
*
* // The above example using a function for config
* machine.onTransitions(({ Enter }) => ({
* 'idle -> sending': () => {
* sendData()
* .then(Enter('done', 'sent'))
* .catch(Enter('done', 'failed'))
* },
* 'idle -> receiving': () => {
* receiveData()
* .then(Enter('done', 'received'))
* .catch(Enter('done', 'failed'))
* },
* 'sending | receiving -> done': whatHappened => {
* console.log('All finished: ', whatHappened)
* }
* }))
*