-
-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathMessenger.ts
More file actions
1250 lines (1176 loc) · 44.1 KB
/
Messenger.ts
File metadata and controls
1250 lines (1176 loc) · 44.1 KB
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
export type ActionHandler<
Action extends ActionConstraint,
ActionType = Action['type'],
> = (
...args: ExtractActionParameters<Action, ActionType>
) => ExtractActionResponse<Action, ActionType>;
export type ExtractActionParameters<
Action extends ActionConstraint,
ActionType = Action['type'],
> = Action extends {
type: ActionType;
handler: (...args: infer HandlerArgs) => unknown;
}
? HandlerArgs
: never;
export type ExtractActionResponse<
Action extends ActionConstraint,
ActionType = Action['type'],
> = Action extends {
type: ActionType;
handler: (...args: infer _) => infer HandlerReturnValue;
}
? HandlerReturnValue
: never;
export type ExtractEventHandler<
Event extends EventConstraint,
EventType = Event['type'],
> = Event extends {
type: EventType;
payload: infer Payload;
}
? Payload extends unknown[]
? (...payload: Payload) => void
: never
: never;
export type ExtractEventPayload<
Event extends EventConstraint,
EventType = Event['type'],
> = Event extends {
type: EventType;
payload: infer Payload;
}
? Payload extends unknown[]
? Payload
: never
: never;
export type GenericEventHandler = (...args: unknown[]) => void;
export type SelectorFunction<
Event extends EventConstraint,
EventType extends Event['type'],
ReturnValue = unknown,
> = (...args: ExtractEventPayload<Event, EventType>) => ReturnValue;
export type SelectorEventHandler<SelectorReturnValue = unknown> = (
newValue: SelectorReturnValue,
previousValue: SelectorReturnValue | undefined,
) => void;
export type ActionConstraint = {
type: NamespacedName;
handler: ((...args: never) => unknown) | ((...args: never[]) => unknown);
};
export type EventConstraint = {
type: NamespacedName;
payload: unknown[];
};
/**
* Extract action types from a Messenger type.
*
* @template Subject - The messenger type to extract from.
*/
export type MessengerActions<
Subject extends Messenger<string, ActionConstraint, EventConstraint>,
> =
Subject extends Messenger<string, infer Action, EventConstraint>
? Action
: never;
/**
* Extract event types from a Messenger type.
*
* @template Subject - The messenger type to extract from.
*/
export type MessengerEvents<
Subject extends Messenger<string, ActionConstraint, EventConstraint>,
> =
Subject extends Messenger<string, ActionConstraint, infer Event>
? Event
: never;
/**
* Messenger namespace checks can be disabled by using this as the `namespace` constructor
* parameter, and using `MockAnyNamespace` as the Namespace type parameter.
*
* This is useful for mocking a variety of different actions/events in unit tests. Please do not
* use this in production code.
*/
export const MOCK_ANY_NAMESPACE = 'MOCK_ANY_NAMESPACE';
/**
* A type representing any namespace.
*
* This is useful for mocking a variety of different actions/events in unit tests. Please do not
* use this in production code.
*/
export type MockAnyNamespace = string;
/**
* Metadata for a single event subscription.
*
* @template Event - The event this subscription is for.
*/
type SubscriptionMetadata<Event extends EventConstraint> = {
/**
* Whether this subscription is for a delegated messenger. Delegation subscriptions are ignored
* when clearing subscriptions.
*/
delegation: boolean;
/**
* The optional selector function for this subscription.
*/
selector?: SelectorFunction<Event, Event['type']>;
};
/**
* A map of event handlers for a specific event.
*
* The key is the handler function, and the value contains additional subscription metadata.
*
* @template Event - The event these handlers are for.
*/
type EventSubscriptionMap<Event extends EventConstraint> = Map<
GenericEventHandler | SelectorEventHandler,
SubscriptionMetadata<Event>
>;
/**
* A namespaced string
*
* This type verifies that the string Name is prefixed by the string Name followed by a colon.
*
* @template Namespace - The namespace we're checking for.
* @template Name - The full string, including the namespace.
*/
export type NamespacedBy<
Namespace extends string,
Name extends string,
> = Name extends `${Namespace}:${string}` ? Name : never;
export type NotNamespacedBy<
Namespace extends string,
Name extends string,
> = Name extends `${Namespace}:${string}` ? never : Name;
export type NamespacedName<Namespace extends string = string> =
`${Namespace}:${string}`;
/**
* A messenger that actions and/or events can be delegated to.
*
* This is a minimal type interface to avoid complex incompatibilities resulting from generics over
* invariant types.
*/
type DelegatedMessenger = Pick<
// The type is broadened to all actions/events because some messenger methods are contravariant
// over this type (`registerDelegatedActionHandler` and `publishDelegated` for example). If this
// type is narrowed to just the delegated actions/events, the types for event payload and action
// parameters would not be wide enough.
Messenger<string, ActionConstraint, EventConstraint>,
| '_internalPublishDelegated'
| '_internalRegisterDelegatedActionHandler'
| '_internalRegisterDelegatedInitialEventPayload'
| '_internalUnregisterDelegatedActionHandler'
| 'captureException'
>;
type StripNamespace<Namespaced extends NamespacedName> =
Namespaced extends `${string}:${infer Name}` ? Name : never;
/**
* A message broker for "actions" and "events".
*
* The messenger allows registering functions as 'actions' that can be called elsewhere,
* and it allows publishing and subscribing to events. Both actions and events are identified by
* unique strings prefixed by a namespace (which is delimited by a colon, e.g.
* `Namespace:actionName`).
*
* @template Action - A type union of all Action types.
* @template Event - A type union of all Event types.
* @template Namespace - The namespace for the messenger.
*/
export class Messenger<
Namespace extends string,
Action extends ActionConstraint = never,
Event extends EventConstraint = never,
Parent extends Messenger<
string,
ActionConstraint,
EventConstraint,
// Use `any` to avoid preventing a parent from having a parent. `any` is harmless in a type
// constraint anyway, it's the one totally safe place to use it.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
any
> = never,
> {
readonly #namespace: Namespace;
/**
* The parent messenger. All actions/events under this namespace are automatically delegated to
* the parent messenger.
*/
readonly #parent?: DelegatedMessenger;
readonly #actions = new Map<Action['type'], Action['handler']>();
readonly #events = new Map<Event['type'], EventSubscriptionMap<Event>>();
/**
* The set of messengers we've delegated events to and their event handlers, by event type.
*/
readonly #subscriptionDelegationTargets = new Map<
Event['type'],
Map<DelegatedMessenger, ExtractEventHandler<Event, Event['type']>>
>();
/**
* The set of messengers we've delegated actions to, by action type.
*/
readonly #actionDelegationTargets = new Map<
Action['type'],
Set<DelegatedMessenger>
>();
/**
* A map of functions for getting the initial event payload.
*
* Used only for events that represent state changes.
*/
readonly #initialEventPayloadGetters = new Map<
Event['type'],
() => ExtractEventPayload<Event, Event['type']>
>();
/**
* A cache of selector return values for their respective handlers.
*/
readonly #eventPayloadCache = new Map<
GenericEventHandler,
unknown | undefined
>();
/**
* Reports an error to an error monitoring service.
*
* @param error - The error to report.
*/
readonly captureException?: (error: Error) => void;
/**
* Construct a messenger.
*
* If a parent messenger is given, all actions and events under this messenger's namespace will
* be delegated to the parent automatically.
*
* @param args - Constructor arguments
* @param args.captureException - Reports an error to an error monitoring service.
* @param args.namespace - The messenger namespace.
* @param args.parent - The parent messenger.
*/
constructor({
captureException,
namespace,
parent,
}: {
captureException?: (error: Error) => void;
namespace: Namespace;
parent?: Action['type'] extends MessengerActions<Parent>['type']
? Event['type'] extends MessengerEvents<Parent>['type']
? Parent
: never
: never;
}) {
this.#namespace = namespace;
this.#parent = parent;
this.captureException = captureException ?? this.#parent?.captureException;
}
/**
* Register an action handler.
*
* This will make the registered function available to call via the `call` method.
*
* The action being registered must be under the same namespace as the messenger.
*
* @param actionType - The action type. This is a unique identifier for this action.
* @param handler - The action handler. This function gets called when the `call` method is
* invoked with the given action type.
* @throws Will throw when a handler has been registered for this action type already.
* @template ActionType - A type union of Action type strings under this messenger's namespace.
*/
registerActionHandler<
ActionType extends Action['type'] & NamespacedName<Namespace>,
>(actionType: ActionType, handler: ActionHandler<Action, ActionType>): void {
if (!this.#isInCurrentNamespace(actionType)) {
throw new Error(
`Only allowed registering action handlers prefixed by '${
this.#namespace
}:'`,
);
}
this.#registerActionHandler(actionType, handler);
if (this.#parent) {
// @ts-expect-error The parent type isn't constructed in a way that proves it supports this
// action, but this is OK because it's validated in the constructor.
this.delegate({ actions: [actionType], messenger: this.#parent });
}
}
#registerActionHandler<ActionType extends Action['type']>(
actionType: ActionType,
handler: ActionHandler<ActionConstraint, ActionType>,
): void {
if (this.#actions.has(actionType)) {
throw new Error(
`A handler for ${actionType} has already been registered`,
);
}
this.#actions.set(actionType, handler);
}
/**
* Registers action handlers for a list of methods on a messenger client
*
* @param messengerClient - The object that is expected to make use of the messenger.
* @param methodNames - The names of the methods on the messenger client to register as action
* handlers.
* @template MessengerClient - The type expected to make use of the messenger.
* @template MethodNames - The type union of method names to register as action handlers.
*/
registerMethodActionHandlers<
MessengerClient extends { name: Namespace },
MethodNames extends keyof MessengerClient & StripNamespace<Action['type']>,
>(
messengerClient: MessengerClient,
methodNames: readonly MethodNames[],
): void {
for (const methodName of methodNames) {
const method = messengerClient[methodName];
if (typeof method === 'function') {
const actionType = `${messengerClient.name}:${methodName}` as const;
this.registerActionHandler(actionType, method.bind(messengerClient));
}
}
}
/**
* Unregister an action handler.
*
* This will prevent this action from being called.
*
* The action being unregistered must be under the same namespace as the messenger.
*
* @param actionType - The action type. This is a unique identifier for this action.
* @template ActionType - A type union of Action type strings under this messenger's namespace.
*/
unregisterActionHandler<
ActionType extends Action['type'] & NamespacedName<Namespace>,
>(actionType: ActionType): void {
if (!this.#isInCurrentNamespace(actionType)) {
throw new Error(
`Only allowed unregistering action handlers prefixed by '${
this.#namespace
}:'`,
);
}
this.#unregisterActionHandler(actionType);
}
#unregisterActionHandler<ActionType extends Action['type']>(
actionType: ActionType,
): void {
this.#actions.delete(actionType);
}
/**
* Unregister all action handlers.
*
* This prevents all actions from being called.
*/
clearActions(): void {
for (const actionType of this.#actions.keys()) {
this.#unregisterActionHandler(actionType);
}
}
/**
* Get the action handler for a given action type.
*
* This is a protected method to allow subclasses to override the way action
* handlers are retrieved, for example to implement custom delegation logic.
*
* @param actionType - The action type. This is a unique identifier for this
* action.
* @returns The action handler for the given action type, or undefined if no
* handler has been registered.
*/
protected getAction(
actionType: Action['type'],
): ActionConstraint['handler'] | undefined {
return this.#actions.get(actionType);
}
/**
* Call an action.
*
* This function will call the action handler corresponding to the given action type, passing
* along any parameters given.
*
* @param actionType - The action type. This is a unique identifier for this action.
* @param params - The action parameters. These must match the type of the parameters of the
* registered action handler.
* @throws Will throw when no handler has been registered for the given type.
* @template ActionType - A type union of Action type strings.
* @returns The action return value.
*/
call<ActionType extends Action['type']>(
actionType: ActionType,
...params: ExtractActionParameters<Action, ActionType>
): ExtractActionResponse<Action, ActionType> {
const handler = this.getAction(actionType) as
| ActionHandler<Action, ActionType>
| undefined;
if (!handler) {
throw new Error(
this.#isInCurrentNamespace(actionType)
? `A handler for ${actionType} has not been registered`
: `A handler for ${actionType} has not been delegated to ${this.#namespace}`,
);
}
return handler(...params);
}
/**
* Register a function for getting the initial payload for an event.
*
* This is used for events that represent a state change, where the payload is the state.
* Registering a function for getting the payload allows event selectors to have a point of
* comparison the first time state changes.
*
* The event type must be under the same namespace as the messenger.
*
* @param args - The arguments to this function
* @param args.eventType - The event type to register a payload for.
* @param args.getPayload - A function for retrieving the event payload.
* @template EventType - A type union of Event type strings under this messenger's namespace.
*/
registerInitialEventPayload<
EventType extends Event['type'] & NamespacedName<Namespace>,
>({
eventType,
getPayload,
}: {
eventType: EventType;
getPayload: () => ExtractEventPayload<Event, EventType>;
}): void {
if (!this.#isInCurrentNamespace(eventType)) {
throw new Error(
`Only allowed registering initial payloads for events prefixed by '${
this.#namespace
}:'`,
);
}
if (
this.#parent &&
!this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)
) {
// @ts-expect-error The parent type isn't constructed in a way that proves it supports this
// event, but this is OK because it's validated in the constructor.
this.delegate({ events: [eventType], messenger: this.#parent });
}
this.#registerInitialEventPayload({ eventType, getPayload });
}
#registerInitialEventPayload<EventType extends Event['type']>({
eventType,
getPayload,
}: {
eventType: EventType;
getPayload: () => ExtractEventPayload<Event, EventType>;
}): void {
this.#initialEventPayloadGetters.set(eventType, getPayload);
const delegationTargets =
this.#subscriptionDelegationTargets.get(eventType);
if (!delegationTargets) {
return;
}
for (const messenger of delegationTargets.keys()) {
messenger._internalRegisterDelegatedInitialEventPayload({
eventType,
getPayload,
});
}
}
/**
* Publish an event.
*
* Publishes the given payload to all subscribers of the given event type.
*
* Note that this method should never throw directly. Any errors from
* subscribers are captured and re-thrown in a timeout handler.
*
* The event being published must be under the same namespace as the messenger.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param payload - The event payload. The type of the parameters for each event handler must
* match the type of this payload.
* @template EventType - A type union of Event type strings under this messenger's namespace.
*/
publish<EventType extends Event['type'] & NamespacedName<Namespace>>(
eventType: EventType & NamespacedName<Namespace>,
...payload: ExtractEventPayload<Event, EventType>
): void {
if (!this.#isInCurrentNamespace(eventType)) {
throw new Error(
`Only allowed publishing events prefixed by '${this.#namespace}:'`,
);
}
if (
this.#parent &&
!this.#subscriptionDelegationTargets.get(eventType)?.has(this.#parent)
) {
// @ts-expect-error The parent type isn't constructed in a way that proves it supports this
// event, but this is OK because it's validated in the constructor.
this.delegate({ events: [eventType], messenger: this.#parent });
}
this.#publish(eventType, ...payload);
}
#publish<EventType extends Event['type']>(
eventType: EventType,
...payload: ExtractEventPayload<Event, EventType>
): void {
const subscribers = this.#events.get(eventType);
if (subscribers) {
for (const [handler, { selector }] of subscribers.entries()) {
try {
if (selector) {
const previousValue = this.#eventPayloadCache.get(handler);
const newValue = selector(...payload);
if (newValue !== previousValue) {
this.#eventPayloadCache.set(handler, newValue);
handler(newValue, previousValue);
}
} else {
(handler as GenericEventHandler)(...payload);
}
} catch (error) {
// Capture error without interrupting the event publishing.
if (this.captureException) {
this.captureException(
error instanceof Error ? error : new Error(String(error)),
);
} else {
console.error(error);
}
}
}
}
}
/**
* Subscribe to an event.
*
* Registers the given function as an event handler for the given event type.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param handler - The event handler. The type of the parameters for this event handler must
* match the type of the payload for this event type.
* @template EventType - A type union of Event type strings.
*/
subscribe<EventType extends Event['type']>(
eventType: EventType,
handler: ExtractEventHandler<Event, EventType>,
): void;
/**
* Subscribe to an event, with a selector.
*
* Registers the given handler function as an event handler for the given
* event type. When an event is published, its payload is first passed to the
* selector. The event handler is only called if the selector's return value
* differs from its last known return value.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param handler - The event handler. The type of the parameters for this event
* handler must match the return type of the selector.
* @param selector - The selector function used to select relevant data from
* the event payload. The type of the parameters for this selector must match
* the type of the payload for this event type.
* @template EventType - A type union of Event type strings.
* @template SelectorReturnValue - The selector return value.
*/
subscribe<EventType extends Event['type'], SelectorReturnValue>(
eventType: EventType,
handler: SelectorEventHandler<SelectorReturnValue>,
selector: SelectorFunction<Event, EventType, SelectorReturnValue>,
): void;
subscribe<EventType extends Event['type'], SelectorReturnValue>(
eventType: EventType,
handler:
| ExtractEventHandler<Event, EventType>
| SelectorEventHandler<SelectorReturnValue>,
selector?: SelectorFunction<Event, EventType, SelectorReturnValue>,
): void {
// Widen type of event handler by dropping ReturnType parameter.
//
// We need to drop it here because it's used as the parameter to the event handler, and
// functions in general are contravariant over the parameter type. This means the type is no
// longer valid once it's added to a broader type union with other handlers (because as far
// as TypeScript knows, we might call the handler with output from a different selector).
//
// This cast means the type system is not guaranteeing the handler is called with the matching
// input selector return value. The parameter types do ensure they match when `subscribe` is
// called, but past that point we need to make sure of that with manual review and tests
// instead.
const widenedHandler = handler as
| ExtractEventHandler<Event, EventType>
| SelectorEventHandler;
this.#subscribe(eventType, widenedHandler, { delegation: false, selector });
if (selector) {
const getPayload = this.#initialEventPayloadGetters.get(eventType);
if (getPayload) {
const initialValue = selector(...getPayload());
this.#eventPayloadCache.set(widenedHandler, initialValue);
}
}
}
/**
* Subscribe to an event.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param handler - The event handler. The type of the parameters for this event handler must
* match the type of the payload for this event type.
* @param metadata - Event metadata.
* @template SubscribedEvent - The event being subscribed to.
* @template SelectorReturnValue - The selector return value.
*/
#subscribe<SubscribedEvent extends EventConstraint>(
eventType: SubscribedEvent['type'],
handler:
| ExtractEventHandler<SubscribedEvent, SubscribedEvent['type']>
| SelectorEventHandler,
metadata: SubscriptionMetadata<SubscribedEvent>,
): void {
let subscribers = this.#events.get(eventType);
if (!subscribers) {
subscribers = new Map();
this.#events.set(eventType, subscribers);
}
subscribers.set(handler, metadata);
}
/**
* Subscribe to an event, with a selector, invoking the handler exactly once.
*
* Registers the given handler function as an event handler for the given
* event type. When an event is published, its payload is first passed to the
* selector. The event handler is only called if the selector's return value
* differs from its last known return value. Additionally if the optional condition
* function is provided, it is checked whether it returns `true`.
* The handler is invoked at most once, after which the subscription is removed.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param handler - The event handler. The type of the parameters for this event
* handler must match the return type of the selector.
* @param options - Options bag.
* @param options.selector - The selector function used to select relevant data
* from the event payload. The type of the parameters for this selector must
* match the type of the payload for this event type.
* @param options.condition - An optional predicate evaluated against the
* selector's return value. The handler is only invoked when this returns `true`.
* @template EventType - A type union of Event type strings.
* @template SelectorReturnValue - The selector return value.
* @example
* ```typescript
* messenger.subscribeOnce(
* 'TransactionController:transactionConfirmed',
* (hash) => { ... },
* { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },
* );
* ```
*/
subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(
eventType: EventType,
handler: SelectorEventHandler<SelectorReturnValue>,
options: {
selector: SelectorFunction<Event, EventType, SelectorReturnValue>;
condition?: (value: SelectorReturnValue) => boolean;
},
): void;
/**
* Subscribe to an event, invoking the handler exactly once.
*
* Registers the given function as an event handler for the given event type
* and automatically unsubscribes after the first invocation.
*
* If `options.condition` is provided, the handler is only invoked (and the
* subscription only removed) when the condition returns `true`.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param handler - The event handler. The type of the parameters for this event
* handler must match the type of the payload for this event type.
* @param options - Options bag.
* @param options.condition - A predicate evaluated against the event payload.
* The handler is only invoked when this returns `true`.
* @template EventType - A type union of Event type strings.
* @example
* ```typescript
* messenger.subscribeOnce(
* 'TransactionController:transactionConfirmed',
* (tx) => { ... },
* { condition: (tx) => tx.hash === 'foo' },
* );
* ```
*/
subscribeOnce<EventType extends Event['type']>(
eventType: EventType,
handler: ExtractEventHandler<Event, EventType>,
options?: {
condition?: (
...payload: ExtractEventPayload<Event, EventType>
) => boolean;
},
): void;
subscribeOnce<EventType extends Event['type'], SelectorReturnValue>(
eventType: EventType,
handler:
| ExtractEventHandler<Event, EventType>
| SelectorEventHandler<SelectorReturnValue>,
options?: {
selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;
condition?:
| ((...payload: ExtractEventPayload<Event, EventType>) => boolean)
| ((value: SelectorReturnValue) => boolean);
},
): void {
const { selector, condition } = options ?? {};
// Casting to unknown to handle both the code path where a selector is defined and where it is omitted.
const internalHandler = (...args: unknown[]): void => {
if (
condition &&
!(condition as (...args: unknown[]) => boolean)(...args)
) {
return;
}
this.unsubscribe(eventType, internalHandler);
(handler as (...args: unknown[]) => void)(...args);
};
this.subscribe(
eventType,
internalHandler,
selector as SelectorFunction<Event, EventType, SelectorReturnValue>,
);
}
/**
* Return a promise that resolves the next time the selector's return value
* changes and, if provided, the `options.condition` predicate returns `true`.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param options - Options bag.
* @param options.selector - The selector function used to select relevant data
* from the event payload.
* @param options.condition - An optional predicate evaluated against the
* selector's return value. The promise only resolves when this returns `true`.
* @template EventType - A type union of Event type strings.
* @template SelectorReturnValue - The selector return value.
* @returns A promise that resolves with the selector's return value.
* @example
* ```typescript
* const [hash] = await messenger.waitUntil(
* 'TransactionController:transactionConfirmed',
* { selector: (tx) => tx.hash, condition: (hash) => hash === 'foo' },
* );
* ```
*/
waitUntil<EventType extends Event['type'], SelectorReturnValue>(
eventType: EventType,
options: {
selector: SelectorFunction<Event, EventType, SelectorReturnValue>;
condition?: (value: SelectorReturnValue) => boolean;
},
): Promise<[SelectorReturnValue, SelectorReturnValue | undefined]>;
/**
* Return a promise that resolves the next time the given event is published.
*
* If `options.condition` is provided, the promise only resolves when the
* condition returns `true`.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param options - Options bag.
* @param options.condition - A predicate evaluated against the event payload.
* The promise only resolves when this returns `true`.
* @template EventType - A type union of Event type strings.
* @returns A promise that resolves with the event payload.
* @example
* ```typescript
* const [transactionMeta] = await messenger.waitUntil(
* 'TransactionController:transactionConfirmed',
* { condition: (tx) => tx.hash === 'foo' },
* );
* ```
* @example
* ```typescript
* await messenger.waitUntil('KeyringController:unlock');
* ```
*/
waitUntil<EventType extends Event['type']>(
eventType: EventType,
options?: {
condition?: (
...payload: ExtractEventPayload<Event, EventType>
) => boolean;
},
): Promise<ExtractEventPayload<Event, EventType>>;
waitUntil<EventType extends Event['type'], SelectorReturnValue>(
eventType: EventType,
options?: {
selector?: SelectorFunction<Event, EventType, SelectorReturnValue>;
condition?:
| ((...payload: ExtractEventPayload<Event, EventType>) => boolean)
| ((value: SelectorReturnValue) => boolean);
},
): Promise<SelectorReturnValue | ExtractEventPayload<Event, EventType>[0]> {
return new Promise((resolve) => {
this.subscribeOnce(
eventType,
(...args) => resolve(args),
options as {
selector: SelectorFunction<Event, EventType, SelectorReturnValue>;
condition?: (value: SelectorReturnValue) => boolean;
},
);
});
}
/**
* Unsubscribe from an event.
*
* Unregisters the given function as an event handler for the given event.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @param handler - The event handler to unregister.
* @throws Will throw when the given event handler is not registered for this event.
* @template EventType - A type union of Event type strings.
* @template SelectorReturnValue - The selector return value.
*/
unsubscribe<EventType extends Event['type'], SelectorReturnValue = unknown>(
eventType: EventType,
handler:
| ExtractEventHandler<Event, EventType>
| SelectorEventHandler<SelectorReturnValue>,
): void {
const subscribers = this.#events.get(eventType);
// Widen type of event handler by dropping ReturnType parameter.
//
// We need to drop it here because it's used as the parameter to the event handler, and
// functions in general are contravariant over the parameter type. This means the type is no
// longer valid once it's added to a broader type union with other handlers (because as far
// as TypeScript knows, we might call the handler with output from a different selector).
//
// This poses no risk in this case, since we never call the handler past this point.
const widenedHandler = handler as
| ExtractEventHandler<Event, EventType>
| SelectorEventHandler;
if (!subscribers) {
throw new Error(`Subscription not found for event: ${eventType}`);
}
const metadata = subscribers.get(widenedHandler);
if (!metadata) {
throw new Error(`Subscription not found for event: ${eventType}`);
}
if (metadata.selector) {
this.#eventPayloadCache.delete(widenedHandler);
}
subscribers.delete(widenedHandler);
}
/**
* Clear subscriptions for a specific event.
*
* This will remove all subscribed handlers for this event registered from this messenger. The
* event may still have subscribers if it has been delegated to another messenger.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @template EventType - A type union of Event type strings.
*/
clearEventSubscriptions<EventType extends Event['type']>(
eventType: EventType,
): void {
const subscriptions = this.#events.get(eventType);
if (!subscriptions) {
return;
}
for (const [handler, metadata] of subscriptions.entries()) {
if (metadata.delegation) {
continue;
}
subscriptions.delete(handler);
}
if (subscriptions.size === 0) {
this.#events.delete(eventType);
}
}
/**
* Clear all subscriptions.
*
* This will remove all subscribed handlers for all events registered from this messenger. Events
* may still have subscribers if they are delegated to another messenger.
*/
clearSubscriptions(): void {
for (const eventType of this.#events.keys()) {
this.clearEventSubscriptions(eventType);
}
}
/**
* Delegate actions and/or events to another messenger.
*
* The messenger these actions/events are delegated to will be able to call these actions and
* subscribe to these events.
*
* Note that the messenger these actions/events are delegated to must still have these
* actions/events included in its type definition (as part of the Action and Event type
* parameters). Actions and events are statically type checked, they cannot be delegated
* dynamically at runtime.
*
* @param args - Arguments.
* @param args.actions - The action types to delegate.
* @param args.events - The event types to delegate.
* @param args.messenger - The messenger to delegate to.
* @template Delegatee - The messenger the actions/events are delegated to.
* @template DelegatedActions - An array of delegated action types.
* @template DelegatedEvents - An array of delegated event types.
*/
delegate<
Delegatee extends Messenger<string, ActionConstraint, EventConstraint>,
DelegatedActions extends (MessengerActions<Delegatee>['type'] &
Action['type'])[],
DelegatedEvents extends (MessengerEvents<Delegatee>['type'] &
Event['type'])[],
>({
actions,
events,
messenger,
}: {
actions?: DelegatedActions;
events?: DelegatedEvents;
messenger: Delegatee;
}): void {
for (const actionType of actions ?? []) {
const delegatedActionHandler = (
...args: ExtractActionParameters<
MessengerActions<Delegatee> & Action,
typeof actionType
>
): ExtractActionResponse<
MessengerActions<Delegatee> & Action,
typeof actionType
> => {
// Cast to get more specific type, for this specific action
// The types get collapsed by `this.#actions`
const actionHandler = this.getAction(actionType) as
| ActionHandler<
MessengerActions<Delegatee> & Action,
typeof actionType