-
-
Notifications
You must be signed in to change notification settings - Fork 168
/
ControllerMessenger.ts
627 lines (583 loc) · 21.9 KB
/
ControllerMessenger.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
type ActionHandler<Action, ActionType> = (
...args: ExtractActionParameters<Action, ActionType>
) => ExtractActionResponse<Action, ActionType>;
type ExtractActionParameters<Action, T> = Action extends {
type: T;
handler: (...args: infer H) => any;
}
? H
: never;
type ExtractActionResponse<Action, T> = Action extends {
type: T;
handler: (...args: any) => infer H;
}
? H
: never;
type ExtractEventHandler<Event, T> = Event extends { type: T; payload: infer P }
? P extends unknown[]
? (...payload: P) => void
: never
: never;
type ExtractEventPayload<Event, T> = Event extends { type: T; payload: infer P }
? P
: never;
type GenericEventHandler = (...args: unknown[]) => void;
type SelectorFunction<Args extends unknown[], ReturnValue> = (
...args: Args
) => ReturnValue;
type SelectorEventHandler<SelectorReturnValue> = (
newValue: SelectorReturnValue,
previousValue: SelectorReturnValue | undefined,
) => void;
export type ActionConstraint = {
type: string;
handler: (...args: any) => unknown;
};
export type EventConstraint = { type: string; payload: unknown[] };
type EventSubscriptionMap = Map<
GenericEventHandler | SelectorEventHandler<unknown>,
SelectorFunction<any, unknown> | undefined
>;
/**
* A namespaced string
*
* This type verifies that the string T is prefixed by the string Name followed by a colon.
*
* @template Name - The namespace we're checking for.
* @template T - The full string, including the namespace.
*/
export type Namespaced<Name extends string, T> = T extends `${Name}:${string}`
? T
: never;
type NarrowToNamespace<T, Namespace extends string> = T extends {
type: `${Namespace}:${string}`;
}
? T
: never;
type NarrowToAllowed<T, Allowed extends string> = T extends {
type: Allowed;
}
? T
: never;
/**
* A restricted controller messenger.
*
* This acts as a wrapper around the controller messenger instance that restricts access to actions
* and events.
*
* @template N - The namespace for this messenger. Typically this is the name of the controller or
* module that this messenger has been created for. The authority to publish events and register
* actions under this namespace is granted to this restricted messenger instance.
* @template Action - A type union of all Action types.
* @template Event - A type union of all Event types.
* @template AllowedAction - A type union of the 'type' string for any allowed actions.
* @template AllowedEvent - A type union of the 'type' string for any allowed events.
*/
export class RestrictedControllerMessenger<
N extends string,
Action extends ActionConstraint,
Event extends EventConstraint,
AllowedAction extends string,
AllowedEvent extends string,
> {
private controllerMessenger: ControllerMessenger<
ActionConstraint,
EventConstraint
>;
private controllerName: N;
private allowedActions: AllowedAction[] | null;
private allowedEvents: AllowedEvent[] | null;
/**
* Constructs a restricted controller messenger
*
* The provided allowlists grant the ability to call the listed actions and subscribe to the
* listed events. The "name" provided grants ownership of any actions and events under that
* namespace. Ownership allows registering actions and publishing events, as well as
* unregistering actions and clearing event subscriptions.
*
* @param options - The controller options.
* @param options.controllerMessenger - The controller messenger instance that is being wrapped.
* @param options.name - The name of the thing this messenger will be handed to (e.g. the
* controller name). This grants "ownership" of actions and events under this namespace to the
* restricted controller messenger returned.
* @param options.allowedActions - The list of actions that this restricted controller messenger
* should be alowed to call.
* @param options.allowedEvents - The list of events that this restricted controller messenger
* should be allowed to subscribe to.
*/
constructor({
controllerMessenger,
name,
allowedActions,
allowedEvents,
}: {
controllerMessenger: ControllerMessenger<ActionConstraint, EventConstraint>;
name: N;
allowedActions?: AllowedAction[];
allowedEvents?: AllowedEvent[];
}) {
this.controllerMessenger = controllerMessenger;
this.controllerName = name;
this.allowedActions = allowedActions || null;
this.allowedEvents = allowedEvents || null;
}
/**
* Register an action handler.
*
* This will make the registered function available to call via the `call` method.
*
* The action type this handler is registered under *must* be in the current namespace.
*
* @param action - The action type. This is a unqiue 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 T - A type union of Action type strings that are namespaced by N.
*/
registerActionHandler<T extends Namespaced<N, Action['type']>>(
action: T,
handler: ActionHandler<Action, T>,
) {
/* istanbul ignore if */ // Branch unreachable with valid types
if (!action.startsWith(`${this.controllerName}:`)) {
throw new Error(
`Only allowed registering action handlers prefixed by '${this.controllerName}:'`,
);
}
this.controllerMessenger.registerActionHandler(action, handler);
}
/**
* Unregister an action handler.
*
* This will prevent this action from being called.
*
* The action type being unregistered *must* be in the current namespace.
*
* @param action - The action type. This is a unqiue identifier for this action.
* @template T - A type union of Action type strings that are namespaced by N.
*/
unregisterActionHandler<T extends Namespaced<N, Action['type']>>(action: T) {
/* istanbul ignore if */ // Branch unreachable with valid types
if (!action.startsWith(`${this.controllerName}:`)) {
throw new Error(
`Only allowed unregistering action handlers prefixed by '${this.controllerName}:'`,
);
}
this.controllerMessenger.unregisterActionHandler(action);
}
/**
* Call an action.
*
* This function will call the action handler corresponding to the given action type, passing
* along any parameters given.
*
* The action type being called must be on the action allowlist.
*
* @param action - The action type. This is a unqiue 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 T - A type union of allowed Action type strings.
* @returns The action return value.
*/
call<T extends AllowedAction & string>(
action: T,
...params: ExtractActionParameters<Action, T>
): ExtractActionResponse<Action, T> {
/* istanbul ignore next */ // Branches unreachable with valid types
if (this.allowedActions === null) {
throw new Error('No actions allowed');
} else if (!this.allowedActions.includes(action)) {
throw new Error(`Action missing from allow list: ${action}`);
}
return this.controllerMessenger.call(action, ...params);
}
/**
* Publish an event.
*
* Publishes the given payload to all subscribers of the given event type.
*
* The event type being published *must* be in the current namespace.
*
* @param event - 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 E - A type union of Event type strings that are namespaced by N.
*/
publish<E extends Namespaced<N, Event['type']>>(
event: E,
...payload: ExtractEventPayload<Event, E>
) {
/* istanbul ignore if */ // Branch unreachable with valid types
if (!event.startsWith(`${this.controllerName}:`)) {
throw new Error(
`Only allowed publishing events prefixed by '${this.controllerName}:'`,
);
}
this.controllerMessenger.publish(event, ...payload);
}
/**
* Subscribe to an event.
*
* Registers the given function as an event handler for the given event type.
*
* The event type being subscribed to must be on the event allowlist.
*
* @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 E - A type union of Event type strings.
*/
subscribe<E extends AllowedEvent & string>(
eventType: E,
handler: ExtractEventHandler<Event, E>,
): 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.
*
* The event type being subscribed to must be on the event allowlist.
*
* @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 E - A type union of Event type strings.
* @template V - The selector return value.
*/
subscribe<E extends AllowedEvent & string, V>(
eventType: E,
handler: SelectorEventHandler<V>,
selector: SelectorFunction<ExtractEventPayload<Event, E>, V>,
): void;
subscribe<E extends AllowedEvent & string, V>(
event: E,
handler: ExtractEventHandler<Event, E>,
selector?: SelectorFunction<ExtractEventPayload<Event, E>, V>,
) {
/* istanbul ignore next */ // Branches unreachable with valid types
if (this.allowedEvents === null) {
throw new Error('No events allowed');
} else if (!this.allowedEvents.includes(event)) {
throw new Error(`Event missing from allow list: ${event}`);
}
if (selector) {
return this.controllerMessenger.subscribe(event, handler, selector);
}
return this.controllerMessenger.subscribe(event, handler);
}
/**
* Unsubscribe from an event.
*
* Unregisters the given function as an event handler for the given event.
*
* The event type being unsubscribed to must be on the event allowlist.
*
* @param event - 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 T - A type union of allowed Event type strings.
*/
unsubscribe<E extends AllowedEvent & string>(
event: E,
handler: ExtractEventHandler<Event, E>,
) {
/* istanbul ignore next */ // Branches unreachable with valid types
if (this.allowedEvents === null) {
throw new Error('No events allowed');
} else if (!this.allowedEvents.includes(event)) {
throw new Error(`Event missing from allow list: ${event}`);
}
this.controllerMessenger.unsubscribe(event, handler);
}
/**
* Clear subscriptions for a specific event.
*
* This will remove all subscribed handlers for this event.
*
* The event type being cleared *must* be in the current namespace.
*
* @param event - The event type. This is a unique identifier for this event.
* @template E - A type union of Event type strings that are namespaced by N.
*/
clearEventSubscriptions<E extends Namespaced<N, Event['type']>>(event: E) {
/* istanbul ignore if */ // Branch unreachable with valid types
if (!event.startsWith(`${this.controllerName}:`)) {
throw new Error(
`Only allowed clearing events prefixed by '${this.controllerName}:'`,
);
}
this.controllerMessenger.clearEventSubscriptions(event);
}
}
/**
* A messaging system for controllers.
*
* The controller 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.
*
* @template Action - A type union of all Action types.
* @template Event - A type union of all Event types.
*/
export class ControllerMessenger<
Action extends ActionConstraint,
Event extends EventConstraint,
> {
private actions = new Map<Action['type'], unknown>();
private events = new Map<Event['type'], EventSubscriptionMap>();
/**
* A cache of selector return values for their respective handlers.
*/
private eventPayloadCache = new Map<
GenericEventHandler,
unknown | undefined
>();
/**
* Register an action handler.
*
* This will make the registered function available to call via the `call` method.
*
* @param actionType - The action type. This is a unqiue 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 T - A type union of Action type strings.
*/
registerActionHandler<T extends Action['type']>(
actionType: T,
handler: ActionHandler<Action, T>,
) {
if (this.actions.has(actionType)) {
throw new Error(
`A handler for ${actionType} has already been registered`,
);
}
this.actions.set(actionType, handler);
}
/**
* Unregister an action handler.
*
* This will prevent this action from being called.
*
* @param actionType - The action type. This is a unqiue identifier for this action.
* @template T - A type union of Action type strings.
*/
unregisterActionHandler<T extends Action['type']>(actionType: T) {
this.actions.delete(actionType);
}
/**
* Unregister all action handlers.
*
* This prevents all actions from being called.
*/
clearActions() {
this.actions.clear();
}
/**
* 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 unqiue 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 T - A type union of Action type strings.
* @returns The action return value.
*/
call<T extends Action['type']>(
actionType: T,
...params: ExtractActionParameters<Action, T>
): ExtractActionResponse<Action, T> {
const handler = this.actions.get(actionType) as ActionHandler<Action, T>;
if (!handler) {
throw new Error(`A handler for ${actionType} has not been registered`);
}
return handler(...params);
}
/**
* Publish an event.
*
* Publishes the given payload to all subscribers of the given event type.
*
* @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 E - A type union of Event type strings.
*/
publish<E extends Event['type']>(
eventType: E,
...payload: ExtractEventPayload<Event, E>
) {
const subscribers = this.events.get(eventType);
if (subscribers) {
for (const [handler, selector] of subscribers.entries()) {
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);
}
}
}
}
/**
* 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 E - A type union of Event type strings.
*/
subscribe<E extends Event['type']>(
eventType: E,
handler: ExtractEventHandler<Event, E>,
): 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 E - A type union of Event type strings.
* @template V - The selector return value.
*/
subscribe<E extends Event['type'], V>(
eventType: E,
handler: SelectorEventHandler<V>,
selector: SelectorFunction<ExtractEventPayload<Event, E>, V>,
): void;
subscribe<E extends Event['type'], V>(
eventType: E,
handler: ExtractEventHandler<Event, E>,
selector?: SelectorFunction<ExtractEventPayload<Event, E>, V>,
): void {
let subscribers = this.events.get(eventType);
if (!subscribers) {
subscribers = new Map();
this.events.set(eventType, subscribers);
}
subscribers.set(handler, selector);
}
/**
* 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 E - A type union of Event type strings.
*/
unsubscribe<E extends Event['type']>(
eventType: E,
handler: ExtractEventHandler<Event, E>,
) {
const subscribers = this.events.get(eventType);
if (!subscribers || !subscribers.has(handler)) {
throw new Error(`Subscription not found for event: ${eventType}`);
}
const selector = subscribers.get(handler);
if (selector) {
this.eventPayloadCache.delete(handler);
}
subscribers.delete(handler);
}
/**
* Clear subscriptions for a specific event.
*
* This will remove all subscribed handlers for this event.
*
* @param eventType - The event type. This is a unique identifier for this event.
* @template E - A type union of Event type strings.
*/
clearEventSubscriptions<E extends Event['type']>(eventType: E) {
this.events.delete(eventType);
}
/**
* Clear all subscriptions.
*
* This will remove all subscribed handlers for all events.
*/
clearSubscriptions() {
this.events.clear();
}
/**
* Get a restricted controller messenger
*
* Returns a wrapper around the controller messenger instance that restricts access to actions
* and events. The provided allowlists grant the ability to call the listed actions and subscribe
* to the listed events. The "name" provided grants ownership of any actions and events under
* that namespace. Ownership allows registering actions and publishing events, as well as
* unregistering actions and clearing event subscriptions.
*
* @param options - Controller messenger options.
* @param options.name - The name of the thing this messenger will be handed to (e.g. the
* controller name). This grants "ownership" of actions and events under this namespace to the
* restricted controller messenger returned.
* @param options.allowedActions - The list of actions that this restricted controller messenger
* should be alowed to call.
* @param options.allowedEvents - The list of events that this restricted controller messenger
* should be allowed to subscribe to.
* @template N - The namespace for this messenger. Typically this is the name of the controller or
* module that this messenger has been created for. The authority to publish events and register
* actions under this namespace is granted to this restricted messenger instance.
* @template AllowedAction - A type union of the 'type' string for any allowed actions.
* @template AllowedEvent - A type union of the 'type' string for any allowed events.
* @returns The restricted controller messenger.
*/
getRestricted<
N extends string,
AllowedAction extends string,
AllowedEvent extends string,
>({
name,
allowedActions,
allowedEvents,
}: {
name: N;
allowedActions?: Extract<Action['type'], AllowedAction>[];
allowedEvents?: Extract<Event['type'], AllowedEvent>[];
}): RestrictedControllerMessenger<
N,
NarrowToNamespace<Action, N> | NarrowToAllowed<Action, AllowedAction>,
NarrowToNamespace<Event, N> | NarrowToAllowed<Event, AllowedEvent>,
AllowedAction,
AllowedEvent
> {
return new RestrictedControllerMessenger<
N,
NarrowToNamespace<Action, N> | NarrowToAllowed<Action, AllowedAction>,
NarrowToNamespace<Event, N> | NarrowToAllowed<Event, AllowedEvent>,
AllowedAction,
AllowedEvent
>({
controllerMessenger: this,
name,
allowedActions,
allowedEvents,
});
}
}